PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000053. Đúng k bước (Exactly K Steps)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đúng k bước (Exactly K Steps)

Exactly K Steps

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

Given an undirected tree with nn vertices, every edge counts as one step. For each query u,ku,k, find any vertex whose distance from uu is exactly kk edges.

If multiple such vertices exist, any one is accepted. If none exists, print -1.

Input

  • The first line contains nn.
  • Each of the next n−1n-1 lines contains an edge a,ba,b.
  • The next line contains the number of queries qq.
  • Each of the last qq lines contains u,ku,k.

Output

Print one valid vertex per query or -1 if impossible. More than one output may be correct.

Subtasks

General constraints: 2≤n,q≤2⋅1052\le n,q\le2\cdot10^5; 1≤a<b≤n1\le a<b\le n; 1≤u,k≤n1\le u,k\le n.

  • Subtask 1 (20 points): 1≤n≤401\le n\le 40; 1≤q≤501\le q\le 50.

  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.

  • Subtask 3 (50 points): 1≤n≤2000001\le n\le 200000; 1≤q≤2000001\le q\le 200000.

Examples

Input

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

Output

4
1
-1

Explanation

From vertex 22, both vertices 44 and 55 are two edges away; the sample chooses 44. From vertex 55, the route 5−3−2−15-3-2-1 is three edges long, so the answer can be 11. No vertex is three edges away from 33, hence -1.