题目
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).
题目大意
有四列数字,从每一列里各取一个数,求有多少组四个数的和加起来为零
思路算法:二分
数量太大了,四重循环暴力枚举肯定会超时,所以才去类似二分
代码
#include<iostream>
#include<algorithm>
#define maxn 4004
using namespace std;
int map1[maxn*maxn];
int map2[maxn*maxn];
int a[maxn],b[maxn],c[maxn],d[maxn];
int main()
{
int n,t=0;
cin>>n;
for(int i=0;i<n;i++) cin>>a[i]>>b[i]>>c[i]>>d[i];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
map1[t]=a[i]+b[j];
map2[t]=c[i]+d[j];
t++;
}
sort(map1,map1+t);
sort(map2,map2+t);
int sum=0,p=n*n-1;
for(int i=0;i<n*n;i++)
{
while(p>=0 && map1[i]+map2[p]>0) p--; //找到两者和<=0的
int temp=p;
while(temp>=0 && map1[i]+map2[temp]==0) //如果等于0就继续,不等于0就直接退出了,因为两个map都是递减的
{
sum++;
temp--;
}
}
cout<<sum;
return 0;
}
四重循环肯定会超时,所以map1记录前两个数列的和,map2记录第二个数列和,然后再通过map1和map2来计算四个数列和
map1和map2一定要排序,排序有大用处
第一重for循环枚举map1,从小到大枚举
内层while循环1(是从最后也就是map2的最大值开始枚举)找到两者和<=0的
然后内层while循环2(循环控制条件是两者和等于0) 如果等于0 num++ ;不等于0的话只能是小于0,因为是map2递减的