hdu1247 字典树

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

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

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

导航