背景:
暑假集训七月份最后一天,写写原来没有写过的
blog
\text{blog}
blog吧。
题目传送门:
https://www.luogu.org/problemnew/show/P2444
题意:
给出
n
n
n个字符串,问能否组成不含这
n
n
n个字符串作为子串的字符串。
思路:
我们考虑
fail
\text{fail}
fail指针的本质。
如果当前不含这
n
n
n个字符转作为子串,则会往下匹配,失配,跳
fail
\text{fail}
fail;往下匹配,失配,跳
fail
.
.
.
\text{fail}...
fail...因此一定会陷入一个环中。
我们在
fail
\text{fail}
fail树上若找到环,则一定是有可能的;反之不存在。
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<algorithm>
#define mod 10007
using namespace std;
int n,len=0;
char s[30010];
bool bz[30010],zhan[30010];
queue<int> f;
struct node
{
int fail,tot;
int son[2];
node()
{
fail=tot=0;
memset(son,0,sizeof(son));
}
} tr[30010];
void build(char *s)
{
int l=strlen(s),x=0;
for(int i=0;i<l;i++)
{
if(!tr[x].son[s[i]-'0']) tr[x].son[s[i]-'0']=++len;
x=tr[x].son[s[i]-'0'];
}
tr[x].tot=1;
}
void get_fail()
{
while(!f.empty()) f.pop();
for(int i=0;i<2;i++)
if(tr[0].son[i])
{
tr[tr[0].son[i]].fail=0;
f.push(tr[0].son[i]);
}
while(!f.empty())
{
int x=f.front();
f.pop();
for(int i=0;i<2;i++)
{
int y=tr[x].son[i];
if(y)
{
tr[y].fail=tr[tr[x].fail].son[i];
tr[y].tot|=tr[tr[y].fail].tot;
f.push(y);
}
else tr[x].son[i]=tr[tr[x].fail].son[i];
}
}
}
void dfs(int x)
{
if(zhan[x])
{
printf("TAK");
exit(0);
}
if(bz[x]||tr[x].tot) return;
bz[x]=zhan[x]=true;
if(tr[x].son[0]) dfs(tr[x].son[0]);
if(tr[x].son[1]) dfs(tr[x].son[1]);
zhan[x]=false;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%s",s);
build(s);
}
tr[0].fail=0;
get_fail();
dfs(0);
printf("NIE");
}