ZOJ - 3228 Searching the String(AC自动机求不重复子串出现次数)
生活随笔
收集整理的這篇文章主要介紹了
ZOJ - 3228 Searching the String(AC自动机求不重复子串出现次数)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出一個匹配串 str ,再給出 n 個長度不大于 6 的匹配串 s ,問每個匹配串出現的次數,分可以重復或不可以重復兩種情況
題目分析:因為是匹配串在模式串中出現的次數,可以重復的情況就是AC自動機的最簡單情況了,對于不允許重復的情況,我們可以對于每個節點記錄一下最后一次出現的位置,與其長度比較一下就好了,為了簡化代碼,我們可以給 cnt 數組,也就是記錄每個節點出現次數的數組多開一維,表示是否允許重復
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<unordered_map> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=6e5+100;char s[10],str[N];int fail[N],pos[N],trie[N][26],type[N],deep[N],num[N][2],cnt;//type:操作類型 0:可重復 1:不可重復 deep:字符串長度 pos:字符串結尾節點編號int last[N];//最后一次出現的位置 int insert_word() {int len=strlen(s);int pos=0;for(int i=0;i<len;i++){int to=s[i]-'a';if(!trie[pos][to]){trie[pos][to]=++cnt;deep[cnt]=i+1;} pos=trie[pos][to];}return pos; }void getfail() {queue<int>q;for(int i=0;i<26;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<26;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];}} }void search_word() {int len=strlen(str),pos=0;for(int i=0;i<len;i++){int to=str[i]-'a';pos=trie[pos][to];int k=pos;while(k){num[k][0]++;if(i-last[k]>=deep[k]){num[k][1]++;last[k]=i;}k=fail[k];}} }void init() {cnt=0;memset(pos,0,sizeof(pos));memset(trie,0,sizeof(trie));memset(num,0,sizeof(num));memset(last,-1,sizeof(last)); }int main() { //#ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); //#endif // ios::sync_with_stdio(false);int kase=0;while(scanf("%s",str)!=EOF){init();int n;scanf("%d",&n);for(int i=1;i<=n;i++){scanf("%d%s",type+i,s);pos[i]=insert_word();}getfail();search_word();printf("Case %d\n",++kase);for(int i=1;i<=n;i++)printf("%d\n",num[pos[i]][type[i]]);putchar('\n');}return 0; }?
總結
以上是生活随笔為你收集整理的ZOJ - 3228 Searching the String(AC自动机求不重复子串出现次数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客 - 树上博弈(思维)
- 下一篇: HDU - 4511 小明系列故事——女