The cheapest crossing is safe
transcript
Join all towns by road. A town has many possible roads. Spend as little as possible. Which road do you build first? The cheapest one that helps. Sort, then check the groups.
Build the cheapest road between two groups. That road is always safe. Skip a road inside one group. It adds cost for nothing.
Sort the road costs. Cheapest first. Build one and one. Build two. Two groups remain. The total is four. Three roads built, three skipped.
The tree must cross each gap. Swap in the cheaper link. Then the tree stays no dearer. The cost never rises.
Sorting costs m log m. Union-find costs almost nothing per link. So the sort dominates. That is fast enough for most inputs.
Union-find tells you the groups. Sorting tells you the order. Cheapest first, always. Together they are Kruskal.
Sort the roads. Build what joins two groups. One group at a time. Skip loops. Full breakdown in the lecture.