首页 > 代码库 > 【POJ】2503 Babelfish

【POJ】2503 Babelfish

字典树简单题。

 1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4  5 typedef struct Trie { 6     Trie *next[26]; 7     char str[15]; 8 } Trie; 9 10 Trie root;11 12 void create(char str[], char des[]) {13     int i = 0, j, id;14     Trie *p = &root, *q;15 16     while (str[i]) {17         id = str[i] - a;18         if (p->next[id] == NULL) {19             q = (Trie *)malloc(sizeof(Trie));20             for (j=0; j<26; ++j)21                 q->next[j] = NULL;22             p->next[id] = q;23         }24         p = p->next[id];25         ++i;26     }27     strcpy(p->str, des);28 }29 30 void find(char str[]) {31     int i = 0, id;32     Trie *p = &root;33 34     while (str[i]) {35         id = str[i] - a;36         if (p->next[id] == NULL) {37             printf("eh\n");38             return ;39         }40         p = p->next[id];41         ++i;42     }43     printf("%s\n", p->str);44 }45 46 void del(Trie *t) {47     int i;48     if (t == NULL)49         return ;50     for (i=0; i<26; ++i)51         del(t->next[i]);52     free(t);53 }54 55 int main() {56     char src[12], des[25];57     char *p;58 59     for (int i=0; i<26; ++i)60         root.next[i] = NULL;61 62     while (gets(des)!=NULL && des[0]!=\0) {63         p = strchr(des,  );64         strcpy(src, p+1);65         *p = \0;66         create(src, des);67     }68 69     while (scanf("%s", src) != EOF)70         find(src);71 72     return 0;73 }