hdu1251 字典树

 1 #include<stdio.h>
 2 #include<string.h>
 3 int sz=1,father[1000005],val[1000005],ch[1000005][30];
 4 void insert(char *s)
 5 {
 6     int u=0,i,len=strlen(s);
 7     for (i=0;i<len;i++)
 8     {
 9         if (ch[u][s[i]-'a']==0)
10         {
11             memset(ch[sz],0,sizeof(ch[sz]));
12             val[sz]=0;
13             ch[u][s[i]-'a']=sz;
14             father[sz]=u;
15             sz++;
16         }
17         else father[ch[u][s[i]-'a']]=u;
18         u=ch[u][s[i]-'a'];
19     }
20     while (u!=0) { val[u]++; u=father[u];}
21 }
22 int main()
23 {
24     int sum,u,d;
25     char s[10005];
26     memset(ch[0],0,sizeof(0));
27     while (gets(s)&&strcmp(s,"")!=0) insert(s);
28     while (gets(s))
29     {
30         sum=0; u=0; d=0;
31         while (ch[u][s[d]-'a']!=0&&d<strlen(s)-1)
32         {
33             u=ch[u][s[d]-'a'];
34             d++;
35         }
36         if (d==strlen(s)-1) sum+=val[ch[u][s[d]-'a']];
37         printf("%d\n",sum);
38     }
39     return(0);
40 }

posted on 2014-07-16 16:27  xiao_xin  阅读(80)  评论(0编辑  收藏  举报

导航