ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
import heapq
def dijk(g, s):
    d = {s: 0}
    h = [(0, s)]
    while h:
        du, u = heapq.heappop(h)
        if du > d[u]:
            continue
        for v, w in g[u]:
            if du + w < d.get(v, float('inf')):
                d[v] = du + w
                heapq.heappush(h, (d[v], v))
    return d
g = {'A': [('B', 4), ('C', 1)], 'C': [('B', 2), ('D', 7)], 'B': [('D', 1)], 'D': []}
print(sorted(dijk(g, 'A').items()))
  1. A. [('A', 0), ('B', 3), ('C', 1), ('D', 4)]
  2. B. [('A', 0), ('B', 4), ('C', 1), ('D', 5)]
  3. C. [('A', 0), ('B', 3), ('C', 1), ('D', 8)]
  4. D. [('A', 0), ('B', 4), ('C', 1), ('D', 4)]

Correct answer: A. [('A', 0), ('B', 3), ('C', 1), ('D', 4)]

Dijkstra pops the smallest tentative distance first and skips stale heap entries. B is reached through C at cost 1 + 2 = 3, which beats the direct 4, and D costs 3 + 1 = 4.

More Python Programming questions

Exams that ask this topic