The Sum of 0 for four numbers(拆解加二分思想)
个人心得:单纯用二分法一直超时,后面发现我的那种方法并没有节省多少时间,后面看了大神的代码,真的是巧妙,
俩个数组分别装a+b,c+d。双指针一个指向最后,从第一个开始想加,加到刚好大于0停止,再看是否存在和为0的情况。
很巧妙,因为此时i,j所指想加刚好大于0,因为是排完序的,所以i往后面走的时候,大于j的数相加一定大于0,所以卡的非常好;
就没有再指针跳转回去了,佩服!
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).
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<vector> 5 #include<algorithm> 6 #define maxn 4004 7 using namespace std; 8 int map1[maxn*maxn]; 9 int map2[maxn*maxn]; 10 int a[maxn],b[maxn],c[maxn],d[maxn]; 11 int main() 12 { 13 int n,i,j,k,sum,p; 14 scanf("%d",&n); 15 for(i=0;i<n;i++) 16 { 17 scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]); 18 } 19 for(i=0;i<n;i++) 20 for(j=0;j<n;j++) 21 map1[i*n+j]=a[i]+b[j]; 22 for(i=0;i<n;i++) 23 for(j=0;j<n;j++) 24 map2[i*n+j]=c[i]+d[j]; 25 sort(map1,map1+n*n); 26 sort(map2,map2+n*n); 27 sum=0; 28 p=n*n-1; 29 for(i=0;i<n*n;i++) 30 { 31 while(p>=0&&map1[i]+map2[p]>0) p--; 32 if(p<0) break; 33 int temp=p; 34 while(temp>=0&&map1[i]+map2[temp]==0) 35 { 36 sum++; temp--; 37 } 38 } 39 printf("%d\n",sum); 40 //system("pause"); 41 return 0; 42 }