标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13776 Accepted Submission(s): 3545
/** 题意:给出病毒的样本,问母串中有那种病毒,并且多少个病毒 做法:AC自动机 **/ #include <iostream> #include <cmath> #include <algorithm> #include <string.h> #include <stdio.h> #include <queue> #define maxn 500010 using namespace std; struct Tire { int next[maxn][128],end[maxn],fail[maxn]; int L,root; int newnode() { for(int i=0; i<128; i++) { next[L][i] = -1; } end[L++] = -1; 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>que; fail[root] = root; int now = root; for(int i=0; i<128; i++) { if(next[now][i] == -1) next[now][i] = root; else { fail[next[now][i]] = root; que.push(next[now][i]); } } while(!que.empty()) { now = que.front(); que.pop(); for(int i=0; i<128; i++) { if(next[now][i] == -1) next[now][i] = next[fail[now]][i]; else { fail[next[now][i]] = next[fail[now]][i]; que.push(next[now][i]); } } } } bool query(char buf[],int id,int n) { bool used[maxn]; memset(used,false,sizeof(used)); int len = strlen(buf); int now = root; int res = 0; bool prime = false; for(int i=0; i<len; i++) { now = next[now][buf[i]]; int tmp = now; while(tmp != root) { if(end[tmp]!=-1) { used[end[tmp]] = true; prime = true; } tmp = fail[tmp]; } } if(!prime) return false; if(prime) { printf("web %d:",id); for(int i=1; i<=n; i++) { if(used[i]) printf(" %d",i); } printf("\n"); return true; } } }; Tire ac; char buf[1000010]; int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif // ONLINE_JUDGE int n,m; while(~scanf("%d",&n)) { ac.init(); for(int i=1; i<=n; i++) { scanf("%s",buf); ac.insert(buf,i); } ac.build(); scanf("%d",&m); int tmp = 0,res = 0; for(int i=1; i<=m; i++) { scanf("%s",buf); if(ac.query(buf,i,n)) res++; } printf("total: %d\n",res); } return 0; }
标签:
原文地址:http://www.cnblogs.com/chenyang920/p/4480382.html