ProgrammingHardCodeforces-style · placement coding round

What is printed?

What is printed?
def comps(n, edges):
    p = list(range(n))
    def find(x):
        while p[x] != x:
            p[x] = p[p[x]]
            x = p[x]
        return x
    cnt = n
    for u, v in edges:
        a, b = find(u), find(v)
        if a != b:
            p[a] = b
            cnt -= 1
    return cnt
print(comps(6, [(0, 1), (1, 2), (3, 4), (2, 0)]), comps(4, []))
  1. A. 3 4
  2. B. 4 4
  3. C. 2 4
  4. D. 3 3

Correct answer: A. 3 4

Start with one component per vertex and subtract one for each edge that joins two different components. The edges 0-1, 1-2 and 3-4 merge, while 2-0 is redundant, which leaves 3 components.

More Python Programming questions

Exams that ask this topic