Introduction to Algorithms (Dynamic Programming II: Text Justification, Blackjack)

5 easy steps to DP

  1. define subproblems #subproblems
  2. guess (part of the solution) #choices for guess
  3. relate subproblem solutions #time/subproblems
  4. recursive & memoize or build DP table bottom-up #check subproblem is acyclic
  5. solve original problem #extra time

Text justification

Split the text into "good" lines

  • obvious (MS Word/Open Office) algorithm: put as many words that fit on the first line, repeat
  • but this can make very bad lines
  • Define badness(i, j) for line of words[i : j]. For example, ∞ if total length > page width, else (page width − total length)^3.
  • goal: split words into lines to min \sum badness
  1. subproblems = min. badness for suffix words[i :] # subproblems = Θ(n) where n = # words
  2. guess: where to start the second line # guess <= n - i = O(n)
  3. recurrence:
    1. DP(i) = DP[i] = min(badness (i, j) + DP[j] for j in range (i + 1, n + 1))
    2. DP[n] = 0 ⇒ time per subproblem = Θ(n)
  4. order: for i = n, n − 1, . . . , 1, 0 total time = Θ(n^2)
  5. original problem: DP(0)

Parent Pointers

To recover actual solution in addition to cost, store parent pointers (which guess used at each subproblem) & walk back

  • typically: remember argmin/argmax in addition to min/max
  • just like memoization & bottom-up, this transformation is automatic

猜你喜欢

转载自blog.csdn.net/Da_tianye/article/details/81352285