# CODECHEF: JUNE CHALLENGE | Dual Distance | PYTHON, JAVA, C++ SOLUTION

Share:

View problem on codechef

Given a tree with NN nodes, answer QQ queries of the following type:

• a,ba,b (where a≠ba≠b) which asks you to calculate ∑Ni=1min(dist(i,a),dist(i,b))∑i=1Nmin(dist(i,a),dist(i,b)) where dist(x,y)dist(x,y) is the number of edges on the shortest path between the nodes xx and yy in the tree.

Note: The input and output of this problem are large, so prefer using fast input/output methods.

### Input

• The first line contains an integer TT, the number of test cases. Then the test cases follow.
• Each test case contains N+QN+Q lines of input.
• The first line contains two integers NN and QQ.
• The next N−1N−1 lines each contains two integers uu, vv representing an edge between nodes uu and vv in the tree.
• The next QQ lines each contains two integers aa, bb, the nodes considered for the respective query.

### Output

For each query of each test case, output the answer in a new line.

### Constraints

• 1≤T≤81≤T≤8
• 2≤N≤1052≤N≤105
• 1≤Q≤1051≤Q≤105
• a≠ba≠b
• The sum of NN over all test cases is at most 5⋅1055⋅105.
• The sum of QQ over all test cases is at most 5⋅1055⋅105.
• Its guaranteed that the given input is a valid tree.

• 2≤N≤1032≤N≤103
• 1≤Q≤1031≤Q≤103
• The sum of NN over all test cases is at most 5⋅1035⋅103.
• The sum of QQ over all test cases is at most 5⋅1035⋅103.
• Time limit: 0.50.5 sec.

• original constraints
• Time limit: 22 sec.

### Sample Input

``````2
4 2
1 2
2 3
3 4
1 2
3 1
7 1
1 2
1 3
2 4
2 5
3 6
3 7
2 6
``````

### Sample Output

``````3
2
6
``````

### Explanation:

Test Case 11:

• Query 11: Answer = min(dist(1,1),dist(1,2))min(dist(1,1),dist(1,2)) + min(dist(2,1),dist(2,2))min(dist(2,1),dist(2,2)) + min(dist(3,1),dist(3,2))min(dist(3,1),dist(3,2)) + min(dist(4,1),dist(4,2))min(dist(4,1),dist(4,2)) = min(0,1)min(0,1) + min(1,0)min(1,0) + min(2,1)min(2,1) + min(3,2)min(3,2) = 0+0+1+20+0+1+2 = 33.
• Query 22: Answer = min(dist(1,1),dist(1,3))min(dist(1,1),dist(1,3)) + min(dist(2,1),dist(2,3))min(dist(2,1),dist(2,3)) + min(dist(3,1),dist(3,3))min(dist(3,1),dist(3,3)) + min(dist(4,1),dist(4,3))min(dist(4,1),dist(4,3)) = min(0,2)min(0,2) + min(1,1)min(1,1) + min(2,0)min(2,0) + min(3,1)min(3,1) = 0+1+0+10+1+0+1 = 22.

## SOLUTION

``Due to copyright issues we won't be able to update the solution here immediately. However you can download the code file from our telegram channel. So join our telegram channel for further updates. Keep tracking, the solution will be updated on this website soon.``