BZOJ [Poi2000]病毒 AC自动机_DFS_细节
Code:
#include<bits/stdc++.h>
#define setIO(s) freopen(s".in","r",stdin)
#define maxn 40000
#define N 2
using namespace std;
char str[maxn];
queue<int>Q;
int ch[maxn][3], tag[maxn], f[maxn], vis[maxn], done[maxn];
int tot,root=0;
void ins(char p[])
{
int n=strlen(p+1),cur=0;
for(int i=1;i<=n;++i)
{
int c=p[i]-'0';
if(!ch[cur][c]) ch[cur][c]=++tot;
if(tag[cur]) tag[ch[cur][c]]=1;
cur=ch[cur][c];
}
tag[cur]=1;
}
void build()
{
for(int i=0;i<2;++i) if(ch[root][i]) Q.push(ch[root][i]);
while(!Q.empty())
{
int u=Q.front();Q.pop();
for(int i=0;i<N;++i)
{
int q=ch[u][i];
if(!q)
{
ch[u][i]=ch[f[u]][i];
continue;
}
f[q]=ch[f[u]][i], tag[q]|=tag[f[q]];
Q.push(q);
if(tag[u])
tag[q]=1;
}
}
}
void dfs(int u)
{
if(vis[u])
{
printf("TAK\n");
exit(0);
}
if(tag[u] || done[u]) return;
done[u]=vis[u]=1;
dfs(ch[u][0]);
dfs(ch[u][1]);
vis[u]=0;
}
int main()
{
// setIO("input");
int tot;
scanf("%d",&tot);
while(tot--) scanf("%s",str+1), ins(str);
build();
dfs(0);
printf("NIE\n");
return 0;
}