UVA 1152-4 Values whose Sum is 0(二分查找)

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 × B × C × D are such that a + b + c + d = 0. In the following, we
assume that all lists have the same size n.

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

Output

For each test case, your program has to write the number quadruplets whose sum is zero.
The outputs of two consecutive cases will be separated by a blank line.

Sample Input

1
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

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)∈A×B×C×D使得a + b + c + d =0。在下面,我们假定所有列表的大小均相同。
输入
输入以一行上的单个正整数开头,表示行数
以下,分别说明如下。该行后跟一个空白行,并且还有一个
两个连续输入之间的空白行。
输入文件的第一行包含列表n的大小(此值可以最大为4000)。
然后,我们有n行包含四个整数值(绝对值最大为228),它们属于
分别到A,B,C和D。
输出
对于每个测试用例,您的程序必须编写四和数,其总和为零。
两个连续案例的输出将由空白行分隔。
样本
1
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
样本输出
5
样本说明:
的确,以下五个四元组的总和为零:(-45,-27、42、30),
(26、30,-10,-46),(-32、22、56,-46),(-32、30,-75、77),(-32,-54、56、30)。

题目大意:给出T组样例,对于每组样例:输入一个n,表示有n行数,统计4列数中每列选一个数,四个数相加等于0的种数。

解题思路;这道题的范围是4000,有4列数,n^4的时间复杂度肯定是会超时的,我们可以两两一组,ab的和的所有情况存一个数组,cd的和的所有情况存一个数组。最后给两个数组排序,用二分来解题就可以。这里需要用到两个函数:

  • upper_bound(a,a+n,num)函数:找出当前数组中第一个大于k的数,并返回下标的地址,减去首地址即可得到下标。
  • lower_bound(a,a+n,num)函数:找出当前数组中第一个大于等于k的数,并返回下标的地址,减去首地址即可得到下标。

AC代码:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int _max=4e3+50;
int sum1[_max*_max],sum2[_max*_max];
int a[_max],b[_max],c[_max],d[_max];
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		for(int i=0;i<n;i++)
		  cin>>a[i]>>b[i]>>c[i]>>d[i];
		int cnt=0;  
		for(int i=0;i<n;i++)
		  for(int j=0;j<n;j++)
		  {
			sum1[cnt]=a[i]+b[j];//存a,b的和
			sum2[cnt++]=c[i]+d[j];//存c,d的和
		  }
		sort(sum1,sum1+cnt);
		sort(sum2,sum2+cnt);  
		int ans=0;
		for(int i=0;i<cnt;i++)
		{
			int s=sum1[i];
			int s1=upper_bound(sum2,sum2+cnt,-s)-sum2;
			int s2=lower_bound(sum2,sum2+cnt,-s)-sum2;
			int ss=s1-s2;//等于0的种数
			ans+=ss;
		}
		cout<<ans<<endl;
		if(t)//这里注意一下格式
		  cout<<endl;
	}
	//system("pause");
	return 0;
}
原文地址:https://www.cnblogs.com/Hayasaka/p/14294294.html