Document Indexing
Time limit2sMemory limit128 MB
Paginate a document by line-count and paragraph rules, then print each word in uppercase with its pages, collapsing runs of three or more consecutive pages into ranges.
- Level
Medium6 of 10
- Topics
- Simulation, Implementation, Hash map, Sorting
- Solved
- No attempts yet
Problem
You are building a text editor for a text-mode operating system, and its hardest component is document indexing. An index of a document is the lexicographically ordered list of every word that occurs in the document, each followed by the page numbers on which it appears.
A document is a sequence of paragraphs. Each paragraph is one or more lines, and consecutive paragraphs are separated by exactly one blank line.
The document is first paginated — split into pages. Each page holds up to lines. Lines are placed on the current page one after another until lines have been placed, and then the following correction rules are applied:
- If the last line on a page is the last line of its paragraph, the blank line that follows it is skipped and is placed on no page. As a result, a page never begins with a blank line.
- If the last line on a page is the first line of a paragraph that has more than one line (an orphan line), that line is moved to the next page.
- If the last line on a page is the next-to-last line of a paragraph that has more than three lines, that line is moved to the next page; otherwise the paragraph's last line would be left alone on a page (a widow line).
- If the last line on a page is the next-to-last line of a paragraph that has exactly two or three lines, the whole paragraph is moved to the next page, so that neither an orphan nor a widow line remains.
After the corrections are applied, the next page is formed, and so on until the whole document has been paginated.
A word is a maximal run of English letters; case is ignored. For every word the index lists, in ascending order and separated by commas, the pages on which it occurs. When a word occurs on three or more consecutive pages, that range is written as its first and last page numbers joined by a dash, for example 3-5,7-10,12,13,15.
Input
The first line contains the integer (). The remaining lines are the document to be indexed; the total input size does not exceed 20,000 bytes.
A line is blank only if it is completely empty. No line has leading or trailing spaces, the document never contains two consecutive blank lines, its first line is not blank, and every line is at most 200 characters long.
Output
Print every word that occurs in the document, one per line, in lexicographical order. After each word print a single space followed by the list of pages on which it occurs, formatted as described above. Print all words in uppercase letters.