算法笔记 - 长链剖分
xiaosi4081 · · 算法·理论
长链剖分,故名思义就是不同于常见的重链剖分,而是以子树内深度最大值划分出轻重儿子。
对于每一个点
:::info[Code]{open}
vector<int> g[N];
int dep[N], mxdep[N], son[N];
void dfs(int u, int fa){
dep[u] = dep[fa]+1;
for(auto v:g[u]){
dfs(v, u);
if(mxdep[v] > mxdep[son[u]]) son[u] = v;
} mxdep[u] = mxdep[son[u]]+1;
}
:::
这样的链剖分也带来了一些优秀的性质:
- 长链长度和为
O(n) ,显然。 - 任意一点向上跳最多跳
O(\sqrt n) 次,因为每次向上跳链当前所在链长至少变大1 ,而总链长为O(n) ,所以跳1+2+3+4+\cdots+\sqrt n = O(n) 之后整棵树就跳完了。 -
考虑其应用。
应用
树上 K 级祖先
:::info[P5903 【模版】树上 K 级祖先]{open}
给定一棵
强制在线,
:::
考虑长链剖分。考虑性质 3 在本题中的应用,我们可以找到最大的
复杂度
:::info[Code]
#include<bits/stdc++.h>
#define ui unsigned int
using namespace std;
const int N = 5e5+5;
int n, q, f[N][20];
ui S;
inline ui get(ui x) {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
return S = x;
}
vector<int> g[N];
int dep[N], mxdep[N], son[N];
void dfs(int u, int fa){
f[u][0] = fa, dep[u] = dep[fa]+1;
for(int i = 1; i <= 19; i++) f[u][i] = f[f[u][i-1]][i-1];
for(auto v:g[u]){
dfs(v, u);
if(mxdep[v] > mxdep[son[u]]) son[u] = v;
} mxdep[u] = mxdep[son[u]]+1;
}
vector<int> l[N], ft[N];
int top[N];
void dfs2(int u, int fa){
if(u == top[u]){
int x = u;
while(x && dep[u]-dep[x] <= mxdep[u]) ft[u].push_back(x), x = f[x][0];
}
l[top[u]].push_back(u);
if(son[u]) top[son[u]] = top[u], dfs2(son[u], u);
for(auto v:g[u]) if(v != fa && v != son[u]){
top[v] = v;
dfs2(v, u);
}
}
int finds(int x, int k){
if(k == 0) return x;
int y = __lg(k);
k -= (1<<y);
x = f[x][y];
k -= dep[x]-dep[top[x]];
x = top[x];
if(k > 0){
return ft[x][k];
} else return l[x][-k];
}
int main(){
cin >> n >> q >> S;
int rt = 0;
for(int i = 1; i <= n; i++){
int fa; cin >> fa;
if(fa == 0) rt = i;
else g[fa].push_back(i);
} dfs(rt, 0);
top[rt] = rt; dfs2(rt, 0);
int lstans = 0, i = 0;
long long ans = 0;
while(q--){
++i;
int x = (get(S) ^ lstans) % n + 1;
int k = (get(S) ^ lstans) % dep[x];
lstans = finds(x, k);
ans ^= 1ll*i*lstans;
} cout << ans;
return 0;
}
:::
长剖优化 dp
长剖可以用于处理状态有一维度是深度的 dp。从重儿子继承 dp 数组并向其开头插入数,同时对于所有轻儿子对应的轻链,直接暴力合并,每个链只会被合并一次,复杂度
:::info[CF1009F Dominant Indices]{open}
给定一棵