弹飞绵羊平衡树解法

· · 题解

思路

LCT 太难了,我不会。分块固然可以,可是时间复杂度不优秀。这道题只用 splay 也可以做。

首先可以发现一个 O(n^2) 的思路。对每个点对它弹到的位置连边,大于 n 就都连 n+1,形成一棵树,根节点是 n+1 号点。答案就是点在树中的深度。

要通过这道题还需要进行优化,先给大家科普一个算深度的方法。

先算出一棵树的括号序,也就是进行一遍深搜,进入时为左括号,退出时为右括号。这样就能形成一个长度为 2n 的括号序列。再把左括号设为 1,右括号设为 -1,每个点的深度就是这个点对应的左括号之前的前缀和减一。

比如说下面这棵树。

5 号点对应的左括号的前缀和减一是 2。

这么做为什么是对的?

简单证明一下吧,可以发现假如一个子树走完了那么这一段左括号之和为零,所以一个点之前的左右括号中,只有根到它路径上的左括号没有被抵消。

回到本题,多出来一个修改操作。对于一个点 x,弹力系数修改成 y,也就是把 x 和父亲的边断开,把其子树连到 x + y 上,想想如何在括号序上操作?

用 `Splay` 树维护括号的顺序。 我们可以在 `Splay` 树上先把 $[l,r]$ 这段区间断开,这涉及到 `Splay` 树的断树操作。 移动到 $p$ 后面可以把 $p$,和 $p$ 后面的位置 $q$ 旋到根,然后把 $[l,r]$ 插入到 $q$ 的左儿子。 查询操作可以把 $x$ 旋到根,然后查它左子树之和就行了。 具体的看代码吧。 ```cpp #include<bits/stdc++.h> using namespace std; const int maxn = 4e6 + 10; int n; int a[maxn]; int w[maxn], ch[maxn][2], sze[maxn], fa[maxn]; int sum[maxn]; int L[maxn], R[maxn]; vector<int> edge[maxn]; int s[maxn * 2], tot; int cnt, rt; void dfs(int u) { s[++tot] = u * 1; for(auto v:edge[u]) dfs(v); s[++tot] = u * -1; } int get(int x) { return x == ch[fa[x]][1]; } void update(int u) { sze[u] = sze[ch[u][0]] +sze[ch[u][1]] + 1; sum[u] = sum[ch[u][0]] + sum[ch[u][1]] + w[u]; } void rotate(int x) { int y = fa[x], z = fa[y], d = get(x); ch[y][d] = ch[x][d ^ 1]; if (ch[x][d ^ 1]) fa[ch[x][d ^ 1]] = y; ch[x][d ^ 1] = y; if (z) ch[z][get(y)] = x; fa[y] = x; fa[x] = z; update(y), update(x); } void splay(int x, int y = 0) { if (y == 0) rt = x; while (fa[x] != y) { int f = fa[x], g = fa[f]; if (g != y) { if (get(f) == get(x)) rotate(f); else rotate(x); } rotate(x); } } void build() { cnt++; sze[cnt] = 1; ch[cnt][1] = cnt + 1; for(int i = 1; i <= tot; i++) { cnt++; sze[cnt] = 1; ch[cnt][1] = cnt + 1; fa[cnt] = cnt - 1; if(s[i] > 0) L[s[i]] = cnt, w[cnt] = 1; else R[abs(s[i])] = cnt, w[cnt] = -1; } cnt++; sze[cnt] = 1; fa[cnt] = cnt - 1; for(int i = cnt; i >= 1; i--) { update(i); } splay(cnt); } int getk(int k) { int cur = rt; while(1) { if(ch[cur][0] && k <= sze[ch[cur][0]]) cur = ch[cur][0]; else { k -= (1 + sze[ch[cur][0]]); if(k <= 0) { splay(cur); return cur; } cur = ch[cur][1]; } } } int Rank(int x) { splay(x); return sze[ch[x][0]] + 1; } void Change(int x, int t){ int p = getk(Rank(L[x]) - 1); int q = getk(Rank(R[x]) + 1); // cout << p << " " << q <<"\n"; splay(p), splay(q, p); int tmp = ch[q][0]; ch[q][0] = 0; update(q), update(p); p = L[t], q = getk(Rank(L[t]) + 1); splay(p), splay(q, p); fa[tmp] = q; ch[q][0] = tmp; update(q), update(p); } int query(int x) { int y = L[x]; splay(y); return sum[ch[y][0]]; } int main() { cin.tie(0), cout.tie(0); ios::sync_with_stdio(0); cin >> n; for(int i = 1; i <= n; i++) { cin >> a[i]; edge[min(n + 1, i + a[i])].push_back(i); } dfs(n + 1); build(); int T; cin >> T; while(T--) { int op, x, y; cin >> op >> x; x++; if(op == 1) { cout << query(x) <<"\n"; } else { cin >> y; Change(x, min(n + 1, x + y)); } } return 0; } ```