Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- algorithm PrintingNeatly ( M; l1 , . . . , ln )
- pre-cond : l1 , . . . , ln are the lengths of the words, and M is the length of each line.
- post-cond : opt Sol splits the text into lines in an optimal way, and cost is its cost.
- begin
- % Table: optSol[i] would store an optimal way to print the first i words of the input,
- but actually we store only the bird’s advice for the subinstance and the cost of its
- solution.
- table[0..n] birdAdvice, cost
- % Base case: The only base case is for the best printing of the first zero words.
- Its solution is the empty printing with cost zero.
- % optSol[0] = ∅
- cost[0] = 0
- birdAdvice[0] = ∅
- % General cases: Loop over subinstances in the table.
- for i = 1 to n
- % Solve instance M; l1 , . . . , li and fill in table entry i .
- K = maximum number k such that the words of length li−k+1 , . . . , li fit
- on a single line.
- % Try each possible bird answers.
- for k = 1 to K
- % The bird-and-friend algorithm: The bird tells us to put k words on the
- last line. We ask the friend for an optimal printing of the first i − k words.
- He gives us optSol[i − k], which he had stored in the table. To this we add
- the bird’s k words on a new last line. This gives us optSolk , which is a best
- printing of the first i words from amongst those printings consistent with
- the bird’s answer.
- % optSolk = optSub[i − k], k
- costk = cost[i − k] + (M − k + 1 − ij =i−k+1 l j )3
- end for
- % Having the best, optSolk , for each bird’s answer k, we keep the best of these
- best.
- k min = a k that minimizes costk
- birdAdvice[i] = k min
- % optSol[i] = optSolkmin
- % cost[i] = costkmin
- end for
- optSol = PrintingNeatlyWithAdvice
- return optSol, cost[n]
- end algorithm
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement