Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.hdu.edu.cn/showproblem.php?pid=1880

最初的想法直接快排+二分查找

为了练习hash就用hash做了

View Code
 1 #include <cstdio>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 const int N=100010,MAXH=100003;
 6 char w0[N][25],w1[N][85];
 7 int head[2][MAXH],next[2][N];
 8 int n;
 9 int hash(char *key)
10 {
11     unsigned int h=0;
12     while(*key)
13     {
14         h=(h<<4)+*key++;
15         unsigned int g=h&0xf000000L;
16         if(g) h^=g>>24;
17         h&=~g;
18     }
19     return h%MAXH;
20 }
21 void insert(int s,int k)
22 {
23     int h=k?hash(w1[s]):hash(w0[s]);
24     next[k][s]=head[k][h];
25     head[k][h]=s;
26 }
27 void dictionary()
28 {
29     const char end[6]="@END@";
30     memset(head,0,sizeof(head));
31     memset(next,0,sizeof(next));
32     n=0;
33     char s1[25],s2[85];
34     while(scanf("%s",s1),strcmp(s1,end))
35     {
36         n++;
37         strcpy(w0[n],s1);
38         insert(n,0);
39         getchar(); gets(s2);
40         strcpy(w1[n],s2);
41         insert(n,1);
42     }
43 }
44 int find(char *s,int k)
45 {
46     int h=hash(s);
47     int u=head[k][h];
48     if(k==0) while(u && strcmp(s,w0[u])) u=next[k][u];
49     else while(u && strcmp(s,w1[u])) u=next[k][u];
50     return u;
51 }
52 void putstr(char *s)
53 {
54     for(int i=1;s[i]!=']';i++) putchar(s[i]);
55     putchar('\n');
56 }
57 int main()
58 {
59     dictionary();
60     int T;
61     scanf("%d",&T); getchar();
62     while(T--)
63     {
64         char s[85];
65         gets(s);
66         if(s[0]=='[')
67         {
68             int p=find(s,0);
69             if(p) puts(w1[p]);
70             else puts("what?");
71         }
72         else
73         {
74             int p=find(s,1);
75             if(p) putstr(w0[p]);
76             else puts("what?");
77         }
78     }
79     return 0;
80 }

 

posted on 2012-04-28 19:02  Qiuqiqiu  阅读(274)  评论(0编辑  收藏  举报