Connect the Forest
Time limit2sMemory limit256 MB
Given a weighted forest, add disjoint vertex pairs (each vertex used at most once) so the graph becomes connected, minimizing the sum of the paired values, or report Impossible.
- Level
Medium7 of 10
- Topics
- Greedy, Sorting, Union-find, Graph
- Solved
- No attempts yet
Problem
You are given a forest with vertices and edges. The vertices are numbered through . Each edge is given as , meaning that vertices and are connected by an edge.
Each vertex is assigned a value . You want to add edges to the given forest so that it becomes a single connected graph. To add an edge, choose two different vertices and and place an edge between them. This operation costs dollars, and afterward neither vertex nor can be chosen again.
Find the minimum total cost needed to make the forest connected, or print "Impossible" if it is impossible.
Input
Input is given in the following format:
Output
Print the minimum total cost needed to make the forest connected, or print "Impossible" if it is impossible.
Constraints
, , , . The given graph is a forest. All input values are integers.
Hint
In Sample 1, connecting vertices and makes the graph connected, and the cost is .
In Sample 2, the graph cannot be connected.
In Sample 3, the graph is connected whether or not we do anything.