Cryptic Line
Practice
2.4 (8 votes)
Algorithms
Trees
Data structures
Depth first search
Lowest common ancestor
Graphs
Problem
41% Success 2022 Attempts 10 Points 1s Time Limit 256MB Memory 1024 KB Max Code

You are given a historical family tree of the noble kingdom, represented as a tree structure. The tree contains information about generations of ancestors and descendants. Your goal is to answer a series of queries in a way that helps people establish their ancestral connections.For each query, you will receive two names, let's call them Person \(X\) and Person \(Y\). Person \(1\) is the root of the family tree. Your task is to determine whether Person \(X\) is an ancestor of Person \(Y \) or not. If Person \(X\) is indeed an ancestor of Person \(Y\), you should respond with \(YES\)  otherwise, you should reply with \(NO\).Think of yourself as the custodian of this invaluable historical record, helping the kingdom's residents trace their noble lineage. Can you provide accurate responses to these queries and unveil the ancestral ties that bind the kingdom's inhabitants together?

Input Format:

  • The first line contains an integer \(N\), representing the number of nodes in the family tree.
  • The second line contains an integer \(Q\), representing the number of queries.
  • The following \(N-1\) lines each contain two space-separated integers \(U\) and \(V\) indicating an ancestral connection between nodes \(U\) and \(V\) in the family tree.
  • The next \(Q\) lines contain two space-separated integers \(X\)  and \(Y\), representing the individuals for each query.

Output Format:

For each query, output either \(YES\) if Person \(X\) is an ancestor of Person \(Y\), or \(NO \) if Person \(X\) is not an ancestor of Person \(Y\).

Constraints:

\(1 \leq N, Q \leq 2*10^5 \\ 1 \leq U,V \leq N \\ 1 \leq X,Y \leq N \)

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:10
22 votes
Tags:
AlgorithmsDepth First SearchGraphs