HihoCoder1445 suffix automaton two melody 5 Repeat (suffix string of several types of automatic machine)

Meaning of the questions:

The number of different sub-strings of the query string

Ideas:

Each node represents a suffix automaton to the end of the current character number suffix number is \ (the maxlen - the minlen \) , where \ (= the minlen the maxlen [Father] \) .

Code:

#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<bitset>
#include<string>
#include<cstdio>
#include<vector>
#include<cstring>
#include <iostream>
#include<algorithm>
using namespace std;
const int maxn = 1000000 + 10;
typedef long long ll;
const ll mod = 998244353;
typedef unsigned long long ull;

struct SAM{
    struct Node{
        int next[27];
        int fa, maxlen;
        void init(){
            memset(next, 0, sizeof(next));
            fa = maxlen = 0;
        }
    }node[maxn << 1];
    int sz, last;

    void init(){
        sz = last = 1;
        node[sz].init();
    }
    void insert(int k){
        int p = last, np = last = ++sz;
        node[np].init();
        node[np].maxlen = node[p].maxlen + 1;
        for(; p && !node[p].next[k]; p = node[p].fa)
            node[p].next[k] = np;
        if(p == 0) {
            node[np].fa = 1;
        }
        else{
            int t = node[p].next[k];
            if(node[t].maxlen == node[p].maxlen + 1){
                node[np].fa = t;
            }
            else{
                int nt = ++sz;
                node[nt] = node[t];
                node[nt].maxlen = node[p].maxlen + 1;
                node[np].fa = node[t].fa = nt;
                for(; p && node[p].next[k] == t; p = node[p].fa)
                    node[p].next[k] = nt;
            }
        }
    }

    void solve(){
        ll ans = 0;
        for(int i = 1; i <= sz; i++){
            ans += node[i].maxlen - node[node[i].fa].maxlen;
        }
        printf("%lld\n", ans);
    }
}sam;
char s[maxn];
int main(){
    sam.init();
    scanf("%s", s);
    int len = strlen(s);
    for(int i = 0; i < len; i++) sam.insert(s[i] - 'a');
    sam.solve();
    return 0;
}

Guess you like

Origin www.cnblogs.com/KirinSB/p/11654893.html