Trivertexpath

5

4 votes
Depth First Search, Data Structures, Lowest Common Ancestor, Trees
Problem

Given a connected tree with N vertices and N1 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 N1 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 Yes if there exists a simple path that contains all three vertices A, B, and C, otherwise print No. Print answer for each query in a new line.

Constraints

1T1053N2×1051u,vN1M2×1051A,B,CN The sum of all values of N over all test cases doesn't exceed 2×105The sum of all values of M over all test cases doesn't exceed 2×105

 

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The first line denotes T = 1.

For test case 1:

We are given:

  • N = 5
  • M = 3

Now,

  •  For the first query, we have a simple path as 1253, which contains all the three vertices 3, 1, and 2. Therefore the answer is Yes.
  •  For the Second query, we have a simple path as 4253, which contains all the three vertices 2, 3, and 4. Therefore the answer is Yes.
  •  For the third query, there exists no simple path in the given tree which contains all the three vertices 1, 3, and 4. Therefore the answer is No.
Editor Image

?