The family tree of Bob
Practice
4.1 (8 votes)
Algorithms
Depth first search
Graphs
Problem
35% Success 2579 Attempts 30 Points 3s Time Limit 1024MB Memory 1024 KB Max Code

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 \(k^{th}\) 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 \(k^{th}\) 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 \(N- 1\) 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

\(1 ≤ N,\ Q ≤ 5e5\\ 0 ≤ k ≤ 5e5\)

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
10 votes
Tags:
Data StructuresDepth First SearchEasyGraphsapproved
Points:30
9 votes
Tags:
Depth First SearchEasyGraphsImplementationRecursion
Points:30
174 votes
Tags:
ApprovedDepth First SearchEasyGraphsOpen