POJ2785 4 Values whose Sum is 0 折半枚举 ʕ •ᴥ•ʔ

                                                                                    4 Values whose Sum is 0

Time Limit: 15000MS   Memory Limit: 228000K
Total Submissions: 19331   Accepted: 5783
Case Time Limit: 5000MS

Description

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

Source

Southwestern Europe 2005

题目意思:

有abcd四个数组,各抽取一个数使得四个数之和为0;问共有多少种取法。

解题思路:

先取cd中的。再用折半枚举算出所需要的ab中的和的值。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#define N 100010
#include<map>
#define ll long long 
using namespace std;
ll a[4010],b[4010],c[4010],d[4010],e[4010*4010];
int main()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i]>>b[i]>>c[i]>>d[i];
	}
	int x=0;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			e[x]=a[i]+b[j];// 折半 将前两个数组组合
			x++;
		}
	}
	sort(e,e+x);
	ll ans=0;
	for(int i=1;i<=n;i++)
	{
		for(int j=1;j<=n;j++)
		{
			int k=-(c[i]+d[j]);
			ans+=upper_bound(e,e+x,k)-lower_bound(e,e+x,k);
			// upper_bound找到可以插入K值得最后一位数组下标  记忆 upper 上线 
			// lower_bound找到可以插入K值得第一位数组下标  记忆 low 下线 
			// 不存在得时候 他们返回得值相同 所以没影响 
		}
	}
	cout<<ans<<endl;
	
}

猜你喜欢

转载自blog.csdn.net/henucm/article/details/81488285