atcoder#APC001D. Forest
Forest
Score : points
Problem Statement
You are given a forest with vertices and edges. The vertices are numbered through . The edges are given in the format , which means that Vertex and are connected by an edge.
Each vertex has a value . You want to add edges in the given forest so that the forest becomes connected. To add an edge, you choose two different vertices and , then span an edge between and . This operation costs dollars, and afterward neither Vertex nor can be selected again.
Find the minimum total cost required to make the forest connected, or print Impossible
if it is impossible.
Constraints
- The given graph is a forest.
- All input values are integers.
Input
Input is given from Standard Input in the following format:
Output
Print the minimum total cost required to make the forest connected, or print Impossible
if it is impossible.
7 5
1 2 3 4 5 6 7
3 0
4 0
1 2
1 3
5 6
7
If we connect vertices and , the graph becomes connected, for the cost of dollars.
5 0
3 1 4 1 5
Impossible
We can't make the graph connected.
1 0
5
0
The graph is already connected, so we do not need to add any edges.