【POJ】1035 Spell checker
字典树。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <vector> 6 #include <string> 7 using namespace std; 8 9 typedef struct Trie { 10 int in; 11 Trie *next[26]; 12 } Trie; 13 14 Trie root; 15 char map[10005][25]; 16 int nums[205], nn; 17 18 void create(char str[], int in) { 19 int i = 0, j, id; 20 Trie *p = &root, *q; 21 22 while (str[i]) { 23 id = str[i] - 'a'; 24 ++i; 25 if (p->next[id] == NULL) { 26 q = (Trie *)malloc(sizeof(Trie)); 27 q->in = -1; 28 for (j=0; j<26; ++j) 29 q->next[j] = NULL; 30 p->next[id] = q; 31 } 32 p = p->next[id]; 33 } 34 p->in = in; 35 } 36 37 int find(char str[], int x) { 38 int i = 0, id; 39 Trie *p = &root; 40 41 while (str[i]) { 42 if (i == x) { 43 ++i; 44 continue; 45 } 46 id = str[i] - 'a'; 47 ++i; 48 if (p->next[id] == NULL) 49 return -1; 50 p = p->next[id]; 51 } 52 53 return p->in; 54 } 55 56 void ffind(char str[]) { 57 int len = strlen(str), i, j, k; 58 char ch, bk, bf[25]; 59 nn = 0; 60 61 for (i=0; i<=len; ++i) 62 bf[i] = str[i]; 63 for (i=0; i<len; ++i) { 64 bk = bf[i]; 65 for (ch='a'; ch<='z'; ++ch) { 66 if (ch == bk) 67 continue; 68 bf[i] = ch; 69 j = find(bf, -1); 70 if (j != -1) 71 nums[nn++] = j; 72 } 73 bf[i] = bk; 74 } 75 76 for (i=0; i<len; ++i) { 77 j = find(bf, i); 78 if (j != -1) 79 nums[nn++] = j; 80 } 81 bf[len+1] = '\0'; 82 for (i=0; i<=len; ++i) { 83 k = j = 0; 84 while (j<len) { 85 if (k != i) { 86 bf[k] = str[j]; 87 ++j; 88 } 89 ++k; 90 } 91 for (ch='a'; ch<='z'; ++ch) { 92 bf[i] = ch; 93 j = find(bf, -1); 94 if (j != -1) 95 nums[nn++] = j; 96 } 97 } 98 } 99 100 int comp(const void *a, const void *b) { 101 return *(int *)a - *(int *)b; 102 } 103 104 int main() { 105 int n = 0, f; 106 char buf[25]; 107 108 for (int i=0; i<26; ++i) 109 root.next[i] = NULL; 110 111 while (scanf("%s", map[n])!=EOF && map[n][0]!='#') { 112 create(map[n], n); 113 ++n; 114 } 115 116 while (scanf("%s", buf)!=EOF && buf[0]!='#') { 117 f = find(buf, -1); 118 if (f != -1) { 119 printf("%s is correct\n", buf); 120 continue; 121 } 122 ffind(buf); 123 printf("%s:", buf); 124 if (nn) { 125 qsort(nums, nn, sizeof(int), comp); 126 for (int i = 0; i<nn; ++i) { 127 if (i && nums[i] == nums[i-1]) 128 continue; 129 printf(" %s", map[nums[i]]); 130 } 131 } 132 printf("\n"); 133 } 134 135 return 0; 136 }