Connectville Conundrums
Practice
5 (3 votes)
Lowest common ancestor
Trees
Data structures
Problem
33% Success 360 Attempts 50 Points 1s Time Limit 256MB Memory 1024 KB Max Code

In the vibrant realm of Connectville, there stands a giant tree that acts as a roadmap for its many towns. This tree showcases \(N\) towns numbered \(1\) to \(N\), connected by \(N-1\) pathways. The townspeople of Connectville have a favorite pastime: a daily puzzle game.

Each morning, \(M\) riddles are put forth by the town's riddle makers. For each riddle, they'd pick three towns - \(A\), \(B\), and \(C\) - and ask everyone a fun question: How many towns (let's say \(X\)), other than towns \(A\), \(B\), and \(C\), exist such that one could travel through all four towns (A, B, C, and X) without revisiting any town along the way?

Can you unravel the riddles of Connectville's towns?

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 a pathway connecting towns \(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 in a new line the number of towns other than towns \(A\), \(B\), and \(C\), that exist such that one could travel through all four towns without revisiting any town along the way.

Constraints

\(1 \leq T \leq 10^5 \\ 3 \leq N \leq 2×10^5 \\ 1≤u,v≤N, u \neq v \\ \\ 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
1 votes
Tags:
Segment TreesEulerian pathData StructuresTreesLowest Common Ancestor
Points:50
Tags:
Sparse TableHardTreeLife-cycle assessmentLoopsSegment tree
Points:50
4 votes
Tags:
Regular expressionHardAlgorithmsStringTrees