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

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

字典树

读入的时候必须用scanf,用gets就错

View Code
 1 #include <cstdio>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 const int N=50010;
 6 const int SZ=100000,CH=26;
 7 int chd[SZ][CH],key[SZ];
 8 int sz=0;
 9 char w[N][50];
10 int n=0;
11 void insert(char *str)
12 {
13     int p=0;
14     for(int i=0;str[i];i++)
15     {
16         int ch=str[i]-'a';
17         if(!chd[p][ch]) chd[p][ch]=++sz;
18         p=chd[p][ch];
19     }
20     key[p]=1;
21 }
22 int find(char *s)
23 {
24     int p=0;
25     for(int i=0;s[i];i++)
26     {
27         int ch=s[i]-'a';
28         p=chd[p][ch];
29         if(!p) return 0;
30     }
31     return key[p];
32 }
33 bool ok(char *s)
34 {
35     for(int p=0,i=0;s[i];i++)
36     {
37         int ch=s[i]-'a';
38         p=chd[p][ch];
39         if(key[p] && find(s+i+1)) return true;
40     }
41     return false;
42 }
43 int main()
44 {
45     memset(chd,0,sizeof(chd));
46     memset(key,0,sizeof(key));
47     while(~scanf("%s",w[n])) insert(w[n++]);
48     for(int i=0;i<n;i++)
49         if(ok(w[i])) puts(w[i]);
50     return 0;
51 }

 

posted on 2012-04-28 20:01  Qiuqiqiu  阅读(157)  评论(0编辑  收藏  举报