跳到正文

个人记录

虚树,KD-Tree,长链剖分,后缀数组,后缀自动机

Altwilio约 30 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 30 分钟

版本

  1. v1当前

SamuraiSamurai

aslongasyoulovemeas long as you love me

霍元甲霍元甲

真的就是讲课两天,吸收一个月呢!

1.1.虚树

2.2.KD-Tree

3.3.长链剖分

4.4.莫队

例题

1.1. P1903 [国家集训队] 数颜色 / 维护队列

带修莫队。

5.5.后缀数组

时间复杂度:倍增求法,复杂度 O(nlogn)O(nlogn)

首先把 ss 的每个后缀字典序排序。 sa[i]:sa[i]: 排名第 ii 位的是第几个后缀(起始下标)。 rk[i]:rk[i]: 第 ii 个(起始下标为 ii)的后缀的的排名。 height[i]:height[i]: sa[i]sa[i] 与 sa[i−1]sa[i-1] 的最长公共前缀。

heightheight 数组的求法: 假设所有后缀都已经排好序了,求 Lcp(i,j)Lcp(i,j) 有:(i,j,ki,j,k 均为排名,不作证明) Lcp(i,j)=Lcp(j,i)Lcp(i,j) = Lcp(j,i)

Lcp(i,i)=len(i)Lcp(i,i) = len(i) Lcp(i,j)=min(Lcp(i,k),Lcp(k,j)),i<=k<=jLcp(i,j)=min(Lcp(i,k), Lcp(k,j)),i<=k<=j height[i]=Lcp(i−1,i)height[i]=Lcp(i-1,i)

定义 h(i)=height[rk[i]]h(i)=height[rk[i]],即起始下标为 ii 的后缀与它排名前一的后缀的最长公共前缀 有:

h(i)>=h(i−1)−1h(i)>=h(i - 1) - 1

代码详细注释:

C++
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

template <class T> inline void read(T &x){
    x = 0; register char c = getchar(); register bool f = 0;
    while (!isdigit(c)) f ^= c == '-', c = getchar();
    while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
    if (f) x = -x;
}

template <class T> inline void print(T x){
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) print(x / 10);
    putchar('0' + x % 10);
}

const int N = 1e6 + 10;
int n, m;
char s[N];
int sa[N], x[N], y[N], c[N], rk[N], height[N];
//sa 排名数组,x第一关键字,y第二关键字,c每个关键字的个数,rk第i个后缀的排名

inline void get_sa(){
    for(int i = 1; i <= n; i ++) c[x[i] = s[i]] ++;//首先按照第一个字母为第一关键字排序,每个关键字的个数累加一下
    for(int i = 2; i <= m; i ++) c[i] += c[i - 1];//基数排序,统计小于等于每个关键字的个数
    for(int i = n; i; i --) sa[c[x[i]] --] = i;//从后往前求每个后缀的排名是多少 **从后往前可以使基数排序stable即元素相等不换顺序**
    for(int k = 1; k <= n; k <<= 1){
        int num = 0;
        for(int i = n - k + 1; i <= n; i ++) y[++ num] = i;//将后面没有第二关键字的后缀存下来
        for (int i = 1; i <= n; i ++ )
            if (sa[i] > k)
                y[ ++ num] = sa[i] - k;
        //再次按第一关键字排序
        for (int i = 1; i <= m; i ++ ) c[i] = 0;
        for (int i = 1; i <= n; i ++ ) c[x[i]] ++ ;//求第一关键字出现数量
        for (int i = 2; i <= m; i ++ ) c[i] += c[i - 1];//前缀和
        for (int i = n; i; i -- ) sa[c[x[y[i]]] -- ] = y[i], y[i] = 0;//按第二关键字从后往前枚举
        swap(x, y);
        //离散化
        x[sa[1]] = 1, num = 1;
        for (int i = 2; i <= n; i ++ )
            x[sa[i]] = (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k]) ? num : ++ num;
        if (num == n) break;//排完了,所有的后缀都不一样了
        m = num;
    }
}

