Data Structures & AlgorithmsHardTCS NQT · Infosys pattern
Kruskal's algorithm: which edges are accepted, in order, for the graph below?
Kruskal's algorithm: which edges are accepted, in order, for the graph below?
edges = sorted([(7, 'A', 'B'), (5, 'A', 'D'), (8, 'B', 'C'), (9, 'B', 'D'), (7, 'B', 'E'),
(5, 'C', 'E'), (15, 'D', 'E'), (6, 'D', 'F'), (8, 'E', 'F'), (9, 'E', 'G'), (11, 'F', 'G')])
p = {v: v for v in 'ABCDEFG'}
def f(x):
while p[x] != x: x = p[x]
return x
acc = []
for w, u, v in edges:
if f(u) != f(v): p[f(u)] = f(v); acc.append(u + v)
print(acc, sum(w for w, u, v in edges if u + v in acc))- A. ['AD', 'CE', 'DF', 'AB', 'BE', 'EF'] 38
- B. ['AD', 'CE', 'DF', 'AB', 'BC', 'EG'] 40
- C. ['AD', 'DF', 'CE', 'AB', 'BE', 'EG'] 39
- D. ['AD', 'CE', 'DF', 'AB', 'BE', 'EG'] 39
Correct answer: D. ['AD', 'CE', 'DF', 'AB', 'BE', 'EG'] 39
Sorted by weight (ties by name): AD 5, CE 5, DF 6, AB 7, BE 7 accepted; BC 8 and EF 8 would close cycles (C–E–B and E–B–A–D–F); BD 9 also a cycle; EG 9 accepted. 6 edges for 7 vertices, total 5 + 5 + 6 + 7 + 7 + 9 = 39. O(E log E).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- How many times is the base case reached when computing C(5, 2) with the plain recursion C(n, k) = C(n−1, k−1) + C(n−1, k)? python base = 0…
- What is printed? (Tower of Hanoi: number of moves and the 5th move) python moves = [] def hanoi(n, a, b, c): if n == 0: return hanoi(n…
- What is printed? (recursion output order) python out = [] def f(n): if n == 0: return out.append(n) f(n - 1) out.append(n) f(3) print(out)
- Solve the recurrences numerically: how many 'work units' does each do for n = 64? python from functools import lrucache @lrucache(None)…
- 0/1 knapsack, capacity 50: items (weight, value) = (10, 60), (20, 100), (30, 120). What do greedy-by-ratio and DP give? python items =…
- Activity selection: activities (start, finish). How many can one person attend, and which? python acts = [(1, 4), (3, 5), (0, 6), (5, 7)…