POJ-2785

 

The SUM problem can be formulated as follows: given four lists A, B, C, D of integer values, compute how many quadruplet (a, b, c, d ) ∈ A x B x C x D are such that a + b + c + d = 0 . In the following, we assume that all lists have the same size n .

Input

The first line of the input file contains the size of the lists n (this value can be as large as 4000). We then have n lines containing four integer values (with absolute value as large as 2 28 ) that belong respectively to A, B, C and D .

Output

For each input file, your program has to write the number quadruplets whose sum is zero.

Sample Input

6
-45 22 42 -16
-41 -27 56 30
-36 53 -37 77
-36 30 -75 -46
26 -38 -10 62
-32 -54 -6 45

Sample Output

5

Hint

Sample Explanation: Indeed, the sum of the five following quadruplets is zero: (-45, -27, 42, 30), (26, 30, -10, -46), (-32, 22, 56, -46),(-32, 30, -75, 77), (-32, -54, 56, 30).

 

 

题意:就是给你4组数,然后让你在每组数里面找一个数,使其4个数和为零。问你有多少组。

题解:可以没两组数相加,和成两个数组,对其中一个数组排序。遍历两个数组(二分法,否则会TE),找相加为零的有多少组。

AC代码为:

 

 1 #include <cstdio>  
 2 #include <iostream>  
 3 #include <cstring>  
 4 #include <algorithm>  
 5 using namespace std;
 6 
 7 
 8 int sum1[16000005], sum2[16000005];
 9 
10 
11 int main()
12 {
13 int n, mid;
14 
15 scanf("%d", &n);
16 
17 int a[n][4];
18 for (int i = 0; i<n; i++)
19 {
20 scanf("%d%d%d%d", &a[i][0], &a[i][1], &a[i][2], &a[i][3]);
21 }
22 
23 int k = 0;
24 int m = 0;
25 for (int i = 0; i<n; i++)
26 for (int j = 0; j<n; j++)
27 {
28 sum1[k++] = a[i][0] + a[j][1];
29 sum2[m++] = a[i][2] + a[j][3];
30 }
31 
32 sort(sum2, sum2 + m);
33 int cnt = 0;
34 
35 for (int i = 0; i<k; i++)
36 {
37 int left = 0;
38 int right = k - 1;
39 
40 while (left <= right)
41 {
42 mid = (left + right) / 2;
43 if (sum1[i] + sum2[mid] == 0)
44 {
45 cnt++;
46 for (int j = mid + 1; j<k; j++)
47 {
48 if (sum1[i] + sum2[j] != 0)
49 break;
50 else
51 cnt++;
52 }
53 for (int j = mid - 1; j >= 0; j--)
54 {
55 if (sum1[i] + sum2[j] != 0)
56 break;
57 else
58 cnt++;
59 }
60 break;
61 }
62 
63 if (sum1[i] + sum2[mid]<0)
64 left = mid + 1;
65 else
66 right = mid - 1;
67 }
68 }
69 cout<<cnt<<endl;
70 
71 return 0;
72 }
View Code

 

posted @ 2018-01-29 20:52  StarHai  阅读(412)  评论(0编辑  收藏  举报