AC自动机超级模板题hihoCoder1036

点击打开链接

;原理题目里直接有解释】



# include<iostream>
# include<cstdio>
# include<queue>
# include<cstring>
# include<algorithm>
using namespace std;
 
const int N=1000000;
 
int cnt;
int ch[N+5][26];
int f[N+5],val[N+5];
 
void init()
{
    cnt=0;
    memset(ch,0,sizeof(ch));
    memset(val,0,sizeof(val));
}
 
int idx(char x)
{
    return x-'a';
}
 
void insert(char *p)
{
    int n=strlen(p);
    int root=0;
    for(int i=0;i<n;++i){
        int c=idx(p[i]);
        if(!ch[root][c]) ch[root][c]=++cnt;
        root=ch[root][c];
    }
    val[root]=1;
}
 
void getFail()
{
    queue<int>q;
    f[0]=0;
    for(int i=0;i<26;++i) if(ch[0][i]){
        f[ch[0][i]]=0;
        q.push(ch[0][i]);
    }
    while(!q.empty()){
        int u=q.front();
        q.pop();
        if(val[f[u]]) val[u]=1;
        for(int i=0;i<26;++i){
            if(ch[u][i]){
                q.push(ch[u][i]);
                f[ch[u][i]]=ch[f[u]][i];
            }else{
                ch[u][i]=ch[f[u]][i];
            }
        }
    }
}
 
char p[N+5];
 
bool match(char *p)
{
    int n=strlen(p);
    int u=0;
    for(int i=0;i<n;++i){
        int c=idx(p[i]);
        u=ch[u][c];
        if(val[u]) return true;
    }
    return false;
}
 
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        init();
        for(int i=0;i<n;++i){
            scanf("%s",p);
            insert(p);
        }
        getFail();
        scanf("%s",p);
        if(match(p)) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_36215255/article/details/79934427
今日推荐