Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (longest path in a DAG using topological order)

What is printed? (longest path in a DAG using topological order)
g = {'A': [('B', 3), ('C', 2)], 'B': [('D', 4)], 'C': [('D', 1), ('E', 6)], 'D': [('F', 2)], 'E': [('F', 1)], 'F': []}
order = ['A', 'B', 'C', 'D', 'E', 'F']
dist = {v: float('-inf') for v in g}; dist['A'] = 0
for u in order:
    for v, w in g[u]:
        dist[v] = max(dist[v], dist[u] + w)
print(dist['F'], dist['D'])
  1. A. 9 3
  2. B. 8 7
  3. C. 11 7
  4. D. 9 7

Correct answer: D. 9 7

Process vertices in topological order and relax with max instead of min. D = max(A→B→D = 7, A→C→D = 3) = 7; F = max(D + 2 = 9, E + 1 = 8 + 1 = 9) = 9. Longest path is NP-hard in general graphs but O(V + E) in a DAG.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic