P3804 【模板】后缀自动机

\(\color{#0066ff}{ 题目描述 }\)

给定一个只包含小写字母的字符串\(S\),

请你求出 \(S\) 的所有出现次数不为 \(1\) 的子串的出现次数乘上该子串长度的最大值。

\(\color{#0066ff}{输入格式}\)

一行一个仅包含小写字母的字符串\(S\)

\(\color{#0066ff}{输出格式}\)

一个整数,为 所求答案

\(\color{#0066ff}{输入样例}\)

abab

\(\color{#0066ff}{输出样例}\)

4

\(\color{#0066ff}{数据范围与提示}\)

对于\(10\%\)的数据,\(∣S∣\leq 1000\)

对于\(100\%\)的数据,\(|S|\leq 10^6\)

\(\color{#0066ff}{ 题解 }\)

后缀自动机是一个可以维护所有字串的最简自动机

时间空间复杂度均为\(O(n)\)

是一个非常优秀的东西

本题要求出所有出现次数不为1的字串

那么考虑parent树

如果一个点所在子树有大于1个叶子节点,就说明当前字串出现次数超过1(每个叶子都是前缀)

但是我们parent树只记录了父亲

没有关系

不难发现,叶子节点维护的是一个前缀,也就是后缀链上最长的

所以我们可以通过鸡排来自下而上统计叶子个数

这题, 数组大小开成偶数会TLE我也不知道为啥

#include<bits/stdc++.h>
using namespace std;
#define LL long long
LL in() {
    char ch; int x = 0, f = 1;
    while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
    for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
    return x * f;
}
const int maxn = 2e6 + 5;
struct SAM {
protected:
    struct node {
        node *ch[26], *fa;
        int len, siz;
        node(int len = 0, int siz = 0): fa(NULL), len(len), siz(siz) {
            memset(ch, 0, sizeof ch);
        }
    };
    node *root, *tail, *lst;
    node pool[maxn], *id[maxn];
    int c[maxn];
    void extend(int c) {
        node *o = new(tail++) node(lst->len + 1, 1), *v = lst;
        for(; v && !v->ch[c]; v = v->fa) v->ch[c] = o;
        if(!v) o->fa = root;
        else if(v->len + 1 == v->ch[c]->len) o->fa = v->ch[c];
        else {
            node *n = new(tail++) node(v->len + 1), *d = v->ch[c];
            std::copy(d->ch, d->ch + 26, n->ch);
            n->fa = d->fa, d->fa = o->fa = n;
            for(; v && v->ch[c] == d; v = v->fa) v->ch[c] = n;
        }
        lst = o;
    }
    void clr() {
        tail = pool;
        root = lst = new(tail++) node();
    }
public:
    SAM() { clr(); }
    void ins(char *s) { for(char *p = s; *p; p++) extend(*p - 'a'); }
    LL getans() {
        LL ans = 0; 
        int len = tail - pool, maxlen = 0;
        for(node *o = pool; o != tail; o++) c[o->len]++, maxlen = std::max(maxlen, o->len);
        for(int i = 1; i <= maxlen; i++) c[i] += c[i - 1];
        for(node *o = pool; o != tail; o++) id[--c[o->len]] = o;
        for(int i = len - 1; i; i--) {
            node *o = id[i];
            o->fa->siz += o->siz;
            if(o->siz > 1) ans = std::max(ans, 1LL * o->siz * o->len);
        }
        return ans;
    }
}sam;
int main() {
    static char s[maxn];
    scanf("%s", s);
    sam.ins(s);
    printf("%lld", sam.getans());
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/olinr/p/10251693.html