题解:AT_abc417_g [ABC417G] Binary Cat
前情提要
如果你想 AC 这道题,你可能需要了解以下知识:
- 树链剖分
- 可持久化平衡树
在这里,我所用的方法为第一种。
思路
首先,我们先搞定一件事情。当我们从当前节点到某一个节点,我们需要查询的
例如:
在这幅图中,现在所在的节点要查询的
- 从自己节点到左子节点的边权为
0 。 - 从自己节点到右子节点的边权为
len_{left} ,即左子串长度。
这样我们就解决了第一个问题(现在所在的节点要查询的
接下来,我们定义(仅本题定义):
- 好子节点表示其子节点中串长度最长的节点。如果有多个串长度最长的子结点,若有多个,取其一。
- 从这个结点到好子节点的边为好边。
- 好链表示由若干条首尾衔接的好边构成的链。
我们可以使用好链进行倍增,来回在好链上跳跃。
时间复杂度
一共
代码
最后代码如下:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 5e5+10;
const int inf = 1e18;
int Q;
int f[N][35], fs[N][35];
int l[N], r[N], x[N];
int len[N];
signed main() {
cin >> Q; len[0] = 1, len[1] = 1;
for (int i = 2;i<= Q+1;i++) {
cin >> l[i] >> r[i] >> x[i];
len[i] = min(len[l[i]]+len[r[i]], inf);
if (len[l[i]] >= len[r[i]]) f[i][0] = l[i];
else f[i][0] = r[i], fs[i][0] = len[l[i]];
for (int j = 1;j<= 25;j++) {
f[i][j] = f[f[i][j-1]][j-1];
fs[i][j] = min(fs[f[i][j-1]][j-1]+fs[i][j-1], inf);
}
int pos = i;
while (pos > 1) {
for (int j = 24;j>= 0;j--) {
if (f[pos][j] > 1 && x[i] > fs[pos][j] && x[i] <= fs[pos][j]+len[f[pos][j]]) {
x[i] -= fs[pos][j];
pos = f[pos][j];
}
}
if (x[i] > len[l[pos]]) x[i] -= len[l[pos]], pos = r[pos];
else pos = l[pos];
}
cout << pos << endl;
}
return 0;
}