#t461. 水井选址
水井选址
Well Site Selection
Problem Background
Special for beginners, ^_^
Problem Description
Consider a binary tree (shown below; the number inside each circle is the population living at that node, the number next to the circle is the node's id). You must drill a well at some node so that the sum of distances travelled by all residents is minimised. Adjacent nodes are at distance .
For the tree shown: if the well is built at node , the distance sum is ; if it is built at node , the distance sum is

Input Format
The first line contains one integer : the number of nodes in the tree ().
Each of the following lines describes one node, with three integers separated by (one or more) spaces:
- the first number is the population at the node;
- the second number is the left link, means no left child;
- the third number is the right link, means no right child.
Output Format
Print a single integer: the minimum possible distance sum.
Sample Input
5
13 2 3
4 0 0
12 4 5
20 0 0
40 0 0
Sample Output
81
Constraints
.
Time limit s, memory KiB per test case.
Hint
- Try every node as the well location. For a fixed well, compute each node's distance to it and add
(distance) × (population); take the minimum over all choices. - Distance in a tree is found by a simple traversal (BFS/DFS) from the well node.