经典的字典树,debug爽歪歪。
Code:
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 500000;
int ch[MAXN][26], tag[MAXN], tot = 1;
char word[50010][80];
void Insert(char *s) {
int now = 1, id;
while(*s) {
id = *s - 'a';
if (ch[now][id]) now = ch[now][id];
else now = ch[now][id] = ++tot;
++s;
}
++tag[now];
}
bool find(char *s) {
int now = 1, id;
while(*s) {
id = *s - 'a';
if (ch[now][id]) now = ch[now][id];
else return false;
++s;
}
if (tag[now]) return true;
else return false;
}
bool find_hat(char *s) {
char ss[80];
int now = 1, id, len = strlen(s);
for (int i = 1; i <= len; ++i) {
id = s[i-1] - 'a';
if (ch[now][id]) now = ch[now][id];
if (tag[now] && i < len) {
strcpy(ss, s+i);
if (find(ss)) return true;
}
}
return false;
}
int main() {
int num = 0;
memset(tag, 0, sizeof(tag));
while(~scanf("%s", word[num]))
Insert(word[num++]);
for (int i = 0; i < num; ++i)
if(find_hat(word[i]))
printf("%s\n", word[i]);
return 0;
}