后缀自动机之统计不同子串个数

166 篇文章 0 订阅

题目背景

因为NOI被虐傻了,蒟蒻的YJQ准备来学习一下字符串,于是它碰到了这样一道题:

题目描述

给你一个长为N的字符串,求不同的子串的个数

我们定义两个子串不同,当且仅当有这两个子串长度不一样 或者长度一样且有任意一位不一样。

子串的定义:原字符串中连续的一段字符组成的字符串

输入格式

第一行一个整数N

接下来一行N个字符表示给出的字符串

输出格式

一行一个整数,表示不一样的子串个数

输入输出样例

输入 #1复制

5
aabaa

输出 #1复制

11

输入 #2复制

3
aba

输出 #2复制

5

说明/提示

请使用64位整数来进行输出

(具体来说,C++和C选手请使用long long 类型,pascal选手请使用Int64)

由于输入文件过大,请使用 高效的读入方法(具体的,c++和c选手请不要使用cin,pascal选手不需要管)

对于30%的数据,N\le 1000N≤1000

对于100%的数据,N\le 10^5N≤105

 

 

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1000010;
struct SAM{
    int ch[26];
    int len, fa;
}sam[MAXN << 1];
int las = 1, cnt = 1;
long long f[MAXN << 1];
inline void add(int c){
    int p = las; int np = las = ++cnt;
    sam[np].len = sam[p].len + 1;
    for(; p && !sam[p].ch[c]; p = sam[p].fa) sam[p].ch[c] = np;
    if(!p) sam[np].fa = 1;
    else{
        int q = sam[p].ch[c];
        if(sam[q].len == sam[p].len + 1) sam[np].fa = q;
        else{
            int nq = ++cnt; sam[nq] = sam[q];
            sam[nq].len = sam[p].len + 1;
            sam[q].fa = sam[np].fa = nq;
            for(; p && sam[p].ch[c] == q; p = sam[p].fa) sam[p].ch[c] = nq;
        }
    }
}
char a[MAXN];
void dfs(int u){
    f[u] = 1;
    for(int i = 0; i < 26; ++i)
        if(sam[u].ch[i]){
            if(!f[sam[u].ch[i]])
                dfs(sam[u].ch[i]);
            f[u] += f[sam[u].ch[i]];
        }
}
int len;
int main(){
    scanf("%d", &len);
    scanf("%s", a + 1);
    for(int i = 1; i <= len; ++i)
       add(a[i] - 'a');
    dfs(1);
    printf("%lld\n", f[1] - 1);
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值