标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7850 Accepted Submission(s): 2736
/** 题意:给出n个子串,给一个母串,问母串中有哪个子串,并且有多少个 做法:AC自动机 **/ #include <iostream> #include <cmath> #include <algorithm> #include <string.h> #include <stdio.h> #include <queue> #define maxn 500010 char buf[1010][maxn]; 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]); } } } } void query(char ch[],int n) { int used[maxn]; memset(used,0,sizeof(used)); int len = strlen(ch); int now = root; int res = 0; bool prime = false; for(int i=0; i<len; i++) { now = next[now][ch[i]]; int tmp = now; while(tmp != root) { if(end[tmp]!=-1) { used[end[tmp]] ++; } tmp = fail[tmp]; } } for(int i=1;i<=n;i++) { if(used[i]>0) printf("%s: %d\n",buf[i],used[i]); } } }; Tire ac; char ch[2000000 + 1000]; int main() { #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif // ONLINE_JUDGE int n; while(~scanf("%d",&n)) { ac.init(); for(int i=1; i<=n; i++) { scanf("%s",buf[i]); ac.insert(buf[i],i); } ac.build(); scanf("%s",ch); ac.query(ch,n); } return 0; }
标签:
原文地址:http://www.cnblogs.com/chenyang920/p/4480391.html