1. 程式人生 > >4 Values whose Sum is 0 UVA - 1152

4 Values whose Sum is 0 UVA - 1152

一個 add spa 哈希 mem class init print const

4 Values whose Sum is 0

UVA - 1152

題意:給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 }
View Code

4 Values whose Sum is 0 UVA - 1152