NYOJ 138 (简单hash)

View Code
 1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 using namespace std;
5
6 struct node
7 {
8 int v;
9 node *next;
10 }point[1000001];
11 node *table[1000000];
12
13 int a[101];
14 int k;
15
16 int hash(int x)
17 {
18 return (x%1000000);
19 }
20
21 void add()
22 {
23 int i,n,h;
24 scanf("%d",&n);
25 for(i=0;i<n;++i,++k)
26 {
27 scanf("%d",&point[k].v);
28 h=hash(point[k].v);
29 node *p=table[h];
30 while(p)
31 {
32 if(p->v==point[k].v)break;
33 p=p->next;
34 }
35 if(!p)
36 {
37 point[k].next=table[h];
38 table[h]=&point[k];
39 }
40 }
41 }
42
43 void query()
44 {
45 int i,n,x,h;
46 scanf("%d",&n);
47 for(i=0;i<n;++i)
48 {
49 scanf("%d",&x);
50 h=hash(x);
51 node *p=table[h];
52 while(p)
53 {
54 if(p->v==x)break;
55 p=p->next;
56 }
57 if(p)printf("YES\n");
58 else printf("NO\n");
59 }
60 }
61
62 int main()
63 {
64 int t;
65 char ch[6];
66 memset(table,0,sizeof(table));
67 k=0;
68 scanf("%d",&t);
69 while(t--)
70 {
71 scanf("%s",ch);
72 if(ch[0]=='A')
73 add();
74 else query();
75 }
76 system("pause");
77 return 0;
78 }

 

View Code
 1 经典: 
2 #include<iostream>
3 #include<cstdio>
4 #include<cstring>
5 using namespace std;
6
7 unsigned int a[3125010]={0};
8
9 int main()
10 {
11 int t,n,i,x;
12 char ch[6];
13 scanf("%d",&t);
14 while(t--)
15 {
16 scanf("%s",ch);
17
18 if(ch[0]=='A')
19 {
20 scanf("%d",&n);
21 for(i=0;i<n;++i)//无符号整型为32位
22 {
23 scanf("%d",&x);
24 a[x/32] |= (1<<(x%32));//按二进制计算 把X对32求余 的k 则把1左移k位
25 } // 相当于2^k方 对于余数相同的 看商,
26 } //上相同 余数k一定不相同
27 else // 若a[1]==3即二进制:11说明商为1的 而余数为0和1的
28 { //这两个数32 33都出现过
29 scanf("%d",&n);
30 for(i=0;i<n;++i)
31 {
32 scanf("%d",&x);
33 if(a[x/32]&(1<<(x%32)))printf("YES\n");
34 else printf("NO\n");
35 }
36 }
37 }
38 system("pause");
39 return 0;
40 }

 

posted @ 2012-02-14 09:24  知行执行  阅读(151)  评论(0编辑  收藏  举报