Beautiful Layout
Time limit5sMemory limit128 MB
Given word lengths and page width W, determine how to break the words into justified rows so that the maximum consecutive blank run is minimized, and output that minimum value.
- Level
Medium7 of 10
- Topics
- Binary search, Greedy, Dynamic programming
- Solved
- No attempts yet
Problem
A text is made up of words, and each word is made up of letters. You want to write the text onto manuscript paper that has columns per row. The number of rows is unlimited.
When writing the text, the following rules are always obeyed.
- The order of the words must not be changed.
- On the same row, there must be at least one blank cell between two neighboring words.
- A word occupies as many consecutive cells as it has letters. A word cannot be split across two rows, and no blank cell may appear inside a word.
- The text must be justified against both the left and right edges. That is, the first word of every row starts in the first column, and the last word of every row except the last row must end in column .
The smaller the longest run of consecutive blank cells in a placement, the nicer the text looks. A placement that makes the longest run of consecutive blank cells as small as possible is called a beautiful layout. Blank cells left after the last word of the final row are not counted.
For example, four words of lengths (such as "This is a pen") written onto -column paper according to the rules can be arranged so that the longest run of consecutive blank cells is as small as . In contrast, another rule-obeying arrangement of the same four words can have a longest blank run of , which is not beautiful.
Given the length of each word and the number of columns , write a program that finds the longest run of consecutive blank cells in a beautiful layout.
Input
The input consists of several test cases.
The first line of each test case contains two integers and , where is the number of columns of the manuscript paper and is the number of words. (, )
The second line contains integers , where is the length of the -th word. ()
It is guaranteed that a placement satisfying the rules always exists.
The last line of the input contains two zeros; this line is not processed.
Output
For each test case, print the longest run of consecutive blank cells in a beautiful layout, one value per line.