Graph Theory37 sections · 1633 units
Open in Course

Implementation - Road Reparation

Kruskal's algorithm

Here is Kruskal's MST implementation:

function roadReparation(n, edges):
    sort edges by cost
    parent = array [0, 1, 2, ..., n]
    totalCost = 0
    edgeCount = 0

    for (u, v, cost) in edges:
        if find(u) != find(v):
            union(u, v)
            totalCost = totalCost + cost
            edgeCount = edgeCount + 1

    if edgeCount == n - 1:
        print totalCost
    else:
        print "IMPOSSIBLE"

Time: O(ElogE)O(E \log E). Space: O(V)O(V).