4 Values whose Sum is 0

来源:互联网 发布:使命召唤12优化设置 编辑:程序博客网 时间:2024/05/16 14:05

Description

Download as PDF

The SUM problem can be formulated as follows: given four listsA, B, C, D of integer values, compute how many quadruplet(a, b, c, d ) $ \in$AxBxCxD are such that a + b + c + d = 0 . In the following, we assume that all lists have the same sizen .

Input

The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.


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 as228 ) that belong respectively to A, B, C and D .

Output

For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.


For each input file, your program has to write the number quadruplets whose sum is zero.

Sample Input

16-45 22 42 -16-41 -27 56 30-36 53 -37 77-36 30 -75 -4626 -38 -10 62-32 -54 -6 45

Sample Output

5


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). 


#  include <algorithm>中:

upper_bound(a,  a+n, x);在左闭右开区间a到a+n地址之间;找到大于x的最小值的位置:

lower_bound(a, a+n,x) ;在左闭右开区间a到a+n地址之间;找到大于或等于的值的位置;

//方法一:二分法求解;

# include <cstdio># include <string># include <cstring># include <iostream># include <algorithm>using namespace std;int a[4005],b[4005],c[4005],d[4005];int sum[16000025],sum2[16000025];int main(){    int t;    cin>>t;    while(t--)    {        int n,i,j,len=0,ans=0;;cin>>n;for(i=0;i<n;i++)scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);for(i=0;i<n;i++)for(j=0;j<n;j++)sum[len++]=a[i]+b[j];len=0;for(i=0;i<n;i++)for(j=0;j<n;j++)sum2[len++]=c[i]+d[j];sort(sum2,sum2+len);for(i=0;i<len;i++){int l=0,r=len-1,mid;while(l<r){mid=(r+l)>>1;if(sum[i]<-sum2[mid])    l=mid+1;else    r=mid;}while(sum2[l]==-sum[i]&&l<len){ans++;l++;}}printf("%d\n",ans);if(t)    printf("\n");    }    return 0;}//方法二:用函数upper_boud(),lower_boud()代替二分:# include <iostream># include <cstdio># include <algorithm>using namespace std;int a[4005],b[4005],c[4005],d[4005];int sum[16000005];int main(){int t;    cin>>t;    while(t--)    {int n,i,j,cnt=0,ans=0;cin>>n;for(i=0;i<n;i++)scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);for(i=0;i<n;i++)for(j=0;j<n;j++)sum[cnt++]=a[i]+b[j];sort(sum,sum+cnt);for(i=0;i<n;i++)for(j=0;j<n;j++)ans+=upper_bound(sum,sum+cnt,-c[i]-d[j])-lower_bound(sum,sum+cnt,-c[i]-d[j]);printf("%d\n",ans);if(t!=0)    printf("\n");    }    return 0;}


0 0
原创粉丝点击