生活随笔
收集整理的這篇文章主要介紹了
HDU - 2896 病毒侵袭(AC自动机)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:點(diǎn)擊查看
題目大意:給出 n 個(gè)模式串,再給出 m 個(gè)匹配串,問(wèn)有多少個(gè)模式串在匹配串中出現(xiàn),需要分別對(duì)應(yīng)上其編號(hào)
題目分析:對(duì)應(yīng)編號(hào)問(wèn)題我們可以直接開(kāi)一個(gè)數(shù)組映射,也是比較經(jīng)典的模板問(wèn)題了,注意輸出格式就好了,還有如果MLE的話,用指針的朋友可以用C++交一下試試,用數(shù)組的朋友不要濫用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;
}
?
總結(jié)
以上是生活随笔為你收集整理的HDU - 2896 病毒侵袭(AC自动机)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。