P2408 不同子串个数 后缀自动机做法

传送门
题意
给一个字符串,求它有多少个不同的子串。
思路
后缀数组当然是能做的,每个sa[i] - height[i]的和就是答案了。
后缀自动机也可以做,后缀自动机上从起点到任意状态就是一个子串,每条路径表示的子串都不同,所以只要求出后缀自动机上从起点到其它点的路径条数就是不同子串的个数。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7, M = 26;
typedef long long ll;
char s[maxn];
int head[maxn], to[maxn], nex[maxn], tot;
void Add(int x, int y) {
    to[tot] = y;
    nex[tot] = head[x];
    head[x] = tot++;
}
/*SAM*/
struct node {
    int ch[M];//字符集大小
    int len, fa;//len表示该等价类的最长的字符串长度
    node() {memset(ch, 0, sizeof(ch)); len = fa = 0;}
}dian[maxn];
int now = 1, last = 1;//总共有now个状态,一开始有空串这个状态,last是没加新字符的上一个状态
void add(int c) {
    int p = last, np = last = ++now;
    dian[np].len = dian[p].len + 1;
    for (; p && !dian[p].ch[c]; p = dian[p].fa) dian[p].ch[c] = np;
    if(!p) dian[np].fa = 1;
    else {
        int q = dian[p].ch[c];
        if(dian[q].len == dian[p].len + 1) dian[np].fa = q;
        else {
            int nq = ++now;
            dian[nq] = dian[q]; dian[nq].len = dian[p].len + 1;
            dian[q].fa = dian[np].fa = nq;
            for (; p && dian[p].ch[c] == q; p = dian[p].fa) dian[p].ch[c] = nq;
        }
    }
}
/*SAM*/
ll dp[maxn];
ll dfs(int u) {
    if(dp[u]) return dp[u];//后缀自动机上会经过一个状态会有多个父亲,计算过就不要重复计算了,这个和parent树不同
    for (int i = 0; i < 26; i++) {
        if(dian[u].ch[i]) dp[u] += dfs(dian[u].ch[i]) + 1;//1就相当于边,用边数来理解更清楚
    }
    return dp[u];
}
int main() {
    memset(head, -1, sizeof(head));
    scanf("%*d%s", s);
    int len = strlen(s);
    for (int i = 0; i < len; i++) add(s[i] - 'a');
    printf("%lld\n", dfs(1));
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值