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]);
			}
			else
				trie[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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章