Trivertexpath
Practice
5 (4 votes)
Depth first search
Data structures
Lowest common ancestor
Trees
Problem
50% Success 310 Attempts 50 Points 1s Time Limit 256MB Memory 1024 KB Max Code

Given a connected tree with \(N\) vertices and \(N-1\) edges, you must answer \(M\) queries of the type:

  • given three unique vertices \(A\), \(B\), and \(C\), find if there exists a simple path that contains all three vertices.

Note: A simple path is a path in a tree that does not have repeating vertices.

Input format

  • The first line contains a single integer \(T\), which denotes the number of test cases.
  • For each test case:
    • The first line contains \(N\) denoting the number of vertices in the tree.
    • The next \(N-1\) lines contain 2 space-separated integers, \(u\) and \(v\), indicating that there is an edge between vertices \(u\) & \(v\).
    • The next line contains \(M\) denoting the number of queries.
    • The next \(M\) lines contain 3 unique space-separated integers, \(A\), \(B\), and \(C\).

Output format

For each test case, answer all the \(M\)  queries. For each query print \(\text{Yes}\) if there exists a simple path that contains all three vertices \(A\), \(B\), and \(C\), otherwise print \(\text{No}\). Print answer for each query in a new line.

Constraints

\(1 \leq T \leq 10^5 \\ 3 \leq N \leq 2×10^5 \\ 1≤u,v≤N\\ \\ 1 \leq M \leq 2×10^5\\ 1≤A, B, C≤N\  \\ \text{The sum of all values of N over all test cases doesn't exceed } 2×10^5 \\ \text{The sum of all values of M over all test cases doesn't exceed } 2×10^5\)

 

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:50
3 votes
Tags:
Lowest Common AncestorTreesData Structures
Points:50
1 votes
Tags:
LoopsHeavy light decompositionHardTreeData Structures
Points:50
6 votes
Tags:
LoopsHardTree