hdu 3695 Computer Virus on Planet Pandora ac自动机

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define SIGMA_SIZE 30
#define MAXNODE 300000
int ch[MAXNODE][SIGMA_SIZE];
int f[MAXNODE];    // fail函数
int val[MAXNODE];  // 每个字符串的结尾结点都有一个非0的val
int last[MAXNODE]; // 输出链表的下一个结点
int sz;
char str1[1100],str2[6000100],str3[6000100];
bool hash[1000];
void init()
{
    sz = 1;
    memset(ch[0], 0, sizeof(ch[0]));
    memset(val, 0, sizeof(val));
}
  // 字符c的编号
int idx(char c)
{
    return c-'A';
}

  // 插入字符串。v必须非0
void insert(char *s, int v)
{
    int u = 0, n = strlen(s);
    for(int i = 0; i < n; i++)
    {
        int c = idx(s[i]);
        if(!ch[u][c])
        {
            memset(ch[sz], 0, sizeof(ch[sz]));
            val[sz] = 0;
            ch[u][c] = sz++;
        }
        u = ch[u][c];
    }
    val[u] = v;
}

  // 递归打印以结点j结尾的所有字符串
void print(int j)
{
    if(j&&hash[val[j]]==0)
    {
        hash[val[j]]=1;
        print(last[j]);
    }
}

  // 在T中找模板
void find(char* T)
{
    int n = strlen(T);
    int j = 0; // 当前结点编号,初始为根结点
    for(int i = 0; i < n; i++)
    { // 文本串当前指针
        int c = idx(T[i]);
        while(j && !ch[j][c]) j = f[j]; // 顺着细边走,直到可以匹配
        j = ch[j][c];
        if(val[j]) print(j);
        else if(last[j]) print(last[j]); // 找到了!
    }
}

  // 计算fail函数
void getFail()
{
    queue<int> q;
    f[0] = 0;
    // 初始化队列
    for(int c = 0; c < SIGMA_SIZE; c++)
    {
      int u = ch[0][c];
      if(u) { f[u] = 0; q.push(u); last[u] = 0; }
    }
    // 按BFS顺序计算fail
    while(!q.empty())
    {
        int r = q.front(); q.pop();
        for(int c = 0; c < SIGMA_SIZE; c++)
        {
            int u = ch[r][c];
            if(!u) continue;
            q.push(u);
            int v = f[r];
            while(v && !ch[v][c]) v = f[v];
            f[u] = ch[v][c];
            last[u] = val[f[u]] ? f[u] : last[f[u]];
        }
    }
}

void decode(char *s,char *s2)
{
    int i,j,k;
    j=i=0;
    while(s[i])
    {
        if(s[i]=='[')
        {
            int m=0;
            i++;
            while(s[i]>='0'&&s[i]<='9')
            {
                m*=10;
                m+=s[i]-'0';
                i++;
            }
            char r=s[i++];
            for(int k=0;k<m;k++) s2[j++]=r;
            i++;
        }
        else s2[j++]=s[i++];
    }
    s2[j]='';
}
int main()
{
    int cas;
    scanf("%d",&cas);
    while(cas--)
    {
        int num,i;
        scanf("%d",&num);
        init();
        for(i=1;i<=num;i++)
        {
            scanf("%s",str1);
            insert(str1,i);
        }
        getFail();
        scanf("%s",str2);
        decode(str2,str3);
        memset(hash,0,sizeof(hash));
        find(str3);
        strrev(str3);
        find(str3);
        int sum=0;
        for(i=1;i<=num;i++) if(hash[i]) sum++;
        printf("%d
",sum);
    }
    return 0;
}


 

原文地址:https://www.cnblogs.com/vermouth/p/3832192.html