首页 > 代码库 > 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 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
1 #include<cstdio> 2 #include<string.h> 3 #include<algorithm> 4 #define MAXN 4400 5 using namespace std; 6 int A[MAXN],B[MAXN],C[MAXN],D[MAXN]; 7 int S[MAXN*MAXN]; 8 int lower_bound1(int low,int high,int num,int a[]) 9 {10 int mid;11 while(low<high)12 {13 mid=low+(high-low)/2;14 if(a[mid]>=num) high=mid;15 else low=mid+1;16 }17 return low;18 }19 int upper_bound1(int low,int high,int num,int a[])20 {21 int mid;22 while(low<high)23 {24 mid=low+(high-low)/2;25 if(a[mid]<=num) low=mid+1;26 else27 high=mid;28 }29 return low;30 }31 int main()32 {33 int n,i;34 int p;35 int cout=0;36 int l,r,j;37 while(scanf("%d",&n)!=EOF)38 {39 cout=0;40 for(i=0;i<n;i++)41 scanf("%d%d%d%d",&A[i],&B[i],&C[i],&D[i]);42 p=0;43 for(i=0;i<n;i++)44 for(j=0;j<n;j++)45 S[p++]=A[i]+B[j];46 sort(S,S+p);47 for(i=0;i<n;i++)48 for(j=0;j<n;j++)49 {50 int t=C[i]+D[j];51 l=lower_bound1(0,p,-t,S);52 r=upper_bound1(0,p,-t,S);53 cout+=(r-l);54 }55 printf("%d\n",cout);56 }57 return 0;58 }
-36 30 -75 -4626 -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).
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。