Min-Mystic

5

8 votes
Depth First Search, Trees, Mathematics, Graphs, Dynamic Programming, Algorithms
Problem

A magical tree with N vertices and N1 edges is provided to you. Each of the N1 edges have some positive weight. Assuming there are X edges in the simple path between vertices A and B, then the separation between the vertices A and B can be determined using the following formula:

  • (Total weights of all the edges along the simple path between vertices A and B) × (X%3)

Now, the mystical value for each vertex is defined as the sum of the separation between this vertex & every other vertex. Your task is to determine the minimum mystical value that a vertex has in the given magical tree.

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 following N1 lines contain 3 space-separated integers, uv, and w indicating that there is an edge between vertices u & v of weight  w.

Output format

For each test case, print the minimum mystical value that a vertex has in the given magical tree in a new line.

Constraints

1T1053N1061u,vN1w106The sum of all values of N over all test cases doesn't exceed 106

 

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

The first line denotes T = 1.

For test case 1:

We are given:

  • N = 6

Now,

  • For vertex 1:
    • The separation between vertices 1 & 2 is 1 × (1%3) = 1.
    • The separation between vertices 1 & 3 is (1+2) × (2%3) = 6.
    • The separation between vertices 1 & 4 is (1+2+3) × (3%3) = 0.
    • The separation between vertices 1 & 6 is (1+5) × (2%3) = 12.
    • The separation between vertices 1 & 5 is (1+2+4) × (3%3) = 0.
  • Therefore the mystical value for vertex 1 is (1+6+0+12+0) = 19.
  • Similarly, the mystical value for vertex 2 is 30.
  • Similarly, the mystical value for vertex 3 is 29.
  • Similarly, the mystical value for vertex 4 is 27.
  • Similarly, the mystical value for vertex 5 is 30.
  • Similarly, the mystical value for vertex 6 is 31.

Since the minimum mystical value that a vertex has in the given magical tree is 19, the answer to this test case is 19.

Editor Image

?