4 Values whose Sum is 0_POJ2758

题目

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递减的

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cherish_lii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值