Mountains and Valleys
Time limit7sMemory limit512 MB
Find the minimum total difficulty of a walk that visits all N sites, where the flat trails of difficulty 1 form a spanning tree and all other trails are heavy.
- Level
Hard8 of 10
- Topics
- Graph, Tree, Dynamic programming
- Solved
- No attempts yet
Problem
You are planning a long hiking trip through interesting but well-known terrain. There are sites you want to visit and trails connecting pairs of sites. Each trail has a positive integer difficulty level.
The trail system is special. Exactly trails have difficulty level 1, and these are completely flat. Every other trail has difficulty at least , and these are very mountainous. ( is the smallest integer greater than or equal to .)
It is possible to travel between any two sites using only the trails with difficulty level 1.
You want to visit every site at least once. You may start at any site, and you must end at a different site. Find the walk with the minimum total difficulty. Walking a trail with difficulty a total of times adds to the sum.
Input
The first line contains two space-separated integers () and (). Each of the next lines contains three space-separated integers , , and , meaning a trail joins sites and with difficulty (; ; ). Each pair of sites is joined by at most one trail. Each is either 1 or satisfies .
Output
Output one integer: the minimum sum of difficulty levels over all walks that visit every site at least once.
Hint
The first figure shows the trails with difficulty level 1.

The second figure shows all trails with their difficulty levels.

The third figure shows all trails except those with difficulty level 1.

An optimal walk is 4 → 1 → 0 → 2 → 5 → 2 → 6 → 7 → 3 → 8, with total cost 1 + 1 + 1 + 1 + 1 + 1 + 3 + 1 + 1 = 11. No walk that visits every site has a lower total difficulty.