atcoder#ABC210E. [ABC210E] Ring MST
[ABC210E] Ring MST
Score : points
Problem Statement
We have an undirected graph with vertices and edges. Let us call the vertices Vertex , Vertex , Vertex , , Vertex .
Consider kinds of operations on this graph. For each , the operation of the -th kind is to choose an integer such that and add an undirected edge connecting Vertex and Vertex . Here, denotes the remainder when dividing by . It costs yen to do the operation of the -th kind once.
You can do these 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
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
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 .
4 2
2 3
3 5
11
If we first do the operation of the first kind to connect Vertices and , then do it again to connect Vertices and , and finally the operation of the second kind to connect Vertices and , the graph will be connected. The total cost incurred here is yen, which is the minimum possible.
6 1
3 4
-1
There is no way to make the graph connected, so we should print .