WA;
这道题题意不清晰,单词相互包含的要不要计算?网上AC的程序跑出来的结果都不太一样,我的是计算在内的。
1 # include <cstdio> 2 # include <cstring> 3 # include <queue> 4 # include <algorithm> 5 6 using namespace std; 7 8 # define WORD_LEN 200 + 5 9 # define TEXT_LEN 10000 + 5 10 # define ALPHA_SIZE 128 + 5 11 12 int n, m, tot; 13 char w[WORD_LEN]; 14 char t[TEXT_LEN]; 15 int solu[10]; 16 17 struct node 18 { 19 node * fail; 20 node * next[ALPHA_SIZE]; 21 int id; 22 node() 23 { 24 id = 0; 25 fail = NULL; 26 memset(next, 0, sizeof(next)); 27 } 28 }* root; 29 30 int alpha_map(char ch) 31 { 32 return ch; 33 } 34 35 void insert_trie(node * root, char *s, int id) 36 { 37 node * p = root; 38 for (int i = 0; s[i]; ++i) 39 { 40 int c = alpha_map(s[i]); 41 if (NULL == p->next[c]) p->next[c] = new node(); 42 p = p->next[c]; 43 } 44 p->id = id; 45 } 46 47 void build_trie(node * root) 48 { 49 for (int i = 1; i <= n; ++i) 50 { 51 gets(w); 52 insert_trie(root, w, i); 53 } 54 } 55 56 void destory_trie(node * root) 57 { 58 int c; 59 node * cur; 60 queue <node *> Q; 61 62 Q.push(root); 63 while (!Q.empty()) 64 { 65 cur = Q.front(); Q.pop(); 66 for (c = 0; c < ALPHA_SIZE; ++c) 67 if (cur->next[c]) Q.push(cur->next[c]); 68 delete(cur); 69 } 70 } 71 72 void build_AC_auto(node *root) 73 { 74 root->fail = NULL; 75 76 int c; 77 queue <node *> Q; 78 for (c = 0; c < ALPHA_SIZE; ++c) 79 { 80 if (root->next[c]) 81 { 82 root->next[c]->fail = root; 83 Q.push(root->next[c]); 84 } 85 } 86 87 node *cur, *tmp; 88 while (!Q.empty()) 89 { 90 cur = Q.front(); 91 Q.pop(); 92 for (c = 0; c < ALPHA_SIZE; ++c) 93 { 94 if (cur->next[c]) 95 { 96 tmp = cur->fail; 97 while (tmp) 98 { 99 if (tmp->next[c]) 100 { 101 cur->next[c]->fail = tmp->next[c]; 102 break; 103 } 104 tmp = tmp->fail; 105 } 106 if (NULL == tmp) cur->next[c]->fail = root; 107 Q.push(cur->next[c]); 108 } 109 } 110 } 111 } 112 113 int query(node *root, char *s) 114 { 115 int i, c, ret = 0; 116 node *tmp, *p = root; 117 118 for (i = 0; s[i]; ++i) 119 { 120 c = alpha_map(s[i]); 121 while (NULL == p->next[c] && p != root) p = p->fail; 122 p = p->next[c]; 123 if (NULL == p) p = root; 124 tmp = p; 125 while (tmp) 126 { 127 if (tmp->id) 128 { 129 solu[ret++] = tmp->id; 130 tmp->id = 0; 131 } 132 tmp = tmp->fail; 133 } 134 } 135 136 return ret; 137 } 138 139 void solve(void) 140 { 141 tot = 0; 142 root = new node; 143 build_trie(root); 144 build_AC_auto(root); 145 scanf("%d", &m); getchar(); 146 int i, cnt; 147 for (i = 1; i <= m; ++i) 148 { 149 gets(t); 150 cnt = query(root, t); 151 if (cnt > 0) 152 { 153 ++tot; 154 sort(solu, solu+cnt); 155 printf("web %d:", i); 156 for (int j = 0; j < cnt; ++j) 157 printf(" %d", solu[j]); 158 putchar('\n'); 159 } 160 } 161 printf("total: %d\n", tot); 162 destory_trie(root); 163 } 164 165 int main() 166 { 167 while (~scanf("%d", &n)) 168 { 169 getchar(); 170 solve(); 171 } 172 173 return 0; 174 }
/**/