inline void get_height(){
    for(int i = 1; i <= n; i ++) rk[sa[i]] = i;//排名是i的字符串排名是i (废话)
    for(int i = 1, k = 0; i <= n; i ++){
        if(rk[i] == 1) continue;//height[1] = 0
        if(k) k --;
        int j = sa[rk[i] - 1];
        while(i + k <= n && j + k <= n && s[i + k] == s[j + k]) k ++;
        height[rk[i]] = k; //h(i)=k
    }
}

signed main(){
    scanf("%s", s + 1); //下标从1开始
    n = strlen(s + 1), m = 122;//值域,最大ASCII是z:122
    get_sa();
    get_height();
    for(int i = 1; i <= n; i ++) printf("%d ", sa[i]);
    puts("");
    for(int i = 1; i <= n; i ++) printf("%d ", height[i]);
    return 0;
}

例题:

1.1.品酒大会(NOI2015NOI2015)

题意:nn 杯酒,每杯酒有一个标签为小写英文字母,(str(l,r)str(l, r) 为 ll 到 rr 长度为 r−l+1r -l + 1 的字符串,貌似没啥用)。pp 和 qq“rr 相似”为从 pp, qq 开始的长度为 rr 的前缀相同,每一杯酒有美味度,对于每一个 rr 从 11 到 n−1n-1 选出两杯 rr 相似的酒,求 rr 相似对数和 rr 相似中两杯美味度相乘最大值。

思路:用后缀数组得到一个后缀排序的结果,并且 heightheight 数组可以得到相邻两个后缀最长公共前缀的长度,并且有 *性质 :i,ji, j 最长前缀长度等于之间的相邻两两最长前缀最小值。对于每个固定的 rr 来说,利用所有 height[i]<rheight[i] < r 的 ii 将数列分成若干段,这样所有 rr 相似的后缀(酒)不可能出现在不同的段里(由于上面的 *性质),段内任意两杯酒一定 rr 相似,由此可以解决第一问求个数(组合数学)。对于第二问统计最大值,三种情况可以化为两种情况(考虑正负)所以只需要在每个段里维护最大次大或最小次小就可以。现在对于固定的 rr 都可以解决。现在需要解决的是所有 rr。考虑用什么顺序遍历比较好处理,从大到小,最开始段多,后来段变少,合并段较容易维护所需信息。区间合并使用并查集 O(n)O(n)。 总复杂度 O(n)+O(nlogn)O(n) + O(nlogn),并查集加后缀数组。

C++
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define int long long
using namespace std;

template <class T> inline void read(T &x){
    x = 0; register char c = getchar(); register bool f = 0;
    while (!isdigit(c)) f ^= c == '-', c = getchar();
    while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
    if (f) x = -x;
}

template <class T> inline void print(T x){
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) print(x / 10);
    putchar('0' + x % 10);
}

#define x first
#define y second
#define PII pair<int, int>

const int N = 3e5 + 10;
const int inf = 2e18;
int n, m; char s[N];
int sa[N], x[N], y[N], c[N], rk[N], height[N];
int w[N], p[N], sz[N];//并查集数组,并查集元素个数
int max1[N], max2[N], min1[N], min2[N];//最大次大最小次小
vector<int> hs[N];//记录每种值的height有哪些
PII ans[N];

//后缀数组
inline void get_sa(){
    for(int i = 1; i <= n; i ++) c[x[i] = s[i]] ++;
    for(int i = 2; i <= m; i ++) c[i] += c[i - 1];
    for(int i = n; i; i --) sa[c[x[i]] -- ] = i;
    for(int k = 1; k <= n; k <<= 1){
        int num = 0;
        for(int i = n - k + 1; i <= n; i ++) y[++ num] = i;
        for(int i = 1; i <= n; i ++)
            if(sa[i] > k)
                y[ ++ num] = sa[i] - k;
        for(int i = 1; i <= m; i ++) c[i] = 0;
        for(int i = 1; i <= n; i ++) c[x[i]] ++ ;
        for(int i = 2; i <= m; i ++) c[i] += c[i - 1];
        for(int i = n; i; i --) sa[c[x[y[i]]] -- ] = y[i], y[i] = 0;
        swap(x, y);
        x[sa[1]] = 1, num = 1;
        for (int i = 2; i <= n; i ++)
            x[sa[i]] = (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k]) ? num : ++ num;
        if(num == n) break;
        m = num;
    }
}


