ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
import heapq
def topo(n, edges):
    indeg = [0] * n
    adj = [[] for _ in range(n)]
    for u, v in edges:
        adj[u].append(v)
        indeg[v] += 1
    h = [i for i in range(n) if indeg[i] == 0]
    heapq.heapify(h)
    out = []
    while h:
        u = heapq.heappop(h)
        out.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                heapq.heappush(h, v)
    return out
print(topo(4, [(3, 0), (1, 0), (2, 0)]), topo(3, [(2, 0), (2, 1)]))
  1. A. [1, 2, 3, 0] [2, 0, 1]
  2. B. [3, 1, 2, 0] [2, 0, 1]
  3. C. [1, 2, 3, 0] [0, 1, 2]
  4. D. [1, 2, 0, 3] [2, 1, 0]

Correct answer: A. [1, 2, 3, 0] [2, 0, 1]

A min-heap of zero in-degree nodes gives the lexicographically smallest order. In the first graph 1, 2 and 3 come before 0, which becomes free only after all three edges are removed.

More Python Programming questions

Exams that ask this topic