Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
006
Massachusetts Institute of Technology November 8, 2018
Instructors: Zachary Abel, Erik Demaine, Jason Ku Lecture 17: Dynamic Programming II
• “Recurse but reuse” (Top down: record and lookup subproblem solutions)
• State topological order to argue relations are acyclic and form a DAG
2. Relate
3. Base
4. Solution
5. Time
• # subproblems: |V | × (|V | + 1)
• Work for subproblem x(v, k): O(degin (v))
|V | |V |
X X X
O(degin (v)) = O(|E|) = O(|V ||E|)
k=0 v∈V k=0
• Computing δ(s, v) takes O(|V |) time per vertex, so O(|V |2 ) time in total
• Running time O(|V |(|V | + |E|)). Can we make O(|V ||E|)?
• Only search on vertices reachable from s, then |V | ≤ |E| + 1 = O(|E|)
• Such vertices can be found via BFS or DFS in O(|V | + |E|) time
Rod Cutting
• Given a rod of length n and the value v(i) of any rod piece of integral length i for 1 ≤ i ≤ n,
cut the rod to maximize the value of cut rod pieces.
1. Subproblems
2. Relate
3. Base
4. Solution
5. Time
• # subproblems: n
• work per subproblem: O(i)
• O(n2 ) running time
Lecture 17: Dynamic Programming II 5
1 # recursive
2 x = {}
3 def cut_rod(w, v):
4 if w < 1: return 0 # base case
5 if w not in x: # check memo
6 for piece in range(1, w + 1): # try piece
7 x_ = v[piece] + cut_rod(w - piece, v) # recurrence
8 if (w not in x) or (x[w] < x_): # update memo
9 x[w] = x_
10 return x[w]
1 # iterative
2 def cut_rod(n, v):
3 x = [0] * (n + 1) # base case
4 for w in range(n + 1): # topological order
5 for piece in range(1, w + 1): # try piece
6 x_ = v[piece] + x[w - piece] # recurrence
7 if x[w] < x_: # update memo
8 x[w] = x_
9 return x[n]