4 Values whose Sum is 0
Time Limit: 15000MS Memory Limit: 228000K
Total Submissions: 26941 Accepted: 8122
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).
思路
普通的dfs不行了,这时候可以对四个数组,两两结合进行查找。
- 二分
- Hash
二分
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#define N 4004
using namespace std;
int a[N], b[N], c[N], d[N];
int l[N * N + 10], r[N * N + 10];
int main() {
// freopen("in.txt", "r", stdin);
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]);
}
//对四个数组两两处理
int now = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int t = a[i] + b[j];
l[now++] = t;
}
}
sort(l, l + now);
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int t = c[i] + d[j];
if(-t > l[now - 1]) continue;
int ll = 0, rr = now - 1;
// 二分找第一个大于等于key
// int *first = lower_bound(l, l + now, -t);
while (ll < rr) {
int mid = (ll + rr) / 2;
if(l[mid] < -t) {
ll = mid + 1;
}else if(l[mid] >= -t) {
rr = mid;
}
}
int first = ll;
ll = 0, rr = now - 1;
// 二分找第一个大于key
// int *last = upper_bound(l, l + now, -t);
while (ll < rr) {
int mid = (ll + rr) / 2;
if(l[mid] <= -t) {
ll = mid + 1;
}else if(l[mid] > -t) {
rr = mid;
}
}
if(l[ll] == -t) ll++;
int last = ll;
ans += last - first;
}
}
cout << ans << endl;
}
return 0;
}
Hash
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<cmath>
#include<string.h>
#define N 4004
using namespace std;
int a[N], b[N], c[N], d[N];
struct ac{
static const int mask = 0x7fffff;
int sum[N * N], vis[N * N];
void clear(){
memset(sum, 0, sizeof(sum));
}
int& operator [](int x){
int i;
for(i = x & mask; sum[i] && vis[i] != x; i = (i + 1) & mask);
vis[i] = x;
return sum[i];
}
}Hash;
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]);
}
Hash.clear();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Hash[a[i] + b[j]]++;
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
ans += Hash[-c[i] - d[j]];
}
}
printf("%d\n",ans);
}
return 0;
}