The family tree of Bob

4.1

8 votes
Algorithms, Depth First Search, Graphs
Problem

Bob wants to know about his ancestors, therefore, he draws a graph of his family. In that graph, root is the eldest-known family member. The leaf node is a member who has no children.

You are given a Q query and N family members. They have to just print the kth ancestors with respect to that query. A member can have only one parent.

Note: Print -1 if the query is incorrect, that is, if the kth ancestor is not available. The root of the tree is 1.

Input format

  • The first line contains two space-separated integers N and Q denoting the number of nodes and the number of queries.
  • Next N1 lines contain two space-separated integers u and v denoting an edge between node u and node v
  • Next Q lines contain two space-separated integers u and k.

Output format

For each query, print a single line containing one integer.

Constraints

1N, Q5e50k5e5

Sample Input
6 5
1 2
2 3
3 4
2 5
1 6
4 1
4 3
6 1
5 1
5 3
Sample Output
3
1
1
2
-1
Time Limit: 3
Memory Limit: 1024
Source Limit:
Explanation

In this tree 1st Parent of 4th node is 3 and also  3rd parent is node 1.

For Third Query 1st parent of 6 is root node.

 

Editor Image

?