社区讨论

全T求助,悬一关

P3808AC 自动机(简单版)参与者 3已保存回复 2

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
2 条
当前快照
1 份
快照标识符
@lwrlv9e6
此快照首次捕获于
2024/05/29 17:09
2 年前
此快照最后确认于
2024/05/29 20:28
2 年前
查看原帖
CPP
#include <bits/stdc++.h>
#define int long long
using namespace std;

const int N=1e6+5;

int n,cnt=1,ans;
int v[N];
char s[N];

struct node
{
	int fail,tag;
	int ch[30];
}t[N];

inline void build_fail()
{
	queue<int> q;
	
	q.push(1);
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		for(int i=0;i<26;i++)
		{
			int v=t[u].ch[i];
			if(!v) continue;
			q.push(v);
			int ti=t[u].fail;
			while(ti&&!t[ti].ch[i]) ti=t[ti].fail;
			t[v].fail=ti?t[ti].ch[i]:1;
		}
	}
	return ;
}

inline void query(char s[])
{
	int x=1;
	
	for(int i=0;i<strlen(s);i++)
	{
		int y=s[i]-'a';
		while(x&&!t[x].ch[y]) x=t[x].fail;
		x=x?t[x].ch[y]:1; y=x;
		while(y&&!v[y])
		{
			ans+=t[y].tag;
			t[y].tag=0;
			v[y]=1;
			y=t[y].fail;
		}
	}
}

signed main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%s",s);
		int rt=1;
		
		for(int j=0;j<strlen(s);j++)
		{
			int x=s[j]-'a';
			if(!t[rt].ch[x])
				t[rt].ch[x]=++cnt;
			rt=t[rt].ch[x];
		}
		t[rt].tag++;
	}
	build_fail();
	scanf("%s",s);
	query(s);
	printf("%d",ans);
	return 0;
}

回复

2 条回复,欢迎继续交流。

正在加载回复...