Raggedy, Raggedy
Time limit1sMemory limit128 MB
Given word widths and a max line length, split the words into lines and minimize the sum of squared unused space on every line except the last.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Prefix sum, Implementation, Math
- Solved
- No attempts yet
Problem
Consider the problem of laying out text in lines of a fixed maximum width (also known as line filling).
If you do a poor job, the ends of the lines are unnecessarily ragged. By convention, we allow the last line of a paragraph to be arbitrarily ragged — it may contain just a few characters — but we expect the earlier lines to be of approximately uniform length, filling up the column in which the text is set.
The straightforward approach of greedily filling each line with as many words as fit and then moving on does not always give the most pleasing result. For instance, at the words See if we care. could be laid out as
See if
we
care.
which is arguably less pleasing than
See
if we
care.
Define a word as any sequence of non-whitespace characters bounded by a line start or end or by a blank. The whitespace characters are blanks and line-terminator characters.
Given words of widths and a maximum line width (with for every ), define as the width of the line containing words through inclusive: the sum of their widths plus one blank between each adjacent pair.
The raggedness of a line containing words through is
Lay out each paragraph so that no line exceeds characters and the total raggedness, summed over every line except the last line of the paragraph, is minimized. (The final line of a paragraph may be arbitrarily shorter than the lines above it.) Line-terminator characters are not counted as part of a line's width.
Input
The input consists of one or more datasets.
Each dataset begins with a line containing a single integer , the maximum line width (not counting line-terminator characters), with . A value of indicates the end of the input.
The rest of the dataset is a paragraph of text on up to lines, terminated by an empty line. A paragraph contains from to words, where a word is any consecutive run of non-whitespace characters. No word is longer than characters.
Output
For each paragraph, print a single line containing the minimum achievable total raggedness — the smallest possible value of taken over every line except the last, across all valid layouts in which no line exceeds characters. After each paragraph, print a line containing === (three equal signs).
Word widths are measured in characters.