找出一个数组中的三个数,三个数不能组成三角形。
三个数不能组成三角形的条件是:a + b < c
两边和小于第三边。
这个问题属于三个数的组合问题了。暴力法可解,可是时间效率就是O(n*n*n)了,非常慢。
只是既然是组合问题就必然能够使用排序后处理的方法减少时间效率的。
这里减少时间效率的方法是:
选一个最大的数c。然后选两个小数a和b,当中a < b,假设符合条件,那么两个数中间的数必然都能够作为b符合条件a + b < c
这样能够把时间效率降到O(n*n)。
这个规律也不好找啊。要很认真观察。然后总结出来。
处理一个数组,要从小到大。从大到小重复观察。寻找其规律。
原题:http://www.codechef.com/problems/NOTATRI/
#include <stdio.h> #include <stdlib.h> #include <algorithm> using std::sort; class NotATriangle { //细心找出其规律进行优化 int getNotTris_3(int *A, const int n) { sort(A, A+n); int i = 0, j = 1, k = n-1, ans = 0; for ( ; k >= 2; k--) { i = 0, j = k-1; while (i < j) { if (A[i] + A[j] < A[k]) { ans += j - i; i++; } else j--; } } return ans; } public: NotATriangle() { int N = 0; while (scanf("%d", &N) && 0 != N) { int *A = (int *) malloc(sizeof(int)* N); for (int i = 0; i < N; i++) { scanf("%d", &A[i]); } printf("%d ", getNotTris_3(A, N)); free(A); } } }; int notATriangle() { NotATriangle ntir; return 0; }