Data Structures & AlgorithmsVery hardProduct company OA
Floyd–Warshall with the correct loop order (k outermost) and with k innermost. What is printed (d[0][1], d[2][0], d[0][3] for each)?
Floyd–Warshall with the correct loop order (k outermost) and with k innermost. What is printed (d[0][1], d[2][0], d[0][3] for each)?
INF = float("inf")
def fw(order):
n = 4
d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for a, b, w in [(0, 2, 9), (1, 0, 2), (2, 3, 6), (3, 1, 1)]: d[a][b] = w
if order == "kij":
for k in range(n):
for i in range(n):
for j in range(n): d[i][j] = min(d[i][j], d[i][k] + d[k][j])
else:
for i in range(n):
for j in range(n):
for k in range(n): d[i][j] = min(d[i][j], d[i][k] + d[k][j])
return d[0][1], d[2][0], d[0][3]
print(fw("kij"), fw("ijk"))- A. (16, 9, 15) (16, 9, 15)
- B. (inf, inf, 15) (16, 9, 15)
- C. (16, 11, 15) (inf, 9, 15)
- D. (16, 9, 15) (inf, inf, 15)
Correct answer: D. (16, 9, 15) (inf, inf, 15)
With k outermost, after iteration k every d[i][j] is optimal among paths whose intermediate vertices are in {0..k}, so all paths are found: 0 → 2 → 3 → 1 = 16 and 2 → 3 → 1 → 0 = 9. With k innermost, d[i][j] is finalised once, using d[i][k] and d[k][j] values that may not be computed yet: d[0][1] needs d[0][3] (computed later in row 0) and d[2][0] needs d[2][1] (later in row 2), so both stay ∞. d[0][3] only needed already-final entries. Same O(n³), wrong answers.
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
- Tarjan's SCC algorithm, then the condensation DAG. What is printed (SCCs, source components, sink components, minimum edges to add to make…
- Centroid of a tree: the vertex whose removal leaves the largest remaining component as small as possible. What is printed (centroid(s)…
- Assignment problem (worker i → distinct job) by DP over bitmasks of used jobs, versus row-by-row greedy. What is printed (optimal cost…
- Recursive segment tree with children 2·node and 2·node + 1: the largest array index actually used for a given n. What is printed? python…
- Match each recurrence to its tight bound: (P) T(n) = 2T(n/2) + n log n (Q) T(n) = 2T(n/2) + n / log n (R) T(n) = T(n/2) + log n (S) T(n) =…
- A road network has n ≤ 2·10⁵ junctions and m ≤ 2·10⁵ roads; each road is either free (0) or tolled (1). You need the minimum number of…