POJ-2785-4 Values whose Sum is 0
4 Values whose Sum is 0
Description
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 228 ) 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
4
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
5
-56 45 34 78
-34 -67 45 -23
-12 -34 -56 46
45 34 -32 8
-23 -56 4 53
Sample Output
5
256
11
分析:
四列数字,然后给出每组的长度,从每组中抽出一个数字,满足这四个数字和是0的情况的总数。
1. 四列数字一个一个每组不存在,会超时。
2.先求出两列数字,(4000*4000种结果)然后对其中一种排序。
2.二分查找,找到一种算一种,还要考虑找到的周围有没有相等的,两个方向检测一下。
1 #include <bits/stdc++.h> 2 using namespace std; 3 int a[4001][4]; 4 int sum1[16000002]; 5 int sum2[16000002]; 6 int main() 7 { 8 int n,mid; 9 while(~scanf("%d",&n)) 10 { 11 for(int i=0;i<n;i++) 12 { 13 scanf("%d%d%d%d",&a[i][0],&a[i][1],&a[i][2],&a[i][3]); 14 } 15 int k = 0; 16 int m = 0; 17 for(int i=0;i<n;i++) 18 { 19 for(int j=0;j<n;j++) 20 { 21 sum1[k++] = a[i][0]+a[j][1]; 22 sum2[m++] = -a[i][2]-a[j][3]; 23 } 24 } 25 sort(sum2,sum2+m); 26 int cnt = 0; 27 for(int i=0;i<k;i++) 28 { 29 int left = 0; 30 int right = k-1; 31 while(left<=right) 32 { 33 mid = (left+right)/2; 34 if(sum1[i]==sum2[mid]) 35 { 36 cnt++; 37 for(int j = mid-1;j>=0;j--) 38 { 39 if(sum1[i] == sum2[j]) 40 cnt++; 41 else 42 break; 43 } 44 for(int j = mid+1;j<m;j++) 45 { 46 if(sum1[i] == sum2[j]) 47 cnt++; 48 else 49 break; 50 } 51 break; 52 } 53 if(sum1[i]<sum2[mid]) 54 { 55 right = mid-1; 56 } 57 else 58 left = mid+1; 59 } 60 } 61 printf("%d\n",cnt); 62 } 63 64 }