virus

https://loj.ac/problem/10062

Title Description

  N given string, character string request if there an infinite length so that it is not a string of n substrings.

Thinking

  When you think of this question may be related to Trie map, you is half the battle. We consider how to solve the answer in Trie map, first of all if there is such an infinitely long substring, then obviously form a ring in Trie map, and this does not ring after the end of each string, and this will be able to ring starting from the root access. We can ask for the ring with dfs, which uses two arrays vis and v, vis indicates whether visited, v indicates that the node is in search of the stack, if you can direct output from the ring.

Code

#include<bits/stdc++.h>
using namespace std;

int ch[30010][2],tot=1;
bool ed[30010];
void insert(char *s)
{
    int u=1,len=strlen(s);
    for(int i=0;i<len;i++)
    {
        int c=s[i]-'0';
        if(!ch[u][c])ch[u][c]=++tot;
        u=ch[u][c];
    }
    ed[u]=1;
}
int nxt[30010];
void getfail()
{
    for(int i=0;i<=1;i++)
        ch[0][i]=1;
    queue<int>q;
    q.push(1);nxt[1]=0;
    while(!q.empty())
    {
        int u=q.front();q.pop();
        for(int i=0;i<=1;i++)
        {
            if(!ch[u][i])ch[u][i]=ch[nxt[u]][i];
            else
            {
                int v=nxt[u];
                q.push(ch[u][i]);
                while(v&&!ch[v][i])v=nxt[v];
                nxt[ch[u][i]]=ch[v][i];
            }
        }
    }
    for(int i=1;i<=tot;i++)
    {
        int v=nxt[i];
        while(v)ed[i]|=ed[v],v=nxt[v];
    }
}
bool vis[30010],v[30010];
void dfs(int u)
{
    vis[u]=1;v[u]=1;
    for(int i=0;i<=1;i++)
    {
        if(v[ch[u][i]])
        {
            printf("TAK");
            exit(0);
        }
        else if(!ed[ch[u][i]]&&!vis[ch[u][i]])
            dfs(ch[u][i]);
    }
    v[u]=0;
}

char s[30010];
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf(" %s",s);
        insert(s);
    } 
    getfail();
//    for(int i=1;i<=tot;i++)
//        cout<<i<<' '<<nxt[i]<<endl;
    dfs(0);
    printf("NIE"); 
} 

 

Guess you like

Origin www.cnblogs.com/fangbozhen/p/11647520.html