Under construction

Still being built. Things may change

Fair Meeting

Time limit2sMemory limit1024 MB

Summary
Fill in the unknown integer distances so that no triangle has a unique smallest edge, minimizing the total, or report -1 if impossible.
Level

Hard8 of 10

Topics
Graph, Union-find, Greedy
Solved
No attempts yet

Problem

In the distant future, SNUPS has grown into a large club of NN members, driven by a boom in algorithm education. Any two distinct members can be assigned a closeness distance, an integer C(i,j)C(i,j) where a smaller value means the two are closer. For all 1≤i,j≤N1\le i, j\le N with i≠ji\ne j, 1≤C(i,j)≤1071\le C(i,j)\le 10^7 and C(i,j)=C(j,i)C(i,j)=C(j,i).

Each time an agenda item comes up, SNUPS picks three of the NN members at random to hold the meeting. When two of the three who are close join forces, the third member's opinion is not reflected. Concretely, if the three distinct members picked are ii, jj, and kk, and C(i,j)<C(j,k)C(i,j) < C(j,k) and C(i,j)<C(i,k)C(i,j) < C(i,k), then member kk's opinion is not reflected. Such a meeting is called unfair.

Jeyeon wants to make sure no unfair meeting can happen for any three members. So far, only MM pairs of members know each other. The distances of known pairs cannot change, but Jeyeon can set the distances of unknown pairs as she likes. The final distances must still be integers within range and symmetric.

If such a plan is feasible, the goal is to minimize ∑i=1N∑j=i+1NC(i,j)\sum_{i=1}^{N}\sum_{j=i+1}^{N} C(i,j). Determine whether the plan is feasible, and if it is, find the minimum value of this sum.

Input

The first line contains NN and MM. Each of the next MM lines contains three integers AiA_i, BiB_i, and DiD_i, meaning members AiA_i and BiB_i already know each other and their closeness distance is DiD_i.

Output

Print -1 if the plan cannot be carried out. Otherwise, print the minimum value of ∑i=1N∑j=i+1NC(i,j)\sum_{i=1}^{N}\sum_{j=i+1}^{N} C(i,j).

Constraints

  • 3≤N≤300,0003 \le N \le 300,000
  • 0≤M≤300,0000 \le M \le 300,000
  • 1≤Ai,Bi≤N1 \le A_i, B_i \le N, Ai≠BiA_i \ne B_i, and {Ai,Bi}≠{Aj,Bj}\{A_i, B_i\} \ne \{A_j, B_j\} for i≠ji \ne j
  • 1≤Di≤1071 \le D_i \le 10^{7}

Examples2

  1. Example 1

    Input
    4 2
    1 2 5
    2 4 3
    
    Expected output
    14
    
  2. Example 2

    Input
    4 4
    1 2 10
    1 3 20
    2 4 30
    3 4 40
    
    Expected output
    -1