本文主要是介绍AC自动机 HDU3065,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
自动机水题
注意多组输入!!!!
#include <bits/stdc++.h>
using namespace std;
int ans[1001],n;
char buf[2000010],str[1001][55];
struct Trie
{int next[50001][128],fail[50010],end[50001];int root,L;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]-0] == -1)next[now][buf[i]-0] = newnode();now = next[now][buf[i]-0];}end[now]=id;}void build(){queue<int>Q;fail[root] = root;for(int i = 0;i < 128;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 < 128;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]);}}}void query(char buf[]){int len = strlen(buf);int now = root;for(int i = 0;i < len;i++){now = next[now][buf[i]-0];int temp = now;while( temp != root ){ans[end[temp]]++;temp = fail[temp];}}for(int i=0;i<n;i++) if(ans[i])printf("%s: %d\n",str[i],ans[i]);}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 < 128;j++)printf("%2d",next[i][j]);printf("]\n");}}
}ac;
int main()
{while(~scanf("%d",&n)){memset(ans,0,sizeof(ans));ac.init();for(int i = 0;i < n;i++){scanf("%s",str[i]);ac.insert(str[i],i);}ac.build();scanf("%s",buf);ac.query(buf);}return 0;
}
这篇关于AC自动机 HDU3065的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!