您的位置:首页 > 其它

POJ 2785 (二分)

2016-02-17 20:12 381 查看
4 Values whose Sum is 0

Time Limit: 15000MS Memory Limit: 228000K
Total Submissions: 18785 Accepted: 5579
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
题意是给出4个数列,每个数列n个数,要求从每个数列中取出一个数使得4个数的和为0。

先取两组记录两两的和,然后枚举另外两组两两的和从已知的和里面去找。

可能map常数比较大过不了,二分就可以了。

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <time.h>
#include <vector>
#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
#define maxn 4111

int n;
long long a[maxn][4];
long long sum[maxn*maxn];

int main () {
while (scanf ("%d", &n) == 1) {
for (int i = 1; i <= n; i++) {
scanf ("%lld%lld%lld%lld", &a[i][0], &a[i][1], &a[i][2], &a[i][3]);
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
long long num = a[i][2]+a[j][3];
sum[cnt++] = num;
}
}
long long ans = 0;
sort (sum, sum+cnt);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
long long num = -1 * (a[i][0] + a[j][1]);
ans += upper_bound (sum, sum+cnt, num) - lower_bound (sum, sum+cnt, num);
}
}
printf ("%lld\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: