牛客(多校4):Count New String

在这里插入图片描述
在这里插入图片描述

#include<bits/stdc++.h>
using namespace std;
 
const int N=3e6;
 
char s[N];
int T[N][30],fa[N],len[N],cnt,last;
long long ans,pos[N];
int st[N],top;
 
void build(int v){
    int i,p=last,np,q,nq;
    last=np=++cnt;
    len[np]=len[p]+1;
    for(;p&&T[p][v]==0;p=fa[p]) T[p][v]=np;
    if(p==0) fa[np]=1;
    else{
        q=T[p][v];
        if(len[q]==len[p]+1) fa[np]=q;
        else{
            nq=++cnt;
            len[nq]=len[p]+1;
            fa[nq]=fa[q];
            fa[q]=fa[np]=nq;
            for(i=0;i<27;i++) T[nq][i]=T[q][i];
            for(;T[p][v]==q;p=fa[p]) T[p][v]=nq;
        }
    }
    ans+=len[last]-len[fa[last]];
}
int main(){
    int j,i,n,a;
    scanf("%s",s+1);
    n=strlen(s+1);
    cnt=last=pos[n+1]=1;
 
    for(i=n;i;i--){
        while(top&&s[st[top]]<s[i]) top--;
        if(top) a=st[top];
        else a=n+1;
        last=pos[a];
        for(j=i;j<a;j++) build(s[i]-'a');
        pos[i]=last;
        st[++top]=i;
    }
    cout<<ans<<endl;
    return 0;
}

知识点:

猜你喜欢

转载自blog.csdn.net/qq_46144237/article/details/107478067