HDU - 3065 病毒侵袭持续中(AC自动机)
生活随笔
收集整理的這篇文章主要介紹了
HDU - 3065 病毒侵袭持续中(AC自动机)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出 n 個模式串和一個文本串,問每個模式串在文本串中分別出現了多少次
題目分析:雖然暴跳fail也是可以實現這個題目的,但個人感覺更好的方法還是建立fail樹后在樹上dfs比較好,需要注意的就是MLE的問題,因為這個題目是多組輸入,直接memset會卡內存,所以不妨自己寫一個newnode函數,用多少初始化多少,比較方便
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<queue> #include<map> #include<set> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=1e5+100;char s[1010][60],str[2000100];int fail[N],trie[N][130],rk[N],dp[N],cnt;struct Edge {int to,next; }edge[N];int head[N],tot;void addedge(int u,int v) {edge[tot].to=v;edge[tot].next=head[u];head[u]=tot++; }int newnode() {cnt++;for(int i=0;i<130;i++)trie[cnt][i]=0;return cnt; }void insert_word(int id) {int len=strlen(s[id]);int pos=0;for(int i=0;i<len;i++){int to=s[id][i];if(!trie[pos][to])trie[pos][to]=newnode();pos=trie[pos][to];}rk[id]=pos; }void getfail() {queue<int>q;for(int i=0;i<130;i++){if(trie[0][i]){fail[trie[0][i]]=0;q.push(trie[0][i]);}}while(!q.empty()){int cur=q.front();q.pop();for(int i=0;i<130;i++){if(trie[cur][i]){fail[trie[cur][i]]=trie[fail[cur]][i];q.push(trie[cur][i]);}elsetrie[cur][i]=trie[fail[cur]][i];}} }int search_word() {int len=strlen(str),pos=0;for(int i=0;i<len;i++){int to=str[i];pos=trie[pos][to];dp[pos]++;} }void dfs(int u) {for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;dfs(v);dp[u]+=dp[v];} }void init() {memset(head,-1,sizeof(head));memset(dp,0,sizeof(dp));for(int i=0;i<130;i++)trie[0][i]=0;cnt=tot=0; }int main() { // freopen("input.txt","r",stdin); // ios::sync_with_stdio(false);int n;while(scanf("%d",&n)!=EOF){init();for(int i=1;i<=n;i++){scanf("%s",s[i]);insert_word(i);}getfail();scanf("%s",str);search_word();for(int i=1;i<=cnt;i++)addedge(fail[i],i);dfs(0);for(int i=1;i<=n;i++)if(dp[rk[i]])printf("%s: %d\n",s[i],dp[rk[i]]);}return 0; }?
總結
以上是生活随笔為你收集整理的HDU - 3065 病毒侵袭持续中(AC自动机)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU - 2896 病毒侵袭(AC自动
- 下一篇: UVA - 11437 Triangle