码迷,mamicode.com
首页 > 其他好文 > 详细

POJ2785 4 Values whose Sum is 0 【枚举】

时间:2014-11-09 14:02:26      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:poj2785

4 Values whose Sum is 0
Time Limit: 15000MS   Memory Limit: 228000K
Total Submissions: 16000   Accepted: 4625
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

/*
** Problem: POJ2785
** Status: Accepted
** Running Time: 6766ms
** Author: Changmu
**
** 题解:将解空间分成两部分分别枚举。
*/

#include <cstdio>
#include <cstring>
#include <algorithm>

#define maxn 4010
typedef __int64 LL;
using namespace std;

int A[4][maxn], CD[maxn * maxn];

int main() {
    LL ret = 0;
    int i, j, n, id = 0, tmp;
    scanf("%d", &n);
    for(i = 0; i < n; ++i) {
        for(j = 0; j < 4; ++j)
            scanf("%d", &A[j][i]);
    }
    for(i = 0; i < n; ++i)
        for(j = 0; j < n; ++j)
            CD[id++] = A[2][i] + A[3][j];
    sort(CD, CD + id);

    for(i = 0; i < n; ++i)
        for(j = 0; j < n; ++j) {
            tmp = A[0][i] + A[1][j];
            ret += upper_bound(CD, CD + id, -tmp) - lower_bound(CD, CD + id, -tmp);
        }
    printf("%I64d\n", ret);
}


POJ2785 4 Values whose Sum is 0 【枚举】

标签:poj2785

原文地址:http://blog.csdn.net/chang_mu/article/details/40948903

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!