Connecting Cities With Minimum Cost
For this problem, we can use Kruskal’s algorithm to find the minimum spanning tree (MST) of the graph that represents the cities and connections. A minimum spanning tree is a subset of the edges that forms a tree that includes every vertex, where the sum of the weights of the edges in the tree is minimized.
The solution will follow these steps:
- Sort the connections by their cost.
- Use Union-Find (Disjoint Set Union) to connect the cities, starting with the smallest cost connections.
- Keep track of the total cost and the number of cities connected.
- If the number of connected cities reaches n, return the total cost. Otherwise, return -1 if connecting all cities is impossible.
Below is the implementation:
|
|
The function find
is a helper function to find the root of a city using a path compression technique. It is part of the Union-Find algorithm.