跳到正文

算法·理论

模板代码——AC自动机

wbqhasvcf约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年11月3日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;

int n,idx,tr[N][26],en[N],fa[N],fail[N],cnt[N],in[N],ans[N];
string s;
void insert(string s,int id)
{
	int p=0;
	for(char i:s)
	{
		int ch=i-'a';
		if(!tr[p][ch])
			tr[p][ch]=++idx;
		p=tr[p][ch];
	}
	if(!en[p]) en[p]=id;
	fa[id]=en[p];
}
void get_fail()
{
	queue<int> q;
	for(int i=0;i<26;i++)
		if(tr[0][i])
			q.push(tr[0][i]);
	while(!q.empty())
	{
		int fr=q.front();
		q.pop();
		for(int i=0;i<26;i++)
		{
			int u=tr[fr][i],v=tr[fail[fr]][i];
			if(u) fail[u]=v,in[v]++,q.push(u);
			else tr[fr][i]=v;
		}
	}
}
void AC_query(string s)
{
	int p=0;
	for(char i:s)
	{
		p=tr[p][i-'a'];
		cnt[p]++;
	}
}
void toposort()
{
	queue<int> q;
	for(int i=1;i<=idx;i++)//从1开始即可,0没必要入队 
		if(in[i]==0)
			q.push(i);
	while(!q.empty())
	{
		int fr=q.front(),u=fail[fr];
		q.pop();
		ans[en[fr]]=cnt[fr];
		cnt[u]+=cnt[fr];
		if(--in[u]==0)
			q.push(u);
	}
}
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>s;
		insert(s,i);
	}
	get_fail();
	cin>>s;
	AC_query(s);
	toposort();
	for(int i=1;i<=n;i++)
		cout<<ans[fa[i]]<<endl;
	return 0;
}
原文