[51nod] 1267 4个数和为0
生活随笔
收集整理的這篇文章主要介紹了
[51nod] 1267 4个数和为0
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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+多元素檢測?
轉載于:https://www.cnblogs.com/Chorolop/p/7788962.html
總結
以上是生活随笔為你收集整理的[51nod] 1267 4个数和为0的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用工具类系列之DateUtil
- 下一篇: Virtual Box 安装过程(卸载V