#abc267f. F - Exactly K Steps

F - Exactly K Steps

Score : 500500 points

问题描述

给定一棵包含 NN 个顶点的树。顶点编号为 1,,N1, \dots, N,第 ii 个(1iN11 \leq i \leq N - 1)边连接顶点 AiA_iBiB_i

我们定义此树中顶点 uu 和顶点 vv 之间的 距离 为从顶点 uu 到顶点 vv 的最短路径上的边数。

你将得到 QQ 个查询。在第 ii 个查询(1iQ1 \leq i \leq Q)中,给定整数 UiU_iKiK_i,输出距离顶点 UiU_i 正好为 KiK_i 的任意一个顶点的索引。如果没有这样的顶点,则输出 -1

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

You are given a tree with NN vertices. The vertices are numbered 1,,N1, \dots, N, and the ii-th (1iN11 \leq i \leq N - 1) edge connects Vertices AiA_i and BiB_i.

We define the distance between Vertices uu and vv on this tree by the number of edges in the shortest path from Vertex uu to Vertex vv.

You are given QQ queries. In the ii-th (1iQ1 \leq i \leq Q) query, given integers UiU_i and KiK_i, print the index of any vertex whose distance from Vertex UiU_i is exactly KiK_i. If there is no such vertex, print -1.

Constraints

  • 2N2×1052 \leq N \leq 2 \times 10^5
  • 1Ai<BiN(1iN1)1 \leq A_i \lt B_i \leq N \, (1 \leq i \leq N - 1)
  • The given graph is a tree.
  • 1Q2×1051 \leq Q \leq 2 \times 10^5
  • 1Ui,KiN(1iQ)1 \leq U_i, K_i \leq N \, (1 \leq i \leq Q)
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN

A1A_1 B1B_1

\vdots

AN1A_{N-1} BN1B_{N-1}

QQ

U1U_1 K1K_1

\vdots

UQU_Q KQK_Q

Output

Print QQ lines. The ii-th (1iQ1 \leq i \leq Q) line should contain the index of any vertex whose distance from Vertex UiU_i is exactly KiK_i if such a vertex exists; if not, it should contain -1. If there are multiple such vertices, you may print any of them.

Sample Input 1

5
1 2
2 3
3 4
3 5
3
2 2
5 3
3 3

Sample Output 1

4
1
-1
  • Two vertices, Vertices 44 and 55, have a distance exactly 22 from Vertex 22.
  • Only Vertex 11 has a distance exactly 33 from Vertex 55.
  • No vertex has a distance exactly 33 from Vertex 33.

Sample Input 2

10
1 2
2 3
3 5
2 8
3 4
4 6
4 9
5 7
9 10
5
1 1
2 2
3 3
4 4
5 5

Sample Output 2

2
4
10
-1
-1

update @ 2024/3/10 11:17:06