Count New String(广义SAM)

Count New String(广义SAM)

顽强补题,刚刚学广义后缀自动机 S A M SAM ,貌似就是 S A M SAM 的多文本串形式。

不过用 S A M SAM 加修改 l a s t last 结点也可以实现广义 S A M SAM ,大概就是碰到新的串就将 l a s t last 置为 1 1 好了开始讲题(口胡)。

貌似这个题意很迷惑,大概就是给定 [ x 1 , y 1 ] , [ x 2 , y 2 ] [x_1,y_1],[x_2,y_2] 两个区间 1 x 1 x 2 y 2 x 1 n 1\leq x_1\leq x_2\leq y_2\leq x_1\leq n ,进行两次 f f 转换操作,求所有本质不同的子串个数。

考虑外层 [ x 1 , y 1 ] [x_1,y_1] [ x 2 , y 2 ] [x_2,y_2] 大,所以内层 f f 变换相当于没有,因为还要被再变换一次。

考虑到所有子串都可以转换为后缀的前缀形式。

所以答案变为: i = 1 n f ( S , i , n ) \sum_{i=1}^n f(S,i,n) 的本质不同的子串。

首先我们肯定不能暴力建图跑 S A M SAM ,这样空间必然炸。

考虑字符集大小 Σ = 10 |\Sigma|=10

所以后缀的形式最坏是:

a a b b b b b b a b b b b b b c c c c c c a\\abbbbbb\\abbbbbbcccccc\dots

即最多 10 N 10N

因此考虑进行从后往前遍历当前字符 i i 向右查找第一个 s [ i ] \geq s[i] 的位置 k k

这里的向右查找操作可以用单调栈实现。

然后 s [ i k 1 ] s[i\dots k-1] 的子串就会产生新的贡献,因为 [ i , k 1 ] [i,k-1] 的字符都会 s [ i ] s[i] 被更新。

然后每次插入 s [ i k 1 ] s[i\dots k-1] 的子串跑 S A M SAM 即可。

貌似 h a s h hash 和序列自动机也能搞,但是我太菜了。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e6+5,M=2e4+5,inf=0x3f3f3f3f,mod=1e9+7;
#define mst(a) memset(a,0,sizeof a)
#define lx x<<1
#define rx x<<1|1
#define reg register
#define PII pair<int,int>
#define fi first
#define se second
#define pb push_back
char s[N];
int pos[N],n;
struct SAM{
    int last,cnt;int ch[N<<1][26],fa[N<<1],len[N<<1],sz[N];
    void insert(int c){
        int p=last,np=++cnt;last=np;len[np]=len[p]+1;
        for(;p&&!ch[p][c];p=fa[p]) ch[p][c]=np;
        if(!p) fa[np]=1;
        else {
            int q=ch[p][c];
            if(len[q]==len[p]+1) fa[np]=q;
            else  {
                int nq=++cnt;len[nq]=len[p]+1;
                memcpy(ch[nq],ch[q],sizeof ch[q]);
                fa[nq]=fa[q],fa[q]=fa[np]=nq;
                for(;ch[p][c]==q;p=fa[p]) ch[p][c]=nq;
            }
        }
        sz[np]=1;
    }
    void build(){
        scanf("%s",s+1); n=strlen(s+1);
        last=cnt=1;
    }
    void solve(){
        pos[n+1]=1;
        stack<int> st;
    for(int i=n;i>=1;i--){
        while(!st.empty()&&s[st.top()]<s[i]) st.pop();
        int k = st.empty() ? n + 1 : st.top();
            last=pos[k];
        for(int j=i;j<k;j++) insert(s[i]-'a');
        pos[i]=last;
        st.push(i);
    }
    ll ans = 0;
    for(int i=2;i<=cnt;i++) ans+=len[i]-len[fa[i]];
    printf("%lld\n",ans);
    }
}sam;
int main(){
    sam.build();
    sam.solve();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45750972/article/details/107496400
今日推荐