LOJ10058(BZOJ4327)

版权声明:发现蒟蒻ff_666,但转载请注明 https://blog.csdn.net/qq_42403731/article/details/82020693

LOJ10058

AC自动机,我们就是在Trie上用nxt指针跳来跳去。。
那么假如我们跳到一个节点x上,就说明Trie上0~x一路遍历下来组成的字符串在模板串中出现过
这样我们就在正常做AC自动机时打标记
之后从词尾位置往上跳到第一个标记即可。。

#include<bits/stdc++.h>
#define gt() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++)
#define pt(ch) (Top<1000000?St[Top++]=ch:(fwrite(St,1,1000000,stdout),St[(Top=0)++]=ch))
using namespace std;
int Top;static char St[1000000],buf[1000000],*p1=buf,*p2=buf;
const int maxs=(1e7)+5,maxm=(1e5)+5;;
int n,m,que[maxs],len[maxm];char s[maxs],mp[130];;
struct Trie{
    int tot,c[maxs][5],End[maxm],fa[maxs],nxt[maxs];bool vis[maxs];
    void insert(int x){
        int rot=0,Rot=0;char ch=gt();while(!isupper(ch)) ch=gt();
        while(isupper(ch)) ++len[x],ch=mp[ch],fa[rot=(c[rot][ch]?c[rot][ch]:c[rot][ch]=++tot)]=Rot,Rot=rot,ch=gt();
        End[x]=rot;
    }
}AC;
void write(int x){if(x>9) write(x/10);pt(x%10+'0');}
void getnxt(){
    int hed=0,tal=0,x;
    for(int i=0;i<4;i++) if(AC.c[0][i]) que[++tal]=AC.c[0][i];
    while(hed!=tal){
        x=que[++hed];
        for(int i=0;i<4;i++)
          if(AC.c[x][i]) AC.nxt[que[++tal]=AC.c[x][i]]=AC.c[AC.nxt[x]][i];
            else AC.c[x][i]=AC.c[AC.nxt[x]][i];
    }
}
int main(){
    scanf("%d%d",&n,&m);char ch=gt();while(!isupper(ch)) ch=gt();
    mp['N']=0,mp['E']=1,mp['S']=2,mp['W']=3;
    for(int i=1;i<=n;i++,ch=gt()) s[i]=mp[ch];
    for(int i=1;i<=m;i++) AC.insert(i);
    getnxt();
    for(int i=1,rot=0;i<=n;i++){
        rot=AC.c[rot][s[i]];
        for(int t=rot;!AC.vis[t]&&t;t=AC.nxt[t]) AC.vis[t]=1;
    }
    AC.vis[0]=1;
    for(int i=1,x;i<=m;i++){
        x=AC.End[i];
        while(!AC.vis[x]) x=AC.fa[x],len[i]--;
        write(len[i]),pt('\n');
    }
    fwrite(St,1,Top,stdout);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42403731/article/details/82020693
今日推荐