Soldering
Time limit2sMemory limit128 MB
Given a tree, cover its edges with paths (wires) that may meet at soldered points, minimizing the sum of squared path lengths.
- Level
Medium7 of 10
- Topics
- Tree, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
The cows are playing with wires! The soldering technique the cows have learned attaches the end of one wire to the middle of another wire. (Soldering two wires end to end is not allowed.) Several wires may be soldered onto the same point.
Using this technique, the cows want to build an impressive structure. The structure is a tree made of connected vertices () and unit-length edges. Each edge is given by two integers and (, , ), the numbers of the vertices at its two ends.
To build the structure the cows must buy wires. Longer wires are more expensive: a wire of length costs . Wires may not be cut, nor spliced together into longer wires.
Given the blueprint of the structure, compute the minimum cost to build it by soldering wires.
Note: for 50% of the test data, .
Input
- The first line contains the integer .
- Each of the next lines contains two integers and describing an edge.
Output
Print, on a single line, the minimum cost to build the structure. The answer may exceed the range of a 32-bit integer.
Hint
Consider a star in which every vertex is connected directly to vertex 1: you can join two edges into a single wire of length 2 and use a length-1 wire for each remaining edge. With 6 vertices the cost is .