POJ - 2785 4 Values whose Sum is 0(二分搜索)

来源:互联网 发布:无缝贴图软件 编辑:程序博客网 时间:2024/05/17 01:25
4 Values whose Sum is 0
Time Limit: 15000MS Memory Limit: 228000KB 64bit IO Format: %I64d & %I64u

Submit Status

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


题意:给出各有n个数字的A,B,C,D四个数列,要求从四个数列中各取出一个数,使得和为0。求符合的组合个数。

分析:处理出A+B和C+D的所有情况,再排序,二分查找符合要求的组合个数。查找过程的复杂度为O(n^2logn)。


#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int MAXN = 4000 + 500;int A[MAXN], B[MAXN], C[MAXN], D[MAXN];int AB[MAXN*MAXN], CD[MAXN*MAXN];int main(){int n;while (scanf("%d", &n) != EOF){for (int i = 0; i < n; i++)scanf("%d%d%d%d", &A[i], &B[i], &C[i], &D[i]);for (int i = 0; i < n;i++)for (int j = 0; j < n; j++){AB[i*n + j] = A[i] + B[j];CD[i*n + j] = C[i] + D[j];}sort(CD, CD + n*n);sort(AB, AB + n*n);long long ans = 0;for (int i = 0; i < n*n; i++){ans += upper_bound(CD, CD + n*n, -AB[i]) - lower_bound(CD, CD + n*n, -AB[i]);}printf("%I64d\n", ans);}}

0 0