Two Friends
Practice
5 (4 votes)
Graphs
Shortest path algorithms
Algorithms
Problem
24% Success 220 Attempts 30 Points 5s Time Limit 256MB Memory 1024 KB Max Code

Bod and Alice are going back to their home from their school through their routes. They want to meet in between but because Alice is running late so Bob will have to go out of his way to meet her. Help Bob find the minimum extra distance that he will have to cover to meet her.

You are given a tree that will represent the locality. 

The number of nodes in the tree is \(N\).

You will be given \(N\) and in the following next \(N-1\) lines, you will be given two integers that represent the nodes that have an edge between them.

There are \(M\) queries. In each query help Bob find the minimum extra distance that he will have to cover to meet Alice.

You are given an integer \(M\) and in the following \(M\) lines you will be given \(4\) integers \(u1,v1,u2,v2\)

 \(u1\) and \(v1\) represent Bob's school and home whereas \(u2\) and \(v2\) represent Alice's school and home.

Input Format:

The first line of input data contains single integer \(T\) — the number of test cases in the test.

The first line contains a single integer \(N\)  

The following \(N-1\) lines two integers are given specifying the two nodes that have a edge between them.   

The next line contains a single integer \(M\), the number of queries.  

The following \(M\) lines contain \(4\) integers \(u1,v1,u2,v2\)  specifying their respective college and their home nodes.   

Output Format:

For each query print the minimum extra distance that he needs to cover to meet her in new line.

Constraints:

\(1 \leq T \leq 100 \\ 1 \leq N \leq 10^5 \\ 1 \leq M \leq 10^5 \\ 1 \leq u1,u2,v1,v2 \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:30
5 votes
Tags:
AlgorithmsApprovedBreadth First SearchGraphsMediumOpen
Points:30
3 votes
Tags:
GraphsMediumShortest Path Algorithm
Points:30
26 votes
Tags:
Ad-HocAlgorithmsBrute-force searchDijkstra's algorithmGraphsMediumShortest Path Algorithm簡単-普通