【POJ-2785】解题报告(二分水题)

原始题目

4 Values whose Sum is 0

  • Time Limit: 15000MS
  • Memory Limit: 228000K
  • Total Submissions: 28507
  • Accepted: 8591
  • 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 \(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

Southwestern Europe 2005

题目大意

给定四个长度为n的数列,从每一个数列中抽取一个数,问和为零的共有多少种可能。

解题思路

  • 预处理出前两个数列的和sum1与后两个数列的和sum2。
  • 对sum1排序,二分查找sum2中每个元素的相反数,累加输出
  • 注意不要用binary_search函数,而应该用upper_bound - lower_bound ,因为可能sum1数列中有多个元素值均为 -sum2[i] 。如果用binary_search 只能得到是否有,计数会少计。

解题代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <vector>
#include <set>
#include <map>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
//#define pb push_back
//#define mp make_pair
//#define np next_permutation
//#define all(x) x.begin(),x.end()
//#define fi first
//#define se second
//#define SZ(x) ((int)(x).size())
//typedef vector <int> vi;
typedef long long ll;
//typedef pair <int,int> pii;
const int mod=1e9+7;
const int maxn=4100;

ll sum1[maxn*maxn],sum2[maxn*maxn];
ll a[maxn],b[maxn],c[maxn],d[maxn];

int main(){
int n;
while(~scanf("%d",&n)){
rep(i,0,n){
scanf("%lld %lld %lld %lld",&a[i],&b[i],&c[i],&d[i]);
}
rep(i,0,n){
rep(j,0,n){
sum1[i*n+j]=a[i]+b[j];
sum2[i*n+j]=c[i]+d[j];
}
}
sort(sum1,sum1+n*n);
ll ans=0;
rep(i,0,n*n){
ans+=(upper_bound(sum1,sum1+n*n,-sum2[i])-lower_bound(sum1,sum1+n*n,-sum2[i]));
}
printf("%lld\n",ans);

}
}

收获与反思

  • 加深STL里三个函数应用和相互区别。