# POJ 2785 4 Values whose Sum is 0（折半枚举）

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

#include <iostream>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <cstdio>
#include <ctime>
#include <bitset>
#include <algorithm>
#define SZ(x) ((int)(x).size())
#define ALL(v) (v).begin(), (v).end()
#define foreach(i, v) for (__typeof((v).begin()) i = (v).begin(); i != (v).end(); ++ i)
#define refeach(i, v) for (__typeof((v).rbegin()) i = (v).rbegin(); i != (v).rend(); ++ i)
#define REP(i,n) for ( int i=1; i<=int(n); i++ )
using namespace std;
typedef long long ll;

const int N = 4000+100;
int a[5][N];
int all[N*N];
int half[N*N];
int main()
{
int n;
while(~scanf("%d",&n))
{
REP(i,n) REP(j,4) scanf("%d",&a[j][i]);
int top = 0;
ll ans = 0;
REP(i,n) REP(j,n) half[++top] = a[1][i]+a[2][j];
REP(i,n) REP(j,n) all[top--] = a[3][i]+a[4][j];
sort(all+1,all+n*n+1);
REP(i,n*n) ans += upper_bound(all+1,all+n*n+1,-half[i])-lower_bound(all+1,all+n*n+1,-half[i]);
printf("%I64d\n",ans);
}
return 0;
}

#### POJ2785：4 Values whose Sum is 0(二分)

2014-08-18 16:37:11

#### poj 2785 测试数据

2013年03月01日 90KB 下载

#### POJ2785 （折半枚举）

2016-12-28 15:01:03

#### uva1152 4 Values whose Sum is 0（中途相遇法）

2016-01-17 14:26:57

#### [算法竞赛入门经典] UVA 1152 - 4 Values whose Sum is 0 | POJ 2785

2014-08-15 19:00:47

#### （POJ - 2785）4 Values whose Sum is 0

2017-08-13 15:49:33

#### POJ 2785 4 Values whose Sum is 0(折半枚举)

2016-02-12 21:15:48

#### 4 Values whose Sum is 0 POJ - 2785（折半枚举）题解

2017-02-13 17:42:39

#### POJ 2785 4 Values whose Sum is 0【双向搜索/折半枚举】

2017-07-03 16:46:49

#### UVA 1152 --4 Values whose Sum is 0（枚举--中途相遇法）

2017-06-16 13:49:59