社区讨论

求助,96,wa一个点

P5357【模板】AC 自动机参与者 2已保存回复 1

讨论操作

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

当前回复
1 条
当前快照
1 份
快照标识符
@locnufr5
此快照首次捕获于
2023/10/30 16:51
2 年前
此快照最后确认于
2023/11/05 03:52
2 年前
查看原帖
CPP
#include<bits/stdc++.h>
#define re register
#define inf 1e18
const int sz=2e6+5;
using namespace std;
int read()
{
	char c=getchar();
	int r=0,f=1;
	while((c<'0'||c>'9')&&c!='-')
		c=getchar();
	if(c=='-') {
		f=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9') {
		r=r*10+c-'0';
		c=getchar();
	}
	return f*r;
}
struct node
{
	int ch[26],fail,siz;
	bool end;
}trie[200000];
struct node1
{
	int nxt,to;
}e[200000];
int tot = 0,head[sz];
void add_edge(int x,int y)
{
	e[++tot]=(node1){head[x],y};
	head[x]=tot;
}
bool end[sz];
int cnt=1,match[sz];
void insert(char *a,int num)
{
	int len=strlen(a+1),p=1;
	for(int i=1;i<=len;i++)
	{
		int c=a[i]-'a';
		if(!trie[p].ch[c]) trie[p].ch[c]=++cnt;
		p=trie[p].ch[c];
	}
	trie[p].end=1;
	match[num]=p;
}
void getfail()
{
	queue<int >q;
	for(int i=0;i<26;i++) trie[0].ch[i]=1;
	q.push(1);
	while(!q.empty())
	{
		int top=q.front();q.pop();
		int Fail=trie[top].fail;
		for(int i=0;i<26;i++)
		{
			if(trie[top].ch[i])
			{
				trie[trie[top].ch[i]].fail=trie[Fail].ch[i];
				q.push(trie[top].ch[i]);
			}
			else
				trie[top].ch[i]=trie[Fail].ch[i];
		}
	}
}
void query(char *a)
{
	int len=strlen(a+1),p=1;
	for(int i=1;i<=len;i++)
	{
		int c=a[i]-'a';
		p=trie[p].ch[c];
		trie[p].siz++;
	}
}
void dfs(int now)
{
	for(int i=head[now];i;i=e[i].nxt)
	{
		dfs(e[i].to);
		trie[now].siz+=trie[e[i].to].siz;
	}
}
char a[sz],b[sz];
signed  main()
{
		cnt=1,tot=0;
		int n=read();
		for(int i=1;i<=n;i++)
		{
			scanf("%s",a+1);
			insert(a,i);
		}
		getfail();
		scanf("%s",b+1);
		query(b);
		for(int i=2;i<=cnt;i++) add_edge(trie[i].fail,i);
		dfs(1);
		for(int i=1;i<=n;i++)
			cout<<trie[match[i]].siz<<endl;
}
/*
3
a
aa
aa
aaa
 */

回复

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

正在加载回复...