Data Structures & AlgorithmsHardTCS CodeVita · Microsoft SDE OA
Floyd–Warshall is run on the 4-vertex directed weighted graph with matrix rows [0,3,∞,7], [8,0,2,∞], [5,∞,0,1], [2,∞,∞,0]. Sum the final shortest distances over all ordered pairs (i, j) with a finite distance, including i = j. Run the code.
Floyd–Warshall is run on the 4-vertex directed weighted graph with matrix rows [0,3,∞,7], [8,0,2,∞], [5,∞,0,1], [2,∞,∞,0]. Sum the final shortest distances over all ordered pairs (i, j) with a finite distance, including i = j. Run the code.
INF=10**9
d=[[0,3,INF,7],[8,0,2,INF],[5,INF,0,1],[2,INF,INF,0]]
n=4
for k in range(n):
for i in range(n):
for j in range(n):
if d[i][k]+d[k][j]<d[i][j]: d[i][j]=d[i][k]+d[k][j]
print(sum(d[i][j] for i in range(n) for j in range(n) if d[i][j]<INF))What is printed?- A. 50
- B. 48
- C. 16
- D. 28
Correct answer: B. 48
Floyd–Warshall must loop over the intermediate vertex k as the outermost loop, which the stem's order satisfies. Moving k inside gives wrong distances, counting reachable pairs instead of summing distances is a different quantity, and skipping the relaxation leaves the direct edge weights.
More Coding Interview Problems questions
- A rod of length 8 can be cut into integer pieces, and a piece of length L sells for p[L] with p = [1, 5, 8, 9, 10, 17, 17, 20] for L =…
- Array b = [1, 11, 2, 10, 4, 5, 2, 1]. Find the length of its longest bitonic subsequence: a subsequence that strictly increases and then…
- Count the 4-element subsets of {1, 2, ..., 12} whose sum is divisible by 5. Count by brute force over combinations. python from itertools…
- Find the smallest positive integer x such that x ≡ 2 (mod 3), x ≡ 3 (mod 5) and x ≡ 2 (mod 7). Solve by brute-force search. python…
- How many trailing zeros does 100! have in base 10? Use Legendre's formula with powers of 5, counted by running the loop over p = 5, 25…
- The string s = "abcbdab" needs characters deleted to become a palindrome. What is the minimum number of deletions? Use n minus the longest…