【AC自动机】Indie Album

假装是门

题目

多个模式串和多个文本串匹配

题解

将所有模式串和文本串都放到AC自动机里
遍历整个Tire树,将经过的点点亮,如果遇见文本串的终结点,就询问对应模式串的终结点的Fail树上的子树被点亮的个数
需要将Fail树重新建图,并用dfs序维护子树信息
请务必明确哪一个是文本串,哪一个是模式串


以下是不想再看到的恶心代码

#include<bits/stdc++.h>
#define re register
using namespace std;
const int N=1e6+10,M=2*N;
int n,q;
int head[N],nex[M],to[M],tot;
void build(int u,int v){tot++;nex[tot]=head[u];to[tot]=v;head[u]=tot;}
//---
int id[N];
int t[N][30],all;
int f[N],val[N];
int sam[N],bl[N],dep[N];
inline int putin(char *s,int p,int bto=0)
{
	for(re int i=0;s[i];++i)
	{
		int now=s[i]-'a';
		if(!t[p][now])t[p][now]=++all;
		p=t[p][now];
	}
	if(bto)
	{
		if(!bl[p])bl[p]=bto;
		else	  sam[bto]=bl[p];
		val[p]=1;		
	}
	return p;
}
inline void get_fail()
{
	queue<int>q;
	int p=0;
	for(re int i=0;i<26;++i)
	if(t[p][i])q.push(t[p][i]),dep[t[p][i]]=dep[p]+1;
	while(!q.empty())
	{
		int u=q.front();q.pop();
		for(re int i=0;i<26;++i)
		{
			p=t[u][i];
			if(!p)
			{
				t[u][i]=t[f[u]][i];
				continue;
			}
			q.push(p);
			int pre=f[u];
			while(pre&&!t[pre][i])pre=f[pre];
			f[p]=t[pre][i];
			dep[p]=dep[u]+1;
		}build(u,f[u]);build(f[u],u);
	}
}
//--
int dfn[N],sz[N],cnt;
inline void dfs(int u)
{
	dfn[u]=++cnt,sz[u]=1;
	for(re int i=head[u];i;i=nex[i])
	{
		int v=to[i];if(dfn[v])continue;
		dfs(v);sz[u]+=sz[v];
	}
}
//---
int T[N],key;
inline int lowbit(int x){return x&(-x);}
inline void add(int i){for(;i<=cnt;i+=lowbit(i))T[i]+=key;}
inline int qur(int i){int tmp=0;for(;i;i-=lowbit(i))tmp+=T[i];return tmp;}
//----
struct qus{
	int x,y,id;
	friend bool operator<(const qus a,const qus b){return a.x<b.x;}
}bt[N];
int res[N];
char s[N];

int fr[N];
inline void DFS(int p)
{
	key= 1;add(dfn[p]);
	if(bl[p])
	{
		int pre=fr[bl[p]];
		while(bt[pre].x==bl[p])
		{
			int is=bt[pre].y;
			res[bt[pre].id]=qur(dfn[is]+sz[is]-1)-qur(dfn[is]-1);
			pre++;
		}
	}
	for(re int i=0;i<26;++i)
	{
		int v=t[p][i];
		if(dep[v]<=dep[p])continue;
		DFS(v);
	}
	key=-1;add(dfn[p]);
}
int main()
{
	scanf("%d",&n);
	for(re int op,x,i=1;i<=n;++i)
	{
		scanf("%d",&op);
		if(op==1)
		{
			scanf("%s",s);
			id[i]=putin(s,0,i);
		}
		else
		{
			scanf("%d%s",&x,s);
			id[i]=putin(s,id[x],i);
		}
	}
	scanf("%d",&q);
	for(re int i=1;i<=q;++i)
	{
		scanf("%d%s",&bt[i].x,s);
		bt[i].id=i;bt[i].y=putin(s,0);
		if(sam[bt[i].x])bt[i].x=sam[bt[i].x];
	}
	get_fail();
	dfs(0);
	sort(bt+1,bt+q+1);
	for(re int i=1;i<=q;++i)
	if(bt[i].x!=bt[i-1].x)fr[bt[i].x]=i;
	DFS(0);
	for(re int i=1;i<=q;++i)
	printf("%d\n",res[i]);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值