[ABC267F] Exactly K Steps题解
[ABC267F] Exactly K Steps
题意
有一颗
定义两点
思路
考虑无解,显然如果从
于是可以离线处理,记录从点
代码
#include <iostream>
#include <vector>
using namespace std;
const int MaxN = 2e5 + 10;
struct S {
int x, y;
bool operator<(const S &j) const {
return y < j.y;
}
};
int u[MaxN], k[MaxN], ans[MaxN], n, q;
vector<int> g[MaxN], c;
vector<S> l[MaxN];
S dfs(int x, int fa) {
S res = {x, 0};
for (int i : g[x]) {
if (i == fa) {
continue;
}
res = max(res, dfs(i, x));
}
return {res.x, res.y + 1};
}
void DFS(int x, int fa) {
c.push_back(x);
for (int i : g[x]) {
if (i == fa) {
continue;
}
DFS(i, x);
}
int len = c.size();
for (S i : l[x]) {
(len > i.x) && (ans[i.y] = c[len - i.x - 1]);
}
c.pop_back();
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n;
for (int i = 1, u, v; i < n; i++) {
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
cin >> q;
for (int i = 1; i <= q; i++) {
cin >> u[i] >> k[i];
l[u[i]].push_back({k[i], i}), ans[i] = -1;
}
int lres = dfs(1, -1).x, rres = dfs(lres, -1).x;
DFS(lres, -1), DFS(rres, -1);
for (int i = 1; i <= q; i++) {
cout << ans[i] << '\n';
}
return 0;
}