【POJ】2001 Shortest Prefixes
字典树。
1 #include <cstdio> 2 #include <cstring> 3 #include <cstdlib> 4 5 #define MAXN 26 6 7 typedef struct Trie{ 8 int n; 9 Trie *next[MAXN]; 10 } Trie; 11 12 Trie root; 13 char buf[1005][25]; 14 15 void create(char str[]) { 16 int len = strlen(str); 17 int i, j, id; 18 Trie *p = &root, *q; 19 20 for (i=0; i<len; ++i) { 21 id = str[i] - 'a'; 22 if (p->next[id] == NULL) { 23 q = (Trie *)malloc(sizeof(Trie)); 24 q->n = 1; 25 for (j=0; j<MAXN; ++j) 26 q->next[j] = NULL; 27 p->next[id] = q; 28 p = p->next[id]; 29 } else { 30 p->next[id]->n++; 31 p = p->next[id]; 32 } 33 } 34 } 35 36 int find(char str[]) { 37 int len = strlen(str), i, id; 38 Trie *p = &root; 39 40 for (i=0; i<len; ++i) { 41 id = str[i] - 'a'; 42 if (p->next[id] == NULL) 43 return i; 44 else { 45 if (p->next[id]->n == 1) 46 return i; 47 p = p->next[id]; 48 } 49 } 50 51 return len; 52 } 53 54 void del(Trie *t) { 55 int i; 56 57 if (t == NULL) 58 return ; 59 for (i=0; i<MAXN; ++i) 60 del(t->next[i]); 61 62 free(t); 63 } 64 65 int main() { 66 int n = 0; 67 int i = 0, j; 68 69 for (i=0; i<MAXN; ++i) 70 root.next[i] = NULL; 71 root.n = -1; 72 73 while (scanf("%s", buf[n]) != EOF) { 74 create(buf[n]); 75 ++n; 76 } 77 78 for (i=0; i<n; ++i) { 79 printf("%s ", buf[i]); 80 j = find(buf[i]); 81 buf[i][j+1] = '\0'; 82 printf("%s\n", buf[i]); 83 } 84 85 return 0; 86 }