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 .
http://blog.csdn.net/lp_opai/article/details/38231259?utm_source=tuicool
- int ab[4010*4010],cd[4010*4010];
- int main()
- {
- int n,i,k,j,count,a[4010],b[4010],c[4010],d[4010];
- while(~scanf("%d",&n))
- {
- for(i=0;i<n;i++)
- scanf("%d %d %d %d",&a[i],&b[i],&c[i],&d[i]);
- int cot1=0;
- int cot2=0;
- for(i=0;i<n;i++)
- {
- for(j=0;j<n;j++)
- {
- ab[cot1++]=a[i]+b[j];
- cd[cot2++]=-(c[i]+d[j]);
- }
- }
- sort(cd,cd+cot2);
- count=0;
- for(i=0;i<cot1;i++)
- {
- int left=0;
- int right=n*n-1;
- while(left<=right)
- {
- int mid=(left+right)/2;
- if(ab[i]==cd[mid])
- {
- count++;
- for(k=mid+1;k<cot2;k++)
- {
- if(ab[i]==cd[k])
- count++;
- else
- break;
- }
- for(k=mid-1;k>=0;k--)
- {
- if(ab[i]==cd[k])
- count++;
- else
- break;
- }
- break;
- }
- else if(ab[i]<cd[mid])
- right=mid-1;
- else
- left=mid+1;
- }
- }
- printf("%d\n",count);
- }
- return 0;
- }
- int erfen(int left,int right,int k)
- {
- int i;
- while(left<=right)
- {
- int mid=(left+right)/2;
- int num=0;
- if(num2[mid]==k)
- {
- num=1;
- for(i=mid-1;i>=0&&num2[i]==k;i--) num++;
- for(i=mid+1;i<n*n&&num2[i]==k;i++) num++;
- return num;
- }
- else if(num2[mid]>k)
- right=mid-1;
- else left=mid+1;
- }
- return 0;
- }
- int main()
- {
- int i,j;
- while(scanf("%d",&n)!=EOF)
- {
- int num=0;
- c=0;
- for(i=0;i<n;i++)
- {
- scanf("%d %d %d %d",&a[0][i],&a[1][i],&a[2][i],&a[3][i]);
- }
- for(i=0;i<n;i++)
- for(j=0;j<n;j++)
- {
- num1[c]=a[2][i]+a[3][j];
- num2[c++]=-(a[0][i]+a[1][j]);
- }
- sort(num2,num2+c);
- for(i=0;i<c;i++)
- {
- num+=erfen(0,n*n-1,num1[i]);
- }
- printf("%d\n",num);
- }
- return 0;
- }
hash 做法 - we can use hashmap directly in java
- int n,a[4040],b[4040],c[4040],d[4040],ans;
- int hash[size],sum[size];
- void Insert(int num)
- {
- int tmp=num;
- num=(num+MAX)%size;
- while(hash[num]!=MAX && hash[num]!=tmp)
- num=(num+key)%size;
- hash[num]=tmp;
- sum[num]++;
- }
- int Find(int num)
- {
- int tmp=num;
- num=(num+MAX)%size;
- while(hash[num]!=MAX && hash[num]!=tmp)
- num=(num+key)%size;
- if(hash[num]==MAX)
- return 0;
- else
- return sum[num];
- }
- int main()
- {
- int i,j;
- scanf("%d",&n);
- for(i=0;i<n;i++)
- scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
- for(i=0;i<size;i++)
- hash[i]=MAX;
- for(i=0;i<n;i++)
- for(j=0;j<n;j++)
- Insert(a[i]+b[j]);
- for(i=0;i<n;i++)
- for(j=0;j<n;j++)
- ans+=Find(-(c[i]+d[j]));
- printf("%d\n",ans);
- }