inline void get_height(){
    for (int i = 1; i <= n; i ++) rk[sa[i]] = i;
    for (int i = 1, k = 0; i <= n; i ++){
        if(rk[i] == 1) continue;
        if(k) k -- ;
        int j = sa[rk[i] - 1];
        while(i + k <= n && j + k <= n && s[i + k] == s[j + k]) k ++ ;
        height[rk[i]] = k;
    }
}

inline int find(int x){
    if(p[x] != x) p[x] = find(p[x]);
    return p[x];
}

inline int get(int x){
    return x * (x - 1ll) / 2; //即组合数C²x,x选2
}

inline PII calc(int r){
    static int cnt = 0, maxv = -inf;
    for(auto x : hs[r]){//将所有值等于r的height合并
        int a = find(x - 1), b = find(x); //合并x和x-1
        cnt -= get(sz[a]) + get(sz[b]); //减去原来两个区间的cnt
        p[a] = b; //合并
        sz[b] += sz[a];
        cnt += get(sz[b]);//维护大小
        if(max1[a] >= max1[b]){
            max2[b] = max(max1[b], max2[b]);
            max1[b] = max1[a];
        }else if(max1[a] > max2[b]) max2[b] = max1[a];
        if(min1[a] <= min1[b]){
            min2[b] = min(min1[b], min2[a]);
            min1[b] = min1[a];
        }else if(min1[a] < min2[b]) min2[b] = min1[a];
        maxv = max(maxv, max(max1[b] * max2[b], min1[b] * min2[b]));
    }
    if(maxv == -inf) return {cnt, 0};
    return {cnt, maxv};
}

signed main(){
    read(n), m = 122;
    scanf("%s", s + 1);
    for(int i = 1; i <= n; i ++) read(w[i]);
    get_sa();
    get_height();
    for(int i = 2; i <= n; i ++) hs[height[i]].push_back(i);//把不同的height分类
    for(int i = 1; i <= n; i ++){
        p[i] = i; sz[i] = 1;
        max1[i] = min1[i] = w[sa[i]];
        max2[i] = -inf, min2[i] = inf;
    }//初始化并查集
    for(int i = n - 1; i >= 0; i --) ans[i] = calc(i);
    for(int i = 0; i < n; i ++) printf("%lld %lld\n", ans[i].x, ans[i].y);
    return 0;
}

2.2.生成魔咒(SDOI2016SDOI2016)

前言:用后缀数组求字符串不同子串的数量。(静态问题)确定 ii 后枚举第 ii 个后缀的所有前缀。所有后缀的前缀集合就是所有子串的集合。(前置知识:P2408 不同子串个数 又水一道紫题)

ans=n(n+1)2−∑i=1nheight[rk[i]]ans = \frac {n(n+1)} 2- \sum_{i=1}^{n}height[rk[i]]

只需要在后缀数组板子上加上:

C++
inline int solve(){
    int ans = 1ll * n * (n + 1) / 2;
    for(int i = 1; i <= n; i ++) ans -= height[rk[i]];
    return ans;
}

思路:来到动态,若每次往后添加一个字符,heightheight 数组将会无法维护,将会影响前面所有的后缀,考虑将整个序列颠倒过来,边删除边维护 heightheight 数组,动态维护,为了删除用双链表维护,对于i,j,ki,j,k 若删除 jj 则 height[k]=min(height[j],height[k])height[k] = min(height[j],height[k]) 可以 O(1)O(1) 实现。总的来说,将字符串翻转,将询问序列翻转,这样就是每次删除一个后缀,

C++
#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#define int long long
using namespace std;

