经典的字典树,debug爽歪歪。
Code:
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int MAXN = 500000; 4 int ch[MAXN][26], tag[MAXN], tot = 1; 5 char word[50010][80]; 6 7 void Insert(char *s) { 8 int now = 1, id; 9 while(*s) { 10 id = *s - 'a'; 11 if (ch[now][id]) now = ch[now][id]; 12 else now = ch[now][id] = ++tot; 13 ++s; 14 } 15 ++tag[now]; 16 } 17 18 bool find(char *s) { 19 int now = 1, id; 20 while(*s) { 21 id = *s - 'a'; 22 if (ch[now][id]) now = ch[now][id]; 23 else return false; 24 ++s; 25 } 26 if (tag[now]) return true; 27 else return false; 28 } 29 30 bool find_hat(char *s) { 31 char ss[80]; 32 int now = 1, id, len = strlen(s); 33 for (int i = 1; i <= len; ++i) { 34 id = s[i-1] - 'a'; 35 if (ch[now][id]) now = ch[now][id]; 36 if (tag[now] && i < len) { 37 strcpy(ss, s+i); 38 if (find(ss)) return true; 39 } 40 } 41 return false; 42 } 43 44 int main() { 45 int num = 0; 46 memset(tag, 0, sizeof(tag)); 47 while(~scanf("%s", word[num])) 48 Insert(word[num++]); 49 for (int i = 0; i < num; ++i) 50 if(find_hat(word[i])) 51 printf("%s ", word[i]); 52 53 return 0; 54 }