Leafonomics

2.5

2 votes
Trees, Dynamic Programming, Segment Trees, Algorithms, Euler Tour and Path, Advanced Data Structures
Problem

Given a tree with N nodes connected by N1 edges, rooted at node 1, each edge in the tree is assigned a value, which can be either positive, negative, or zero. Your task is to calculate, for each node, the smallest total sum of edge values that can be obtained on a simple path from that particular node to any leaf node in the tree.

Notes :

  • A simple path is a path in a tree that does not have repeating vertices. 
  • A node that does not have any child node is called a leaf node.

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, and this edge has value w.

Output format

For each test case, print N integers in a new line, where the ith integer depicts the smallest total sum of edge values that can be obtained on a simple path from the ith node to any leaf node in the tree.

Constraints

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

 

Sample Input
1
6
1 2 4
1 4 5
2 3 2 
4 5 -2 
4 6 3
Sample Output
3 2 0 -2 0 0
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

The first line denotes T = 1.

For test case 1:

We are given:

  • N = 6, and the tree is as follows:

                

  • Leaf nodes are - 3, 5, and 6.

Now, the simple paths, having the smallest total sum of edge values that can be obtained from each node to a leaf node, are:

  • 145
  • 23
  • 3
  • 45
  • 5
  • 6

Therefore, the answer is : 3 2 0 -2 0 0.

Editor Image

?