PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GL0000331. Kết nối vòng tròn với chi phí nhỏ nhất (Ring MST)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Kết nối vòng tròn với chi phí nhỏ nhất (Ring MST)

Ring MST

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

Initially an undirected graph has NN vertices numbered 00 through N−1N-1 and no edges. There are MM types of operations.

For operation type ii, choose any vertex xx with 0≤x<N0\le x<N and add an undirected edge between xx and (x+Ai) mod N(x+A_i)\bmod N. This single edge costs CiC_i. You may use each operation type any number of times, including zero.

Find the minimum total cost required to make the graph connected, or output −1-1 if it is impossible.

One operation adds exactly one edge; it does not add every edge of that type simultaneously.

Input

The first line contains N,MN,M. Each of the following MM lines contains Ai,CiA_i,C_i.

Output

Print the minimum total cost, or -1 if impossible.

Subtasks

  • Subtask 1 (20 points): 2≤N≤122\le N\le 12, 1≤M≤81\le M\le 8, 1≤Ai<N1\le A_i<N, 1≤Ci≤1001\le C_i\le 100.
  • Subtask 2 (30 points): 2≤N≤20002\le N\le 2000, 1≤M≤50001\le M\le 5000, 1≤Ai<N1\le A_i<N, 1≤Ci≤1061\le C_i\le 10^6.
  • Subtask 3 (50 points): 2≤N≤1092\le N\le 10^9, 1≤M≤1051\le M\le 10^5, 1≤Ai<N1\le A_i<N, 1≤Ci≤1091\le C_i\le 10^9.

Examples

Example 1

Input

4 2
2 3
3 5

Output

11

Explanation

Two edges of step 22 cost 33 each, connecting 00 to 22 and 11 to 33. One edge of step 33 connects the two components for 55, giving 3+3+5=113+3+5=11.

Example 2

Input

6 1
3 4

Output

-1

Explanation

Step 33 on six vertices connects only opposite pairs; the graph cannot become connected.

Note: Each input file contains one case using the specified format.