生活随笔
收集整理的這篇文章主要介紹了
HDU - 2896 病毒侵袭(AC自动机)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出 n 個模式串,再給出 m 個匹配串,問有多少個模式串在匹配串中出現,需要分別對應上其編號
題目分析:對應編號問題我們可以直接開一個數組映射,也是比較經典的模板問題了,注意輸出格式就好了,還有如果MLE的話,用指針的朋友可以用C++交一下試試,用數組的朋友不要濫用memset,剩下的就是模板了
代碼:
?
#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[N];int fail[N],trie[N][130],cntword[N],rk[N],vis[N],cnt,tot;void insert_word(int id)
{int len=strlen(s);int pos=0;for(int i=0;i<len;i++){int to=s[i];if(!trie[pos][to])trie[pos][to]=++cnt;pos=trie[pos][to];}cntword[pos]++;rk[pos]=id;
}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 id)
{vector<int>ans;int len=strlen(s),pos=0;for(int i=0;i<len;i++){int to=s[i];pos=trie[pos][to];int temp=pos;while(temp&&vis[temp]!=id){vis[temp]=id;if(cntword[temp])//如果匹配成功ans.push_back(rk[temp]);temp=fail[temp];}}if(ans.size()){tot++;sort(ans.begin(),ans.end());printf("web %d:",id);for(int i=0;i<ans.size();i++)printf(" %d",ans[i]);printf("\n");}
}int main()
{
// freopen("input.txt","r",stdin);
// ios::sync_with_stdio(false);int n;scanf("%d",&n);for(int i=1;i<=n;i++){scanf("%s",s);insert_word(i);}getfail();scanf("%d",&n);for(int i=1;i<=n;i++){scanf("%s",s);search_word(i);}printf("total: %d\n",tot);return 0;
}
?
總結
以上是生活随笔為你收集整理的HDU - 2896 病毒侵袭(AC自动机)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。