bzoj2938AC自动机+拓扑排序

问是否存在,无限长的串保证没有病毒串。实际上就是看看能否在ac自动机上无限走

 

处理出ac自动机安全图之后,拓扑排序就好

#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#define maxn 30005
using namespace std;

char s[30005];
int n,ch[maxn][2],fail[maxn],tot;
inline int idx(char ch){return ch-'0';}
bool b[maxn],o[maxn];

void insert(char *s)
{
	int id,len=strlen(s),now=0;
	for (int i=0;i<len;i++)
	{
		id=idx(s[i]);
		if (!ch[now][id]) ch[now][id]=++tot;
		now=ch[now][id];
	}
	b[now]=true;
}

queue<int> q;
void getfail()
{
	for (int i=0;i<=1;i++) if (ch[0][i]) q.push(ch[0][i]);
	while (!q.empty())
	{
		int v,u=q.front();q.pop();
		for (int i=0;i<=1;i++)
		if (v=ch[u][i])
		{
			int t=fail[u];
			while (ch[t][i]==0&&t!=0) t=fail[t];
			t=ch[t][i];
			fail[v]=t;
			if (b[t]) b[v]=true;
			q.push(v);
		}
	}
}

void work1()
{
	q.push(0);
	while (!q.empty())
	{
		int u=q.front();q.pop();
		o[u]=true;
		for (int i=0;i<=1;i++) if (ch[u][i]&&!b[ch[u][i]])q.push(ch[u][i]);
	}
}
bool ans;
int head[maxn],to[maxn*5],pre[maxn*5],tt,du[maxn],id[maxn];
void addedge(int u,int v)
{
	if (v==0) return;
	du[v]++;
	to[++tt]=v;pre[tt]=head[u];head[u]=tt;
}
void work2()
{
	int m=0;
	for (int i=0;i<=tot;i++) if (o[i]) id[i]=++m;
	for (int i=0;i<=tot;i++) if (o[i])
	{
		int u;
		for (int j=0;j<=1;j++)
		{
			u=i;
			while (ch[u][j]==0&&u!=0) u=fail[u];
			u=ch[u][j];
			addedge(id[i],id[u]);
		}
	}
	for (int i=1;i<=m;i++) if (du[i]==0) q.push(i);
	int num=0;
	while (!q.empty())
	{
		num++;
		int u=q.front();q.pop();
		for (int i=head[u];i;i=pre[i])
		{
			du[to[i]]--;
			if (du[to[i]]==0) q.push(to[i]);
		}
	}
	if (num==m) ans=true;else ans=false;
}

int main()
{
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
	{
		scanf("%s",s);
		insert(s);
	}
	getfail();
	work1();
	work2();
	if (ans) printf("NIE");else printf("TAK");
	return 0;
}

总结

1:ac自动机的安全图,总会有特殊的作用,作为一个图来说他本身就有图的性质,而作为ac自动机的组成部分又有自己的意义


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值