问是否存在,无限长的串保证没有病毒串。实际上就是看看能否在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自动机的组成部分又有自己的意义