Go with the Flow
Time limit12sMemory limit1024 MB
Choose a line width for justified monospaced text, then find the longest run of spaces that drifts by at most one column per line, and report the best width and length.
- Level
Hard8 of 10
- Topics
- Brute force, String, Implementation, Simulation
- Solved
- No attempts yet
Problem
In typesetting, a "river" is a run of spaces formed by the gaps between words that flows down several lines of text. Figure 1 shows several rivers marked in red. The text is blurred on purpose so that the rivers are easier to see.

Figure 1: Examples of rivers in typeset text.
Flo Ng studies rivers, and she wants her new book on the rivers of the world to contain the longest typographic rivers she can get. She sets the text in a monospaced font (all letters and spaces have equal width) in a column of some fixed width aligned on the left, with exactly one space between words on a line. The right edge is not aligned. For Flo, a river is a sequence of spaces taken one per line from consecutive lines, in which the position of each space, except the first, differs by at most 1 from the position of the space chosen in the line above it. Trailing white space cannot appear in a river. Words are packed as tightly as possible on each line, and no word is split across lines. The line width must be at least as long as the longest word in the text. Figure 2 shows the same text set at two different line widths.

Figure 2: Longest rivers (*) for two different line widths.
Given a text, determine the line width that produces the longest river of spaces.
Input
The first line contains an integer (), the number of words in the text. The following lines contain the words of the text. Each word consists only of lowercase and uppercase letters, and words on the same line are separated by a single space. No word is longer than 80 characters.
Output
Print the line width for which the text contains the longest river, followed by the length of that river (the number of spaces it contains), separated by a single space on one line. If more than one line width yields this maximum, print the smallest such line width.