AC自动机 1AC+1WA 求调,没看出有错误。
查看原帖
AC自动机 1AC+1WA 求调,没看出有错误。
477258
charleshe楼主2022/6/12 12:42

RT。

#include<bits/stdc++.h>
using namespace std;
char T[1000005],t[1000005];
int ch[500005][30],k,ans,tot;
int bo[500005]; 
queue<int>q;
int nxt[500005];
void insert(char *s){
    int len=strlen(s),u=1;
    for(int i=0;i<len;i++){
        int c=s[i]-'a';
        if(!ch[u][c]){
            ch[u][c]=++tot;
        }   
        u=ch[u][c];
    }
    bo[u]+=1;
    return;
}
void build_nxt(){
    for(int i=0;i<=25;i++){
        if(ch[0][i]) nxt[ch[0][i]]=0,q.push(ch[0][i]);
    }
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int i=0;i<=25;i++){
            if(!ch[u][i])ch[u][i]=ch[nxt[u]][i];
            else{
                q.push(ch[u][i]);
                int v=nxt[u];
                nxt[ch[u][i]]=ch[v][i];
            }
        } 
    }
}
void AC_find(char *s){
    int u=1,m=strlen(s);
    for(int i=0;i<m;i++){
        int c=s[i]-'a';
        int k=ch[u][c];
        while(k>1){
            ans+=bo[k];
            bo[k]=0;
            k=nxt[k];
        }
        u=ch[u][c];
    }
    return;
}
int main(){
    ans=0;tot=1;
    for(int i=0;i<26;++i) ch[0][i]=1,ch[1][i]=0;
    scanf("%d",&k);
    for(int i=1;i<=k;i++){
        scanf("%s",t);
        insert(t);
    } 
    scanf("%s",T);
    build_nxt();
    AC_find(T);
    printf("%d\n",ans);
    return 0;
}
2022/6/12 12:42
加载中...