Cheapest way to connect everything

n towns are numbered 0 to n - 1 and roads lists possible (a, b, cost) links. Write min_connection_cost(n, roads) that returns the smallest total cost of a set of roads that connects every town, or -1 if they cannot all be connected.

min_connection_cost(4, [(0, 1, 1), (1, 2, 2), (2, 3, 3), (0, 3, 10), (1, 3, 4)])  ->  6
min_connection_cost(3, [(0, 1, 1)])  ->  -1

Kruskal's algorithm: sort roads by cost and take each one that joins two towns not already connected. "Already connected" is answered by a disjoint-set (union-find): a parent list where find(x) follows parents to a root, and union(a, b) links one root under the other. Build it yourself; it is a dozen lines.

def min_connection_cost(n, roads):
    ...