[BZOJ 1966] [Ahoi2005]VIRUS 病毒检测(Trie / dp)

题目

传送门

题解

方法一:trie树
标签是AC自动机,但明显不是AC自动机啊,根本没有失配指针的过程,只能叫Tire树吧
我们对每一个单词建立好Tire树之后,在树上进行bfs,进行匹配

代码

#include 
#include 
#include 
using namespace std;

const int Maxn = 0x3f3f3f3f;
const int N = 505, L = N << 1, M = L * 350;
int T = 1, n, Ans, len, t = 0, w = 1;
int G[M][4], val[M], Q[M][2];
char s[L], a[N], c[255]; 
bitset vis[M];

inline  Ins()
{
    scanf("%s", a + 1); int l = strlen(a + 1), x = 1;
    for (int i = 1; i <= l; ++i)
    {
        int y = c[a[i]]; 
        if (!G[x][y]) G[x][y] = ++T;
        x = G[x][y];
    }
    val[x]++;
}

inline void Push(const int x, const int stp)
{
    if (!x || stp > len) return;
    if (!vis[x][stp])
    {
        vis[x][stp] = 1; w = (w + 1) % M;   
        Q[w][0] = x; Q[w][1] = stp;
    } 
}

int main()
{
    c['A'] = 0; c['C'] = 1; c['T'] = 2; c['G'] = 3;
    c['?'] = -1; c['*'] = -2;
    scanf("%s", s + 1); len = strlen(s + 1);
    s[0] = '?';
    scanf("%d",&n);
    for (int i = 1; i <= n; ++i) Ins();
    int u, v, I; 
    Q[1][0] = 1; Q[1][1] = 0; vis[1][0] = 1;
    while (t != w)
    {
        t = (t + 1) % M;
        u = Q[t][0]; v = Q[t][1];//0字典树上的位置 1序列中的位置 
        if (s[v] == '*')
            for (int i = 0; i < 4; ++i) Push(G[u][i], v);
        if (v == len) {Ans += val[u]; val[u] = 0; continue;}

        if (c[s[v + 1]] >= 0) Push(G[u][c[s[v + 1]]], v + 1);
        else
        {
             for (int i = 0; i < 4; ++i) Push(G[u][i], v + 1);
             if (s[v + 1] == '*') Push(u, v + 1);
        }
    }
    printf("%d\n",n-Ans);
    return 0;
}
/* A*G?C 3 AGTC AGTGTC AGTGC */

你可能感兴趣的:(Trie,AC自动机)