ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
def mst(n, edges):
    p = list(range(n))
    def f(x):
        while p[x] != x:
            x = p[x]
        return x
    total = 0
    for w, u, v in sorted(edges):
        a, b = f(u), f(v)
        if a != b:
            p[a] = b
            total += w
    return total
print(mst(4, [(1, 0, 1), (4, 1, 2), (3, 0, 2), (2, 2, 3), (5, 1, 3)]))
  1. A. 7
  2. B. 5
  3. C. 6
  4. D. 10

Correct answer: C. 6

Kruskal's algorithm takes edges by weight and skips any edge that closes a cycle. It keeps weights 1, 2 and 3, and the edge of weight 4 and the edge of weight 5 are skipped.

More Python Programming questions

Exams that ask this topic