BZOJ 3940: [Usaco2015 Feb]Censoring AC自动机_栈

Code:

#include<bits/stdc++.h>
#define setIO(s) freopen(s".in","r",stdin)  // ,freopen(s".out","w",stdout) 
#define maxn 200000 
using namespace std;
char str[maxn],arr[maxn]; 
int S[maxn],pos[maxn],top; 
namespace AC
{
    #define sigma 30 
    queue<int>Q; 
    int tot=0,root=0; 
    int ch[maxn][30],tag[maxn],f[maxn]; 
    void ins(char p[],int n)
    {
        int x=root; 
        for(int i=1;i<=n;++i)
        {
            int c=p[i]-'a';
            if(!ch[x][c]) ch[x][c]=++tot; 
            x=ch[x][c]; 
        } 
        tag[x]=n;  
    }
    void getfail()
    { 
        for(int i=0;i<sigma;++i) if(ch[root][i]) Q.push(ch[root][i]);    
        while(!Q.empty())
        {
            int u=Q.front();Q.pop(); 
            for(int i=0;i<sigma;++i)
            {
                int q=ch[u][i];
                if(!q) { ch[u][i]=ch[f[u]][i]; continue; }
                Q.push(q); 
                f[q]=ch[f[u]][i];             
            }
        }
    }     
}; 
int main()
{
    // setIO("input");
    int len,m; 
    scanf("%s",str+1),len=strlen(str+1); 
    scanf("%d",&m);  
    for(int i=1,a;i<=m;++i) 
    {
        scanf("%s",arr+1), a=strlen(arr+1), AC::ins(arr,a);
    }
    AC::getfail(); 
    int tr=0; 
    for(int i=1;i<=len;++i)
    { 
        int c=str[i]-'a'; 
        tr=AC::ch[tr][c];   
        pos[i]=tr;             
        S[++top]=i;   
        if(AC::tag[tr]) top -= AC::tag[tr], tr = pos[S[top]];                  
    }        
    for(int i=1;i<=top;++i) printf("%c",str[S[i]]); 
    printf("\n"); 
    return 0; 
}

  

猜你喜欢

转载自www.cnblogs.com/guangheli/p/10951566.html