4 Values whose Sum is 0

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 -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

首先把a+b+c+d = 0化为a+b = -c-d
然后利用二分进行优化,再利用Lower bound和upper bound的差来统计符合的答案个数,刚开始没有想到,只是求解是否存在,没考虑有相同数的情况
 
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 typedef long long ll;
 7 int n, a[4005][5], ab[4005*4005];
 8 int main(void)
 9 {
10     while(cin >> n)
11     {
12         for(int i = 0; i < n; i++)
13             for(int j = 0; j < 4; j++)
14                 scanf("%d", &a[i][j]);
15         for(int i = 0; i < n; i++)
16             for(int j = 0; j < n; j++)
17                 ab[i*n+j] = a[i][0]+a[j][1];
18         ll ans = 0;
19         sort(ab, ab+n*n);
20         for(int i = 0; i < n; i++)
21             for(int j = 0; j < n; j++)
22             {
23                 int del = -(a[i][2]+a[j][3]);
24                 ans += upper_bound(ab, ab+n*n, del)-lower_bound(ab, ab+n*n, del);
25             }
26         printf("%lld\n", ans);
27     }
28     return 0;
29 }

猜你喜欢

转载自www.cnblogs.com/fhzy291146030/p/9371127.html
今日推荐