template <class T> inline void read(T &x){
    x = 0; register char c = getchar(); register bool f = 0;
    while (!isdigit(c)) f ^= c == '-', c = getchar();
    while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
    if (f) x = -x;
}

template <class T> inline void print(T x){
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) print(x / 10);
    putchar('0' + x % 10);
}

const int N = 1e5 + 10;
int n, m, s[N];
int sa[N], x[N], y[N], c[N], rk[N], height[N];
int u[N], d[N], ans[N];

inline int get(int x){
    static unordered_map<int, int> hash;
    if(hash.count(x) == 0) hash[x] = ++ m;
    return hash[x];
}

inline void get_sa(){
    for(int i = 1; i <= n; i ++) c[x[i] = s[i]] ++ ;
    for(int i = 2; i <= m; i ++) c[i] += c[i - 1];
    for(int i = n; i; i --) sa[c[x[i]] --] = i;
    for(int k = 1; k <= n; k <<= 1){
        int num = 0;
        for(int i = n - k + 1; i <= n; i ++) y[++ num] = i;
        for(int i = 1; i <= n; i ++)
            if(sa[i] > k)
                y[++ num] = sa[i] - k;
        for(int i = 1; i <= m ; i ++) c[i] = 0;
        for(int i = 1; i <= n; i ++) c[x[i]] ++ ;
        for(int i = 2; i <= m; i ++) c[i] += c[i - 1];
        for(int i = n; i; i --) sa[c[x[y[i]]] --] = y[i], y[i] = 0;
        swap(x, y);
        x[sa[1]] = 1, num = 1;
        for (int i = 2; i <= n; i ++)
            x[sa[i]] = (y[sa[i]] == y[sa[i - 1]] && y[sa[i] + k] == y[sa[i - 1] + k]) ? num : ++ num;
        if(num == n) break;
        m = num;
    }
}

inline void get_height(){
    for(int i = 1; i <= n; i ++) rk[sa[i]] = i;
    for(int i = 1, k = 0; i <= n; i ++){
        if(rk[i] == 1) continue;
        if(k) k -- ;
        int j = sa[rk[i] - 1];
        while(i + k <= n && j + k <= n && s[i + k] == s[j + k]) k ++;
        height[rk[i]] = k;
    }
}

signed main(){
    read(n);
    for(int i = n; i; i --) read(s[i]), s[i] = get(s[i]);
    get_sa();
    get_height();
    int res = 0;
    for(int i = 1; i <= n; i ++){
        res += n - sa[i] + 1 - height[i];
        u[i] = i - 1, d[i] = i + 1;
    }
    d[0] = 1, u[n + 1] = n;
    for(int i = 1; i <= n; i ++){
        ans[i] = res;
        int k = rk[i], j = d[k];
        res -= n - sa[k] + 1 - height[k];
        res -= n - sa[j] + 1 - height[j];
        height[j] = min(height[j], height[k]);
        res += n - sa[j] + 1 - height[j];
        d[u[k]] = d[k], u[d[k]] = u[k];
    }
    for(int i = n; i; i --) print(ans[i]), puts("");
    return 0;
}

6.6.后缀自动机

一、SAM的性质

  1. SAM是个状态机。一个起点,若干终点。原串的所有子串和从SAM起点开始的所有路径一一对应,不重不漏。所以终点就是包含后缀的点。

  2. 每个点包含若干子串,每个子串都一一对应一条从起点到该点的路径。且这些子串一定是里面最长子串的连续后缀。

  3. SAM问题中经常考虑两种边:

    (1)普通边,类似于 TrieTrie。表示在某个状态所表示的所有子串的后面添加一个字符。

    (2)Link.FatherLink.Father 表示将某个状态所表示的最短子串的首字母删除。这类边构成一棵树。

