awelgorithms

DAG DP in topo order

Updated

On a DAG, dp[u] depends only on successors (or only on predecessors). Process vertices in topological order so every neighbor you read is done. Cycles break this; you need another method.

What to focus on

a[u] is the out-list. Longest path from u: dp[u] = 0 if no out-edge else 1+max dp[v] for v in a[u]. Fill sinks first if you read successors, sources first if you read predecessors.

Worked examples

path length 2

a = [[1], [2], []]
  1. dp[2]=0
  2. dp[1]=1
  3. dp[0]=2

Result: longest from 0 is 2

two outs

a = [[1, 2], [2], []]
  1. dp[2]=0
  2. dp[1]=1
  3. dp[0]=max(1+1, 1+0)=2

Result: 2

isolated

a = [[]]
  1. no successor
  2. dp[0]=0

Result: 0

Try it

Write dagDp(a). a is a DAG adjacency list: a[u] is the out-neighbor list of u. dp[u] is longest path from u (edges). Topo-fill. Write dp at sinks first when the rec reads out-neighbors. Return dp[0]. A vertex with no out-edge is 0. [[1], [2], []] → 2. [[1, 2], [2], []] → 2. [[]] → 0.

The graph is a DAG with 1–4 labeled vertices. Edges are valid indices. A topological order exists.