atcoder#CODEFESTIVAL2016FINALG. Zigzag MST
Zigzag MST
Score : points
Problem Statement
We have a graph with vertices, numbered through . Edges are yet to be added.
We will process queries to add edges. In the -th query, three integers and will be given, and we will add infinitely many edges to the graph as follows:
- The two vertices numbered and will be connected by an edge with a weight of .
- The two vertices numbered and will be connected by an edge with a weight of .
- The two vertices numbered and will be connected by an edge with a weight of .
- The two vertices numbered and will be connected by an edge with a weight of .
- The two vertices numbered and will be connected by an edge with a weight of .
- The two vertices numbered and will be connected by an edge with a weight of .
- The two vertices numbered and will be connected by an edge with a weight of .
- ...
Here, consider the indices of the vertices modulo . For example, the vertice numbered is the one numbered , and the vertice numbered is the one numbered .
The figure below shows the first seven edges added when :
After processing all the queries, find the total weight of the edges contained in a minimum spanning tree of the graph.
Constraints
Input
The input is given from Standard Input in the following format:
:
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