二、SAM的构造思路

  1. endpos(s)endpos(s) :子串 ss 所有出现的位置(尾字母下标)集合。SAM中的每个状态都一一对应一个 endposendpos 的等价类。 endpos的性质:

  2. (1) 令 s1,s2s1,s2 为 SS 的两个子串 ,不妨设 ∣s1∣≤∣s2∣|s1|≤|s2| 。则 s1s1 是 s2s2 的后缀当且仅当 endpos(s1)⊇endpos(s2)endpos(s1)⊇endpos(s2) ,s1s1 不是 s2s2 的后缀当且仅当 endpos(s1)endpos(s1) ∩ endpos(s2)=endpos(s2) = ∅ 。

    (2) 两个不同子串的 endposendpos,要么有包含关系,要么没有交集。

    (3) 两个子串的 endposendpos 相同,那么短串为长串的后缀。

    (4) 对于一个状态 stst ,以及任意的 longest(st)longest(st) 的后缀 ss ,如果 ss 的长度满足:∣shortest(st)∣≤∣s∣≤∣longsest(st)∣|shortest(st)|≤|s|≤|longsest(st)| ,那么 s∈substrings(st)s∈substrings(st)。

例题: 1.1. 模板后缀自动机

C++
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#define ll long long
using namespace std;

template <class T> inline void read(T &x){
    x = 0; register char c = getchar(); register bool f = 0;
    while (!isdigit(c)) f ^= c == '-', c = getchar();
    while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
    if (f) x = -x;
}

template <class T> inline void print(T x){
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) print(x / 10);
    putchar('0' + x % 10);
}

const int N = 2e6 + 10;
int tot = 1, last = 1;
//当前用到哪个点,上一个点的编号(1表示空点)
struct Node{
    int len, fa;//最长长度,绿色的边
    int ch[26];//26个儿子
}node[N];
char str[N];
ll f[N], ans;//表示每一个状态的E(s)大小
int h[N], e[N], ne[N], idx;

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

inline void extend(int c){
    int p = last;//表示上一个状态
    int np = last = ++ tot;//表示当前状态
    f[tot] = 1;
    node[np].len = node[p].len + 1;//新状态的长度等于旧状态加一
    for(; p && !node[p].ch[c]; p = node[p].fa) //如果p没有c这个儿子就一直往父亲走
        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;
        }
    }
}

inline void dfs(int u){
    for(int i = h[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);
}

signed main(){
    scanf("%s", str);
    memset(h, -1, sizeof h);
    for(int i = 0; str[i]; i ++) extend(str[i] - 'a');
    for(int i = 2; i <= tot; i ++) add(node[i].fa, i);
    dfs(1);
    print(ans), puts("");
    return 0;
}

2.2. 玄武密码

题意:对于给定母串。询问给定子串在母串中出现的最长前缀。

思路:后缀自动机,从原点出发的所有路径,对原串的所有不同字串是一一对应的,对于任意给定字符串,在后缀自动机上一直走直道走不了,我们走的任何路径都是原串的一个子串。总结,对于任意给定串,如何判断其是不是原串的子串,只需从自动机起点开始走,能走完就是子串。

C++
#include <map>
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#define ll long long
using namespace std;

template <class T> inline void read(T &x){
    x = 0; register char c = getchar(); register bool f = 0;
    while (!isdigit(c)) f ^= c == '-', c = getchar();
    while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
    if (f) x = -x;
}

template <class T> inline void print(T x){
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) print(x / 10);
    putchar('0' + x % 10);
}

const int N = 1e7 + 10;
int n, m;
int tot = 1, last = 1;
char str[N];
struct Node{
    int len, fa;
    int ch[4];
}node[N * 2];

inline int get(char c){
    if(c == 'E') return 0;
    if(c == 'S') return 1;
    if(c == 'W') return 2;
    return 3;
}

inline void extend(int c){
    int p = last, np = last = ++ tot;
    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;
        }
    }
}

signed main(){
    read(n), read(m);
    scanf("%s", str);
    for(int i = 0;  str[i]; i ++) extend(get(str[i]));
    while(m --){
        scanf("%s", str);
        int p = 1, res = 0;
        for(int i = 0; str[i]; i ++){
            int c = get(str[i]);
            if(node[p].ch[c]) p = node[p].ch[c], res ++;
            else break;
        }
        print(res), puts("");
    }
    return 0;
}
原文