4 Values whose Sum is 0 UVA - 1152
Posted yijiull
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4 Values whose Sum is 0 UVA - 1152相关的知识,希望对你有一定的参考价值。
4 Values whose Sum is 0
题意:给n组4个数,问有多少种组合(每组选一个)使得四个数的和为零.
补个题...之前写的哈希表有问题一直没过就忘了,今天刚好看到~
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 const int maxn = 4010; 5 const int H_SZ = 16131313; 6 7 int a[maxn][4]; 8 9 struct HS{ 10 ll val[H_SZ], res[H_SZ]; 11 int head[H_SZ], nex[H_SZ]; 12 int cnt; 13 14 void init(){ 15 memset(head, -1, sizeof(head)); 16 memset(res, 0, sizeof(res)); 17 cnt = 0; 18 } 19 20 void add(ll x) { 21 x += 1e11; 22 int u = x%H_SZ; 23 val[cnt] = x; 24 res[cnt] ++; 25 nex[cnt] = head[u]; 26 head[u] = cnt++; 27 } 28 29 int query(ll x) { 30 x += 1e11; 31 int u = x%H_SZ; 32 for(int i = head[u]; ~i; i = nex[i]) { 33 if(val[i] == x) return i; 34 } 35 return H_SZ; 36 } 37 }hs; 38 39 int main(){ 40 int t, kase = 0; 41 //freopen("in.txt", "r", stdin); 42 scanf("%d", &t); 43 while(t--) { 44 if(kase) puts(""); 45 kase++; 46 hs.init(); 47 int n; 48 scanf("%d", &n); 49 for(int i = 0; i < n; i++){ 50 for(int j = 0; j < 4; j++) { 51 scanf("%d", &a[i][j]); 52 } 53 } 54 for(int i = 0; i < n; i++){ 55 for(int j = 0; j < n; j++){ 56 int x = a[i][0] + a[j][1]; 57 int id = hs.query(x); 58 if(id == H_SZ) hs.add(x); 59 else hs.res[id]++; 60 } 61 } 62 int ans = 0; 63 for(int i = 0; i < n; i++){ 64 for(int j = 0; j < n; j++){ 65 int x = -(a[i][2] + a[j][3]); 66 int id = hs.query(x); 67 if(id != H_SZ) ans += hs.res[id]; 68 } 69 } 70 printf("%d\n", ans); 71 } 72 }
以上是关于4 Values whose Sum is 0 UVA - 1152的主要内容,如果未能解决你的问题,请参考以下文章
4 Values whose Sum is 0 (二分+排序)
poj 2785 4 Values whose Sum is 0
4 Values whose Sum is 0 :POJ - 2785