【HDOJ】1247 Hat’s Words

时间:2023-11-24 23:49:14

字典树。

 #include <cstdio>
#include <cstring>
#include <cstdlib> #define MAXN 50005
#define MAXL 25 typedef struct Trie {
bool f;
Trie *next[];
Trie() {
f = false;
for (int i=; i<; ++i)
next[i] = NULL;
}
} Trie; Trie root;
char map[MAXN][MAXL], buf[MAXL];
int nn = ; void create(char str[]) {
int i = , id;
Trie *p = &root, *q; while (str[i]) {
id = str[i] - 'a';
++i;
if (p->next[id] == NULL) {
q = new Trie();
p->next[id] = q;
}
p = p->next[id];
}
p->f = true;
} bool find(char str[], int x) {
int i = , id;
Trie *p = &root;
bool f; while (i<x && str[i]) {
id = str[i] - 'a';
++i;
if (p->next[id] == NULL)
return false;
p = p->next[id];
}
f = p->f;
if (!f) return false; p = &root;
while (str[i]) {
id = str[i] - 'a';
++i;
if (p->next[id] == NULL)
return false;
p = p->next[id];
}
return p->f;
} int main() {
int i, j, len, n = ;
bool f; while (scanf("%s", map[n]) != EOF)
create(map[n++]); for (i=; i<n; ++i) {
len = strlen(map[i]);
f = false;
for (j=; !f&&j<len-; ++j)
f = find(map[i], j);
if (f)
printf("%s\n", map[i]);
} return ;
}