atcoder#CODEFESTIVAL2016FINALG. Zigzag MST

Zigzag MST

Score : 13001300 points

Problem Statement

We have a graph with NN vertices, numbered 00 through N1N-1. Edges are yet to be added.

We will process QQ queries to add edges. In the ii-th (1iQ)(1 \leq i \leq Q) query, three integers Ai,BiA_i, B_i and CiC_i will be given, and we will add infinitely many edges to the graph as follows:

  • The two vertices numbered AiA_i and BiB_i will be connected by an edge with a weight of CiC_i.
  • The two vertices numbered BiB_i and Ai+1A_i+1 will be connected by an edge with a weight of Ci+1C_i+1.
  • The two vertices numbered Ai+1A_i+1 and Bi+1B_i+1 will be connected by an edge with a weight of Ci+2C_i+2.
  • The two vertices numbered Bi+1B_i+1 and Ai+2A_i+2 will be connected by an edge with a weight of Ci+3C_i+3.
  • The two vertices numbered Ai+2A_i+2 and Bi+2B_i+2 will be connected by an edge with a weight of Ci+4C_i+4.
  • The two vertices numbered Bi+2B_i+2 and Ai+3A_i+3 will be connected by an edge with a weight of Ci+5C_i+5.
  • The two vertices numbered Ai+3A_i+3 and Bi+3B_i+3 will be connected by an edge with a weight of Ci+6C_i+6.
  • ...

Here, consider the indices of the vertices modulo NN. For example, the vertice numbered NN is the one numbered 00, and the vertice numbered 2N12N-1 is the one numbered N1N-1.

The figure below shows the first seven edges added when N=16,Ai=7,Bi=14,Ci=1N=16, A_i=7, B_i=14, C_i=1:

After processing all the queries, find the total weight of the edges contained in a minimum spanning tree of the graph.

Constraints

  • 2N200,0002 \leq N \leq 200,000
  • 1Q200,0001 \leq Q \leq 200,000
  • 0Ai,BiN10 \leq A_i,B_i \leq N-1
  • 1Ci1091 \leq C_i \leq 10^9

Input

The input is given from Standard Input in the following format:

NN QQ

A1A_1 B1B_1 C1C_1

A2A_2 B2B_2 C2C_2

:

AQA_Q BQB_Q CQC_Q

Output

Print the total weight of the edges contained in a minimum spanning tree of the graph.

7 1
5 2 1
21

The figure below shows the minimum spanning tree of the graph:

Note that there can be multiple edges connecting the same pair of vertices.

2 1
0 0 1000000000
1000000001

Also note that there can be self-loops.

5 3
0 1 10
0 2 10
0 4 10
42