C - 4 Values whose Sum is 0

本文介绍了一个经典的编程问题——SUM问题的高效求解方法。通过将输入列表分为两组并利用排序与二分查找技巧,有效地计算出了所有四元组的组合中元素之和等于零的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题意:题意很好理解,就是abcd序列里面,各选一个数字相加为0的情况个数,这道题因为数据很多,就把abcd分成两个部分,ab一个部分求和排序,cd一个部分,然后再用二分求两个部分的和为0的情况,这里不能只是找到是否存在,还要计算符合要求的情况个数
代码:
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include<iostream>
using namespace std;
int ab[4010*4010],cd[4010*4010];
int main()
{

	int n,i,k,j,count,a[4010],b[4010],c[4010],d[4010];
	while(cin>>n)
	{

		for(i=0;i<n;i++)
			cin>>a[i]>>b[i]>>c[i]>>d[i];
		int cot1=0;
		int cot2=0;
		for(i=0;i<n;i++)
		{
			for(j=0;j<n;j++)
			{
				ab[cot1++]=a[i]+b[j];
				cd[cot2++]=-(c[i]+d[j]);
			}
		}
		sort(cd,cd+cot2);
		count=0;
		for(i=0;i<cot1;i++)
		{
			int left=0;
		    int right=n*n-1;
			while(left<=right)
			{
				int mid=(left+right)/2;
				if(ab[i]==cd[mid])
				{
					count++;
					for(k=mid+1;k<cot2;k++)
					{
						if(ab[i]==cd[k])
							count++;
						else
							break;
					}
					for(k=mid-1;k>=0;k--)
					{
						if(ab[i]==cd[k])
							count++;
						else
							break;
					}
					break;
				}
				else if(ab[i]<cd[mid])
					 right=mid-1;
				else
					 left=mid+1;

			}
		}
		cout<<count<<endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值