bzoj4327 AC自动机

原题:https://www.lydsy.com/JudgeOnline/problem.php?id=4327

题解:将模式串加入ac自动机跑主串。对于每一个前缀,打上标记跳失败指针,统计答案即可。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
const int N=1e7+10,MAXL=110,Z=4,M=1e5+10;
map<char,int> temp;
queue<int> q;
int ch[N][Z],end[M],len[M],nxt[N],fa[N],n,m,tot;
bool f[N]={0};
char s[N],t[MAXL];
inline void init(){
	temp['N']=0;temp['S']=1;temp['W']=2;temp['E']=3;
	tot=1;f[0]=f[1]=1;//终点 
}

inline void ins(char *s,int ind){
	len[ind]=strlen(s+1);int p=1;
	for(int i=1,c;i<=len[ind];i++){
		c=temp[s[i]];
		if(!ch[p][c]) ch[p][c]=++tot;
		fa[ch[p][c]]=p;//父节点 
		p=ch[p][c];
		
	}
	end[ind]=p;
}
inline void pre(){	 
	for(int i=0;i<Z;i++) ch[0][i]=1;//失败指针 
	q.push(1);nxt[1]=0;
	while(!q.empty()) {
		int u=q.front();q.pop();
		for(int i=0;i<Z;i++){
			if(!ch[u][i]) ch[u][i]=ch[nxt[u]][i];
			else {
				q.push(ch[u][i]);
				int v=nxt[u];
				while(v>0 && !ch[v][i]) v=nxt[v];
				nxt[ch[u][i]]=ch[v][i];
			} 	
		}
	}
	int p=1;
	for(int i=1,c;i<=n;i++){//跑主串,打标记 
		c=temp[s[i]];
		for(int k=ch[p][c];k>1&&!f[k];k=nxt[k]) f[k]=1;
		p=ch[p][c];
		
	}
} 

int main(){
//	freopen("bzoj4327.in","r",stdin);
	init();
	scanf("%d%d%s",&n,&m,s+1);
	for(int i=1;i<=m;i++){
		scanf("%s",t+1);ins(t,i);
	}
	pre();
	for(int i=1;i<=m;i++){
		for(int k=end[i];k && !f[k];k=fa[k]) len[i]--;//统计答案 
		printf("%d\n",len[i]);
	}
	return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值