1. 程式人生 > >[51nod] 1267 4個數和為0

[51nod] 1267 4個數和為0

nco swa 分享 ref oid ostream play sum arr

1267 4個數和為0

基準時間限制:1 秒 空間限制:131072 KB 分值: 20 難度:3級算法題 給出N個整數,你來判斷一下是否能夠選出4個數,他們的和為0,可以則輸出"Yes",否則輸出"No"。 Input
第1行,1個數N,N為數組的長度(4 <= N <= 1000)
第2 - N + 1行:A[i](-10^9 <= A[i] <= 10^9)
Output
如果可以選出4個數,使得他們的和為0,則輸出"Yes",否則輸出"No"。
Input示例
5
-1
1
-5
2
4
Output示例
Yes
Analysis分析  我從Hash的題目列表點進來,,,結果發現一堆人寫排序  = =  如果枚舉的話是 n4 那麽我們枚舉兩個數的和,然後用Hash存起來  然後再次枚舉數和,檢測其相反數是否存在(當然這裏需要再加一個所有四個元素下標不重復的判定,如果是 1 -1 0 這種那麽就會出事)  Emmm加補丁的Hash Code代碼 技術分享
 1 #include<stdio.h>
 2 #include<iostream>
 3 #define ULL unsigned long long
 4 #define
maxn 1000007 5 using namespace std; 6 7 // 上面maxn那裏我一開始設的是100007,結果TLE qwq 8 9 struct data{ ULL val,pos; }sum[maxn]; 10 int m,n,arr[maxn]; 11 12 struct edge{ ULL val,pos; int from; }e[maxn*4]; 13 int tot,first[maxn]; 14 15 bool noequ(ULL A,ULL B){ 16 return (A/10000 != B/10000) && (A%10000 != B%10000
); 17 } 18 19 bool check(ULL val,ULL pos){ 20 int w = val%maxn; 21 for(int i = first[w];i;i = e[i].from){ 22 if(e[i].val == val && noequ(e[i].pos,pos)) return true; 23 }return false; 24 } 25 26 void insert(int pos1,int pos2,int suuum){ 27 if(pos1 > pos2) swap(pos1,pos2); 28 ULL val = (ULL)(suuum+1e9); 29 ULL kcode = pos1*10000+pos2; 30 31 if(check(val,kcode)) return; 32 33 int w = val%maxn; 34 35 tot++; e[tot].from = first[w]; 36 e[tot].val = val; e[tot].pos = kcode; 37 first[w] = tot; 38 sum[++m].val = val; 39 sum[m].pos = kcode; 40 } 41 42 int main(){ 43 scanf("%d",&n); 44 45 for(int i = 1;i <= n;i++) 46 scanf("%d",&arr[i]); 47 48 for(int i = 1;i <= n;i++) 49 for(int j = i+1;j <= n;j++) 50 insert(i,j,arr[i]+arr[j]); 51 52 // for(int i = 1;i <= m;i++) printf("%I64u %I64u\n",sum[i].val,sum[i].pos); 53 // 54 // cout << "Hash:" << endl; 55 // 56 // for(int i = 1;i <= tot;i++) printf("%I64u %I64u\n",e[i].val,e[i].pos); 57 58 for(int i = 1;i <= m;i++){ 59 if(check(2e9-sum[i].val,sum[i].pos)){ 60 cout << "Yes"; 61 return 0; 62 } 63 } 64 65 cout << "No"; 66 67 return 0; 68 }
Hash+多元素檢測

[51nod] 1267 4個數和為0