跳到正文

题解

题解:AT_abc417_g [ABC417G] Binary Cat

#SUSPENDED#约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年8月20日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

前情提要

如果你想 AC 这道题,你可能需要了解以下知识:

在这里,我所用的方法为第一种。

思路

首先,我们先搞定一件事情。当我们从当前节点到某一个节点,我们需要查询的 xx 在这一个节点为多少。

例如:

在这幅图中,现在所在的节点要查询的 xx 为多少,我们是不知道的。但是我们可以这样处理:

  • 从自己节点到左子节点的边权为 00。
  • 从自己节点到右子节点的边权为 lenleftlen_{left},即左子串长度。

这样我们就解决了第一个问题(现在所在的节点要查询的 xx 为多少)。

接下来,我们定义(仅本题定义):

  • 好子节点表示其子节点中串长度最长的节点。如果有多个串长度最长的子结点,若有多个,取其一。
  • 从这个结点到好子节点的边为好边。
  • 好链表示由若干条首尾衔接的好边构成的链。

我们可以使用好链进行倍增,来回在好链上跳跃。

时间复杂度

一共 QQ 次询问,每次倍增需要 log⁡n\log n 次,最多跳跃 log⁡n\log n 次,则总时间复杂度为 O(Qlog⁡2n)O(Q\log^2 n)。

代码

最后代码如下:

C++
#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;
}