Sunday, January 5, 2014

codechef NOTATRI - "not a triangle" solution

codechef NOTATRI - "not a triangle": http://www.codechef.com/problems/NOTATRI

codechef NOTATRI - "not a triangle" solution: http://ideone.com/ymrXXE

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;

int cmp(const void *a, const void *b) {
return (*(int*)a-*(int*)b);
}

int main() {
int n, l[2000], cnt, i, j, k;
scanf("%d", &n);
while(n) {
cnt=0;
for(i=0; i<n; i++) scanf("%d", &l[i]);
qsort(l, n, sizeof(int), cmp);
for(k=n-1; k>1; k--) {
i=0; j=k-1;
while(i<j) {
if(l[k]>(l[i]+l[j])) { cnt+=j-i; i++; }
else j--;
}
}
printf("%d\n", cnt);
scanf("%d", &n);
}
return 0;
}

codechef NOTATRI - "not a triangle" guidance: 

sorting will help in terms of time. after sorting, start from the greatest value of length, if sum of smallest value and value lesser than(l[k-1]) taken value(l[k]), then add difference to count(cnt=cnt+l[k-1]-l[i]), because sum of all indices between those numbers, if considered particularly, will be lesser than taken value(l[k]). if sum of those two particular indices is greater than or equal to taken value(l[i]+l[j]>=l[k]), then increment the smallest index(i++). loop the aforementioned case for all index. voila.

No comments:

Post a Comment