其他分享
首页 > 其他分享> > 二分-G - 4 Values whose Sum is 0

二分-G - 4 Values whose Sum is 0

作者:互联网

G - 4 Values whose Sum is 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).
  题目大意:每行会给出四个整数,要求在每列整数中找出一个整数,使四个整数之和为0,求有几种不同组合
 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 
 5 const int maxn = 4010;
 6 const int maxm = 4010*4010;
 7 int a[maxn],b[maxn],c[maxn],d[maxn];
 8 int ab[maxm],cd[maxm];
 9 
10 int main(){
11     int n;
12     scanf("%d",&n);
13     for(int i=0;i<n;i++)
14         scanf("%d %d %d %d",a+i,b+i,c+i,d+i);
15         
16     int cnt = 0;
17     for(int i=0;i<n;i++)//前两列整数求和 
18         for(int j=0;j<n;j++)
19             ab[cnt++] = a[i] + b[j];
20     cnt = 0;    
21     for(int i=0;i<n;i++)//后两列整数求和 
22         for(int j=0;j<n;j++)
23             cd[cnt++] = c[i] + d[j];
24     
25     sort(ab,ab+n*n);
26     sort(cd,cd+n*n);
27     
28     int p = n*n-1;
29     cnt = 0;
30     for(int i=0;i<n*n;i++){
31         for(;p>=0;p--)
32             if(ab[i]+cd[p]<=0)    break;
33         if(p<0)                    break;
34         for(int j=p;j>=0;j--){
35             if(ab[i]+cd[j]==0)    cnt++;
36             if(ab[i]+cd[j]<0)    break;
37         } 
38     }
39     printf("%d",cnt);
40 }

  面对四列整数,一一组合将会造成极其庞大的数据,可将其中两两组合,组合以后再相加寻找和为0的情况。

标签:whose,ab,int,32,Sum,30,cd,Values,maxn
来源: https://www.cnblogs.com/0424lrn/p/12228294.html