Under construction

Still being built. Things may change

Mountains and Valleys

Time limit7sMemory limit512 MB

Summary
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 NN sites you want to visit and MM trails connecting pairs of sites. Each trail has a positive integer difficulty level.

The trail system is special. Exactly N−1N-1 trails have difficulty level 1, and these are completely flat. Every other trail has difficulty at least ⌈N/3⌉\lceil N/3 \rceil, and these are very mountainous. (⌈x⌉\lceil x \rceil is the smallest integer greater than or equal to xx.)

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 dd a total of kk times adds k⋅dk \cdot d to the sum.

Input

The first line contains two space-separated integers NN (4≤N≤5000004 \le N \le 500000) and MM (N−1≤M≤2000000N-1 \le M \le 2000000). Each of the next MM lines contains three space-separated integers xix_i, yiy_i, and wiw_i, meaning a trail joins sites xix_i and yiy_i with difficulty wiw_i (1≤i≤M1 \le i \le M; 0≤xi,yi≤N−10 \le x_i, y_i \le N-1; xi≠yix_i \ne y_i). Each pair of sites is joined by at most one trail. Each wiw_i is either 1 or satisfies ⌈N/3⌉≤wi≤N\lceil N/3 \rceil \le w_i \le N.

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.

Flat trails

The second figure shows all trails with their difficulty levels.

All trails

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

Mountainous trails

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.

Examples1

  1. Example 1

    Input
    9 10
    0 1 1
    0 2 1
    0 3 1
    1 4 1
    2 5 1
    2 6 1
    3 7 1
    3 8 1
    2 4 5
    6 7 3
    
    Expected output
    11