hdu 3065 病毒持续侵袭中 AC自动机入门题

点击打开链接

题意:给出母串s长度<=2e6 n个模式串 n<=1e3 每个长度<=50 问每个模式串在母串中出现多少次

aho中记录模式串出现次数,用AC自动机进行匹配即可 

ac自动机时间复杂度:
  假设有N个模式串,平均长度为L;文章长度为M。 建立Trie树:O(N*L) 建立fail指针:O(N*L) 模式匹配:O(M*L) 所以,总时间复杂度为:O( (N+M)*L )。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e6+20;
struct Aho{
	int sz,chd[N][26],f[N],last[N],v[N];
	int cnt[N];//第i个模式串出现次数 
	void init()
	{
		sz=1;
		memset(cnt,0,sizeof(cnt));
		memset(v,0,sizeof(v));
		memset(f,0,sizeof(f));
		memset(chd[0],0,sizeof(chd[0]));	
	}
	void insert(char *s,int x)
	{
		int u=0,i=0;
		while(s[i])
		{
			int id=s[i]-'A';	
			if(chd[u][id]==0)
			{
				memset(chd[sz],0,sizeof(chd[sz]));
				chd[u][id]=sz++;
			}
			u=chd[u][id];
			i++;
		}
		v[u]=x;//记录编号	
	}	
	void getFail()
	{
		queue<int> q;
		f[0]=0;
		for(int c=0;c<26;c++)
		{
			int u=chd[0][c];
			if(u)
			{
				f[u]=0;q.push(u);last[u]=0;
			}
		}
		while(!q.empty())
		{
			int r=q.front();
			q.pop();
			for(int c=0;c<26;c++)
			{
				int u=chd[r][c];
				if(!u)
				{
					chd[r][c]=chd[f[r]][c];
					//小优化,匹配中失配时不需重复找失配边 
					continue; 
				}
				q.push(u);
				int x=f[r];
				while(x&&!chd[x][c])
					x=f[x];
				f[u]=chd[x][c];
				last[u]=v[f[u]]?f[u]:last[f[u]];
			
			
			}
		}
	}
	void solve(int j)
	{
		if(!j)
		return;
		if(v[j])
		{
			cnt[v[j]]++;
		}
		solve(last[j]);
	}
	void find(char *s)
	{
		int j=0;
		for(int i=0;s[i];i++)
		{
			if(s[i]>'Z'||s[i]<'A')
			{
				//遇到非法字符,从Trie根开始重新配 
				j=0;
				continue;
			}
			int id=s[i]-'A';
			j=chd[j][id];
			if(v[j])
			solve(j);
			else if(last[j])
			solve(last[j]);
		}
	}
}aho;
char s[2234567];  
char dic[2000][100];
int main()
{
	int n;
	while(cin>>n)
	{
		aho.init();
		for(int i=1;i<=n;i++)
		{
			scanf("%s",dic[i]);
			aho.insert(dic[i],i);
		}
		aho.getFail();
		scanf("%s",s);
		aho.find(s);
		for(int i=1;i<=n;i++)
		{
			if(aho.cnt[i])
			printf("%s: %d\n",dic[i],aho.cnt[i]);
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值