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)]))- A. 7
- B. 5
- C. 6
- 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
- What is printed? python def candy(r): n = len(r) c = [1] n for i in range(1, n): if r[i] > r[i - 1]: c[i] = c[i - 1] + 1 for i in range(n…
- What is printed? python def mat(a, b, m): return [[sum(a[i][k] b[k][j] for k in range(2)) % m for j in range(2)] for i in range(2)] def…
- What is printed? python class A: x = 1 def get(self): return self.x a = A() a.x = 5 A.x = 9 b = A() print(a.get(), b.get(), A.x)
- What is printed? python class A: def f(self): return ['A'] class B(A): def f(self): return ['B'] + super().f() class C(A): def f(self)…
- What is printed? python from itertools import product print(len(list(product('01', repeat=3))), list(product('ab', 'x'))[-1], sum(1 for in…
- What is printed? python import heapq, itertools c = itertools.count() h = [] for p, name in [(2, 'x'), (1, 'y'), (2, 'z'), (1, 'w')]…