hiho SAM模板题二 【长度为1-n 的字串的最多出现次数】

题目链接:https://hihocoder.com/problemset/problem/1449

通过topo计算每个节点的R集大小,然后给每个节点的maxlen打标记。

#include 
#define rep(i, a, b) for(int i = (a); i <= (b); i++)
 
#define ll long long
const int N = 1e6+100;
using namespace std;
struct SAM{
    int cnt,last,fa[N<<1],son[N<<1][30],l[N<<1],siz[N<<1];
    SAM(){
        cnt = 1;
        fa[1] = 0;
        last = 1;
        memset(son,0,sizeof(son));
    }
    void ins(int x){
        int u = last,now = last = ++cnt; //last不一定是cnt
        l[now] = l[u]+1;          //新加点now
        for(;u&&!son[u][x];u=fa[u]) son[u][x] = now; //向上寻找第一个有x的父亲
        if(!u) fa[now] = 1;       //如果找到根节点
        else {
            int v = son[u][x];
            if(l[u]+1==l[v]) fa[now] = v; //判断该父亲的x儿子是否合法
            else{
                int vv = ++cnt;    //分割节点,制造合法儿子
                l[vv] = l[u]+1;    //合法长度
                memcpy(son[vv],son[v],sizeof(son[v])); //复制信息
                fa[vv] = fa[v];
                fa[now] = fa[v] = vv;
                for(;u&&son[u][x]==v;u=fa[u]) son[u][x] = vv;
            }
        }
        siz[now] = 1;
    }
    ll solve() {
        ll ans = 0;
        rep(i, 1, cnt) ans += l[i] - (l[fa[i]]);
        return ans;
    }
}sam;
int main(){
   // freopen("a.txt","r",stdin);
    ios::sync_with_stdio(0);
    string s;
    cin>>s;
    for(auto v:s) sam.ins(v-'a');
    cout<

 

你可能感兴趣的:(SAM)