Problem 331
Text Justification
Hard · 30 pts · String, Greedy, Simulation
Problem
Format a list of words into lines of exactly W characters, fully justified. Pack words greedily: put as many words on each line as fit with at least one space between them. Then pad every line except the last with extra spaces between the words so it is exactly W characters long. Spread the spaces as evenly as possible; if they do not divide evenly, the gaps on the left get one more space than the gaps on the right. A line with a single word is left-justified. The last line is left-justified with single spaces between words. Do not print trailing spaces on any line.
Input
First line: N and W. Second line: the N words.
Output
Print the justified lines, one per line.
Constraints
1 <= N <= 300; 1 <= word length <= W <= 100
Example input
7 16 This is an example of text justification.
Example output
This is an example of text justification.
Explanation
With W = 16, the first line holds 'This', 'is' and 'an' (8 letters), so 8 spaces are shared by 2 gaps: 'This is an'. The last line 'justification.' is left-justified.