[bzoj2938][Poi2000]病毒 AC自动机

2938: [Poi2000]病毒

Time Limit: 1 Sec   Memory Limit: 128 MB
[ Submit][ Status][ Discuss]

Description

二进制病毒审查委员会最近发现了如下的规律:某些确定的二进制串是病毒的代码。如果某段代码中不存在任何一段病毒代码,那么我们就称这段代码是安全的。现在委员会已经找出了所有的病毒代码段,试问,是否存在一个无限长的安全的二进制代码。
示例:
例如如果{011, 11, 00000}为病毒代码段,那么一个可能的无限长安全代码就是010101…。如果{01, 11, 000000}为病毒代码段,那么就不存在一个无限长的安全代码。
任务:
请写一个程序:
l         读入病毒代码;
l         判断是否存在一个无限长的安全代码;
l         将结果输出

Input

 
第一行包括一个整数n,表示病毒代码段的数目。以下的n行每一行都包括一个非空的01字符串——就是一个病毒代码段。所有病毒代码段的总长度不超过30000。

Output

你应在在文本文件WIN.OUT的第一行输出一个单词:
l         TAK——假如存在这样的代码;
l         NIE——如果不存在。

Sample Input

3
01
11
00000

Sample Output

NIE

HINT

补全trie图,找是否存在不经过结尾节点的环
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
const int N = 30000 + 5;
int ch[N][2],fail[N],n,sz;
char s[N]; bool is_end[N],vis[N];
queue<int> q;
int cnt,last[N],in[N]; struct Edge{ int to,next; }e[N*2];
void insert(){
	int len = strlen(s), now = 0;
	for( int i = 0; i < len; i++ ){
		int x = s[i] - '0';
		if( !ch[now][x] ) ch[now][x] = ++sz;
		now = ch[now][x];
	}
	is_end[now] = true;
	return;
}
void make_fail(){
	while( !q.empty() ) q.pop();
	for( int i = 0; i <= 1; i++ ) if( ch[0][i] ) q.push(ch[0][i]);
	while( !q.empty() ){
		int now = q.front(); q.pop();
		for( int i = 0; i <= 1; i++ ){
			if( !ch[now][i] ){
				ch[now][i] = ch[fail[now]][i];
				continue;
			}
			fail[ch[now][i]] = ch[fail[now]][i];
			if( is_end[fail[ch[now][i]]] ) is_end[ch[now][i]] = true;
			q.push(ch[now][i]);
		}
	}
}
void insert1( int u, int v ){ e[++cnt].to = v; e[cnt].next = last[u]; last[u] = cnt;}
void dfs( int x ){
	vis[x] = 1;
	for( int i = 0; i <= 1; i++ ){
		insert1( x, ch[x][i] ); in[ch[x][i]]++;
		if( !vis[ch[x][i]] && !is_end[ch[x][i]] ) dfs(ch[x][i]);
	}
}
bool top(){
	int tot = 0;
	while( !q.empty() ) q.pop();
	for( int i = 0; i <= sz; i++ ) if( !in[i] ) q.push(i);
	while( !q.empty() ){
		int now = q.front(); q.pop(); tot++;
		for( int i = last[now]; i; i = e[i].next ){
			in[e[i].to]--;
			if( !in[e[i].to] ) q.push(e[i].to);
		}
	}
	return tot < sz;
}
int main(){
	scanf("%d", &n);
	for( int i = 1; i <= n; i++ ){
		scanf("%s", s); insert();
	}
	make_fail(); dfs(0);
	puts(top()?"TAK":"NIE");
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值