这道题目和B题差不多,也是成两部分,不过四个数组,就两两合并,再以一个二分来暴力查找即可,不过有一点点小技巧在中间~
题目如下:
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).
日常翻译:
SUM问题可以表述如下:给定四个列表A,B,C,D的整数值,计算多少个四元组(a,b,c,d)∈Ax B x C x D是这样的a + b + c + d = 0。 在下文中,我们假设所有列表都具有相同的大小n。
输入
输入文件的第一行包含列表n的大小(此值可以大到4000)。 然后我们有n行包含四个整数值(绝对值大到2 28),它们分别属于A,B,C和D.
产量
对于每个输入文件,程序必须写入总和为零的四元组数。
样本输入
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
样本输出
五
提示
示例说明:实际上,以下五个四联体的总和为零:( - 45,-27,42,30),(26,30,-10,-46),( - 32,22,56,-46) ,( - 32,30,-75,77),( - 32,-54,56,30)。
思路:这道题是记录次数,为了找到多次满足条件的相同数据,可以找到一个mid后向两边分别判断,若有满足的就加一,否则跳出循环~
代码如下:
#include <stdio.h>
#include <algorithm>
using namespace std;
int a[4002][4],sum1[16000002],sum2[16000002];//以一个二维数组简洁记录了四组数据
int main()
{
int n,mid;
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d%d%d%d",&a[i][0],&a[i][1], &a[i][2],&a[i][3]);
}
int k=0;
int m=0;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
{
sum1[k++]=a[i][0]+a[j][1]; //分别对两组合并
sum2[m++]=a[i][2]+a[j][3];
}
sort(sum2,sum2+k);
int cnt=0;
for(int i=0; i<k; i++)
{
int left=0;
int right=k-1;
while(left<=right)
{
mid=(left+right)/2;
if(sum1[i]+sum2[mid]==0)
{
cnt++;
for(int j=mid+1;j<k;j++) //找到mid后向右边寻找
{
if(sum1[i]+sum2[j]!=0)
break;
else
cnt++;
}
for(int j=mid-1;j>=0;j--) //找到mid后向左边寻找
{
if(sum1[i]+sum2[j]!=0)
break;
else
cnt++;
}
break;
}
if(sum1[i]+sum2[mid]<0) //不满足的话就返回左端点或者右端点的下标
left=mid+1;
else
right=mid-1;
}
}
printf("%d\n",cnt);
return 0;
}