标签:
题目链接:病毒侵袭
解析:利用end数组记录各病毒的编号,然后统计即可。注意此时sigma_size为128(0~127的ascii码可见字符)。
AC代码:
#include <bits/stdc++.h> using namespace std; const int maxn = 502; const int max_word = 202; const int max_text = 10002; const int sigma_size = 128; struct Trie{ int next[max_word*maxn][sigma_size], fail[max_word*maxn], end[max_word*maxn]; int root, L; int newnode(){ for(int i = 0; i < sigma_size; i++) next[L][i] = -1; end[L++] = 0; return L-1; } void init(){ L = 0; root = newnode(); } void insert(char buf[], int id){ int len = strlen(buf); int now = root; for(int i = 0; i < len; i++){ if(next[now][ buf[i] ] == -1) next[now][ buf[i] ] = newnode(); now = next[now][ buf[i] ]; } end[now] = id; } void build(){ queue<int> Q; fail[root] = root; for(int i = 0; i < sigma_size; i++){ if(next[root][i] == -1) next[root][i] = root; else{ fail[ next[root][i] ] = root; Q.push(next[root][i]); } } while(!Q.empty()){ int now = Q.front(); Q.pop(); for(int i = 0; i < sigma_size; i++){ if(next[now][i] == -1) next[now][i] = next[ fail[now] ][i]; else{ fail[ next[now][i] ] = next[ fail[now] ][i]; Q.push(next[now][i]); } } } } bool used[maxn]; int query(char buf[], int n, int id){ memset(used, false, sizeof(used)); int len = strlen(buf); int now = root; bool flag = false; for(int i = 0; i < len; i++){ now = next[now][ buf[i] ]; int temp = now; while(temp != root){ if(end[temp]){ used[ end[temp] ] = true; flag = true; } temp = fail[temp]; } } if(!flag) return false; printf("web %d:", id); for(int i = 1; i <= n; i++){ if(used[i]) printf(" %d", i); } printf("\n"); return true; } void debug(){ for(int i = 0; i < L; i++){ printf("id = %3d, fail = %3d, end = %3d, chi = [", i, fail[i], end[i]); for(int j = 0; j <sigma_size; j++) printf("%2d", next[i][j]); printf("]\n"); } } }; char buf[max_text]; Trie ac; int main(){ #ifdef sxk freopen("in.txt", "r", stdin); #endif //sxk int n, m; while(scanf("%d", &n) == 1){ ac.init(); for(int i = 1; i <= n; i++){ scanf("%s", buf); ac.insert(buf, i); } ac.build(); scanf("%d", &m); int cnt = 0; for(int i = 1; i <= m; i++){ scanf("%s", buf); cnt += ac.query(buf, n, i); } printf("total: %d\n", cnt); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u013446688/article/details/47177561