Luo Gu 2444: Virus

Luo Gu 2444: Virus

Meaning of the questions:

  • There are n binary string, called viruses.
  • Construct a binary string, so that no virus present in a binary string in this configuration.
  • Whether the answer can construct such a string.

Ideas:

  • AC automaton.
  • AC automaton is a multi-pattern matching data structure.
  • We first construct \ (trie \) tree and build a \ (fail \) pointer.
  • This time \ (trie \) tree is no longer \ (trie \) tree, and after the addition of several \ (fail \) pointer becomes a directed graph.
  • If there is such an infinite string, making sure that no virus is a string of his child, then what will happen?
  • Take this string to match the automatic machine, no matter how kind is also not the end position to a virus string, because the string constructed infinitely long, so he will be going round in circles in the infinitely automata in.
  • So the question into:
    • Get a ring on the AC automatic machine without this ring node is the end of the string virus.
  • Note that a node \ (fail \) node if the node is the end, then he should also be a self-end node.
  • Draw a map to see
#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e4 + 10;
char s[maxn];
int n;

struct AC_Automaton
{
    int trie[maxn][5];
    int val[maxn];
    int fail[maxn];
    int tot;

    void ins(char *str)
    {
        int len = strlen(str), p = 0;
        for(int k = 0; k < len; k++)
        {
            int ch = str[k] - '0';
            if(trie[p][ch] == 0) trie[p][ch] = ++tot;
            p = trie[p][ch];
        }
        val[p] = 1;
    }

    void build()
    {
        queue<int> q;
        for(int i = 0; i < 2; i++)
        {
            if(trie[0][i])
            {
                //第二层指向根节点
                fail[trie[0][i]] = 0;
                q.push(trie[0][i]);
            }
        }
        while(q.size())
        {
            int x = q.front(); q.pop();
            for(int i = 0; i < 2; i++)
            {
                if(trie[x][i])
                {
                    fail[trie[x][i]] = trie[fail[x]][i];
                    val[trie[x][i]] |= val[fail[trie[x][i]]];
                    q.push(trie[x][i]);
                }
                else trie[x][i] = trie[fail[x]][i];
            }
        }
    }

    bool v1[maxn];
    
    void dfs(int x)
    {
        if(v1[x])
        {
            puts("TAK");
            exit(0);
        }
        if(val[x]) return;
        v1[x] = 1;
        if(trie[x][0]) dfs(trie[x][0]);
        if(trie[x][1]) dfs(trie[x][1]);
        v1[x] = 0;
    }
}AC;


int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
    {
        scanf("%s", s);
        AC.ins(s);
    } AC.build();
    AC.dfs(0); //从字典树根节点开始找环
    puts("NIE"); //不存在无限的串
    return 0;
}

Guess you like

Origin www.cnblogs.com/zxytxdy/p/12233485.html