atcoder#ABC267F. [ABC267F] Exactly K Steps

[ABC267F] Exactly K Steps

Score : 500500 points

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.

5
1 2
2 3
3 4
3 5
3
2 2
5 3
3 3
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.
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
2
4
10
-1
-1