poj 2785 4 Values whose Sum is 0
二分枚举;
也可以将两个和数组都排序,这样可以在查找时保持沿一个方向,最坏情况下复杂度为O(n),不如二分查找;
计算cpd[]时,c[i] + d[j]错写成c[i]+d[i]查了半天才发现。。。
1 # include <stdio.h>
2 # include <stdlib.h>
3
4 # define MAXN 4001
5
6 int apb[MAXN*MAXN], cpd[MAXN*MAXN];
7 int a[MAXN], b[MAXN], c[MAXN], d[MAXN];
8
9 int cmp(const void *a, const void *b)
10 {
11 return (*(int *)a - *(int *)b);
12 }
13
14 int bin_search(int *a, int key, int n);
15
16 int main()
17 {
18 int n, i, j, ans, t;
19
20 while (~scanf("%d", &n))
21 {
22 for (i = 0; i < n; ++i)
23 scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);
24 for (i = 0; i < n; ++i)
25 for (j = 0; j < n; ++j)
26 {
27 apb[i*n + j] = a[i] + b[j];
28 cpd[i*n + j] = c[i] + d[j];
29 }
30 qsort(apb, n*n, sizeof(int), cmp);
31 t = n*n;
32 for (ans = i = 0; i < t; ++i)
33 ans += bin_search(apb, -cpd[i], t);
34 printf("%d\n", ans);
35 }
36
37 return 0;
38 }
39
40 int bin_search(int *a, int key, int n)
41 {
42 int cnt, up, low, mid, t;
43
44 cnt = 0;
45 up = n-1;
46 low = 0;
47 while (low <= up)
48 {
49 mid = (up + low) >> 1;
50 if (key == a[mid]) break;
51 if (key < a[mid]) up = mid - 1;
52 else low = mid + 1;
53 }
54 if (key == a[mid])
55 {
56 ++cnt;
57 t = mid;
58 while (t > 0 && key == a[--t]) ++cnt;
59 while (mid < n-1 && key == a[++mid]) ++cnt;
60 }
61 return cnt;
62 }