1100. Connecting Cities With Minimum Cost

Medium
Union Find
Graph
Heap (Priority Queue)
Minimum Spanning Tree

Description

Hints

Hint 1
What if we model the cities as a graph?
Hint 2
Build a graph of cities and find the minimum spanning tree.
Hint 3
You can use a variation of the Kruskal's algorithm for that.
Hint 4
Sort the edges by their cost and use a union-find data structure.
Hint 5
How to check all cities are connected?
Hint 6
At the beginning we have n connected components, each time we connect two components the number of connected components is reduced by one. At the end we should end with only a single component otherwise return -1.

Statistics

Acceptance
63.3%
Submissions
141,972
Accepted
89,924