[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+多元素检测

 

posted @ 2017-11-05 21:47  Leviaton  阅读(286)  评论(0编辑  收藏  举报