题解 CF1491H【Yuezheng Ling and Dynamic Tree】
Warriors_Cat · · 题解
钦定树根为
考虑分块。将
接下来是比较神仙的一步。定义
首先看修改操作,直接考虑整块和零散点怎么处理。
对于零散点,直接暴力修改其
而对于整块,我们就需要打懒标记
因此,我们可以维护每一块被修改的次数
其次考虑询问操作,我们发现这个
对于节点
-
当
pos_u \neq pos_v 时,让pos 值大的那个节点跳到它的b 值。 -
当
pos_u = pos_v 且b_u \neq b_v 时,两个节点均跳到它们的b 值。 -
当
pos_u = pos_v 且b_u = b_v 时,直接一直让编号大的那个点跳到自己的父亲,直至两点相同即可。
分析一波复杂度。由于一条链上最多有
因此,总时间复杂度为
实现时如果卡常了的话可以适当调块长,不过我做这题好像不卡常的样子?
Code:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;
#define ll long long
#define ull unsigned long long
#define ld long double
#define fi first
#define se second
#define dingyi int mid = l + r >> 1, ls = p << 1, rs = p << 1 | 1
#define y0 y_csyakioi_0
#define y1 y_csyakioi_1
#define rep(i, x, y) for(int i = x; i <= y; ++i)
#define per(i, x, y) for(int i = y; i >= x; --i)
#define repg(i, u) for(int i = head[u]; i; i = e[i].nxt)
inline int read(){
int x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); }
while(ch >= '0' && ch <= '9'){ x = x * 10 + (ch ^ 48); ch = getchar(); }
return x * f;
}
const int N = 100010, M = 350;
int n, m, k, p, opt, x, y, z, a[N], b[N], cnt[M], f[M], L[M], R[M], pos[N];
inline void update(int x){
rep(i, L[x], R[x]) a[i] = max(1, a[i] - f[x]);
f[x] = 0; rep(i, L[x], R[x]){
if(a[i] < L[x]) b[i] = a[i];
else b[i] = b[a[i]];
}
}
inline void change(int x, int y, int z){
int l = pos[x], r = pos[y];
if(l == r){
rep(i, x, y) a[i] = max(a[i] - z, 1);
update(l); return;
}
rep(i, x, R[l]) a[i] = max(a[i] - z, 1); update(l);
rep(i, L[r], y) a[i] = max(a[i] - z, 1); update(r);
rep(i, l + 1, r - 1){
++cnt[i]; f[i] = min(N, f[i] + z);
if(cnt[i] <= k) update(i);
}
}
inline int realb(int x){ return max(1, b[x] - f[pos[x]]); }
inline int lca(int x, int y){
while(1){
if(pos[x] < pos[y]) swap(x, y);
if(pos[x] != pos[y]) x = realb(x);
else{
if(realb(x) != realb(y)) x = realb(x), y = realb(y);
else break;
}
}
while(x != y){
if(x < y) swap(x, y);
x = max(1, a[x] - f[pos[x]]);
}
return x;
}
inline void work(){
n = read(); m = read(); k = sqrt(n); pos[1] = 1; p = (n - 1) / k + 1;
rep(i, 2, n) a[i] = read(), pos[i] = (i - 1) / k + 1;
rep(i, 1, p) L[i] = (i - 1) * k + 1, R[i] = min(n, i * k);
rep(i, 1, p) update(i); while(m--){
opt = read(); x = read(); y = read();
if(opt == 1) z = read(), change(x, y, z);
else printf("%d\n", lca(x, y));
}
}
int main(){ int qwq = 1; while(qwq--) work(); return 0; }