51 Nod 2497-half the number of triangles

B contains only a small non-negative integer array a, she would like to know how many triples (i, j, k), satisfy i <j <k and a [i], a [j], a [k ] may be used as three sides of a triangle side lengths.

 

Entry

The first input line of a positive integer n, a represents the number of elements in the array; 
second row non-negative integer n, a represents the elements, separated by a space; 
wherein 0 <n≤1000, any element in a a [i ] satisfying 0≤a [i] ≤1000.

Export

A number triple the number of output, the meaning of the title is satisfied by

SAMPLE INPUT

4
2 2 3 4

Sample Output

3 


it is easy to think of an O (n ^ 2 * logn) of the solution, we drained after the original array sequence, enumerated two smaller sides, and two separated can range longest side;
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<set>
#include<map>
using namespace std;
#define maxn 100005
#define rdint(x) scanf("%d",&x)
typedef long long ll;

int n;
int a[1002];
int main() {
	rdint(n);
	for (int i = 1; i <= n; i++)rdint(a[i]);
	int tot = 0;
	sort(a + 1, a + 1 + n);
//	int nn = unique(a + 1, a + 1 + n) - (a + 1);
	for (int i = 1; i < n; i++) {
		for (int j = i + 1; j < n; j++) {
			int l = j + 1;
			int r = n;
			int ans1 = -1;
			while (l <= r) {
				int mid = (l + r) / 2;
				if (a[mid] > (a[j] - a[i])) {
					r = mid - 1; ans1 = mid;
				}
				else {
					l = mid + 1;
				}
			}
			ans1 = upper_bound(a + 1 + j + 1, a + 1 + n, a[j] - a[i]) - (a + 1);
			l = j + 1; r = n;
			int ans2 = -1;
			ans2 = lower_bound(a + 1 + j + 1, a + 1 + n, a[i] + a[j]) - (a + 1);
//			cout << ans1 << ' ' << ans2 <<' '<< a[i] + a[j] << endl;
			if (ans1 == -1 || ans2 == -1)continue;
//			tot += (ans2 - ans1 + 1);

			
			else if (ans2 == ans1 && a[ans1] > a[i] + a[j]) {
				tot += 0;
			}
			else if (ans2 == ans1 && a[ans2] < a[i] + a[j]) {
//				cout << 2 << endl;
				tot += (ans2 - ans1 + 1);
			}
			else if (ans2 > ans1 && a[ans2]<a[i]+a[j]) {
				tot += (ans2 - ans1 + 1);
			}
			else if (ans2 > ans1&& a[ans2] >= a[i] + a[j]) {
				tot += (ans2 - ans1);
			}
		}
	}
	printf("%d\n", tot);
//	system("pause");
}

  

 
 

Guess you like

Origin www.cnblogs.com/zxyqzy/p/11116181.html