SAM模板题

在这里插入图片描述

中间else部分的图解。

在这里插入图片描述

一点理解

这道题是求每个本质不同串的个数,

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;

const int N = 2e6+10;

int tot = 1, last = 1;

struct Node{
    int len, fa;
    //fa 是绿边
    int ch[26];
} node[N];

char str[N];
LL f[N], ans;
int head[N], e[N], ne[N], idx;

void extend(int c){
    //以下是1,2,3,4,5,。。。链的部分
    int p = last, np = last = ++tot;
    f[tot] = 1;
    node[np].len = node[p].len+1;
    //
    for(; p && !node[p].ch[c]; p = node[p].fa) node[p].ch[c] = np;
    //通过前面的后缀 指向当前这个点(即连接蓝边)
    if(!p) node[np].fa = 1;
    else {
        int q = node[p].ch[c];
        if(node[q].len == node[p].len + 1) node[np].fa = q;
        else {
            int nq = ++tot;
            node[nq] = node[q], node[nq].len = node[p].len + 1;
            node[q].fa = node[np].fa = nq;
            for(; p && node[p].ch[c] == q; p = node[p].fa) node[p].ch[c] = nq;
        }
    }
}

void add(int a, int b){
    e[idx] = b, ne[idx] = head[a], head[a] = idx++;
}

void dfs(int u){
    for(int i = head[u]; ~i; i = ne[i]){
        dfs(e[i]);
        f[u] += f[e[i]];
    }
    if(f[u] > 1) ans = max(ans, f[u]*node[u].len);
}

int main(){
    scanf("%s", str);
    for(int i = 0; str[i]; i ++ ) extend(str[i] - 'a');
    memset(head,-1, sizeof head);
    for(int i = 2; i <= tot; i ++ ) add(node[i].fa, i);
    dfs(1);
    printf("%lld\n", ans);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值