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()))- A. [('A', 0), ('B', 3), ('C', 1), ('D', 4)]
- B. [('A', 0), ('B', 4), ('C', 1), ('D', 5)]
- C. [('A', 0), ('B', 3), ('C', 1), ('D', 8)]
- 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
- What is printed? python from collections import deque def topo(n, edges): indeg = [0] n adj = [[] for in range(n)] for u, v in edges…
- What is printed? python dp = [0] 16 for i in range(1, 16): dp[i] = dp[i >> 1] + (i & 1) print(dp[13], sum(dp))
- What is printed? python print([format(i ^ (i >> 1), '02b') for i in range(4)])
- What is printed? python from functools import reduce import operator a = [4, 1, 2, 1, 2] print(reduce(operator.xor, a)…
- What is printed? python def spf(n): s = list(range(n + 1)) for i in range(2, int(n 0.5) + 1): if s[i] == i: for j in range(i i, n + 1, i)…
- What is printed? python def row(n): r = [1] for in range(n): r = [1] + [r[i] + r[i + 1] for i in range(len(r) - 1)] + [1] return r…