#abc210e. E - Ring MST

E - Ring MST

Score : 500500 points

问题描述

我们有一个含有 NN 个顶点且无边的无向图。我们将这 NN 个顶点依次称为顶点 00, 顶点 11, 顶点 22, \ldots, 顶点 N1N-1

考虑对这个图进行 MM 种操作。 对于每一种 i=1,2,,Mi = 1, 2, \ldots, M,第 ii 种操作是选择一个整数 xx 使得 0x<N0 \leq x < N,并添加一条连接顶点 xx 和顶点 (x+Ai)modN(x + A_i) \mod N 的无向边。这里,amodba \bmod b 表示将 aa 除以 bb 后的余数。执行一次第 ii 种操作需要花费 CiC_i 日元。

你可以以任意顺序执行这 MM 种操作任意次(包括零次)。例如,如果有三种操作可选,你可以选择执行第一种操作两次,第二种操作零次,以及执行第三次操作一次。

确定是否可能使该图变得连通。如果可能的话,找出实现这一目标所需的最小总成本。

以上为通义千问 qwen-max 翻译,仅供参考。

Problem Statement

We have an undirected graph with NN vertices and 00 edges. Let us call the NN vertices Vertex 00, Vertex 11, Vertex 22, \ldots, Vertex N1N-1.

Consider MM kinds of operations on this graph.
For each i=1,2,,Mi = 1, 2, \ldots, M, the operation of the ii-th kind is to choose an integer xx such that 0x<N0 \leq x \lt N and add an undirected edge connecting Vertex xx and Vertex (x+Ai)modN(x + A_i) \bmod N. Here, amodba \bmod b denotes the remainder when dividing aa by bb. It costs CiC_i yen to do the operation of the ii-th kind once.

You can do these MM kinds of operations any number of times (possibly zero) in any order. For example, if three kinds of operations are available, you can choose to do the first operation twice, the second zero times, and the third once.

Determine whether it is possible to make the graph connected. If it is possible, find the minimum total cost needed to do so.

Constraints

  • 2N1092 \leq N \leq 10^9
  • 1M1051 \leq M \leq 10^5
  • 1AiN11 \leq A_i \leq N-1
  • 1Ci1091 \leq C_i \leq 10^9
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN MM

A1A_1 C1C_1

A2A_2 C2C_2

\vdots

AMA_M CMC_M

Output

If it is possible to make the graph connected, print the minimum total cost needed to do so.
If it is impossible to make the graph connected, print 1-1.

Sample Input 1

4 2
2 3
3 5

Sample Output 1

11

If we first do the operation of the first kind to connect Vertices 00 and 22, then do it again to connect Vertices 11 and 33, and finally the operation of the second kind to connect Vertices 11 and 00, the graph will be connected. The total cost incurred here is 3+3+5=113+3+5 = 11 yen, which is the minimum possible.

Sample Input 2

6 1
3 4

Sample Output 2

-1

There is no way to make the graph connected, so we should print 1-1.

update @ 2024/3/10 09:25:09