Great Cow Gathering
InterviewTime limit1sMemory limit128 MB
Pick a node of a weighted tree with node weights as the gathering point, and minimize the sum of cow count times distance to that node.
- Level
Medium6 of 10
- Topics
- Tree, DFS, Dynamic programming, Prefix sum
- Solved
- No attempts yet
Problem
Bessie is planning the annual Great Cow Gathering and wants to choose the most convenient barn to host it.
Every cow lives in one of barns, numbered through . The barns are connected by roads so that you can travel between any two barns. Road connects barns and and has length ; the barns therefore form a tree. Barn is home to cows.
The gathering may be held in any single barn. If it is held in barn , its inconvenience is the total distance every cow must travel to reach : a barn holding cows at distance from contributes . For example, if cows live in a barn units away from , they add to the inconvenience.
Choose the barn that minimizes the total inconvenience, and report that minimum inconvenience.
Constraints
Input
- Line : a single integer .
- Lines to : line contains a single integer , the number of cows in barn .
- Lines to : each of these lines contains three integers , , and , describing a road of length between barns and .
Output
- A single line containing the minimum possible inconvenience.