Word wrapping P59168


Statement
 

pdf   zip

Word wrapping is breaking a text into lines so that they fit into the width ww of a page. For simplicity, suppose that the text has only nn words [t0,,tn1][t_0, \dots, t_{n-1}] without punctuation marks. If we decide to include the words [ti,,tj][t_i, \dots, t_j] separated with spaces in the kk-th line, and the sum of lengths of those words is \ell, then we will use +ji\ell + j - i characters. Hence, we will have exactly sk=wj+is_k = w - \ell - j + i unused spaces at the end of the kk-th line.

Let us fix an integer constant c1c \ge 1. We can define the uglyness of each line kk as uk=(sk)cu_k = (s_k)^c. A way of choosing where to break the lines is to minimize the resulting kuk\sum_k u_k, where the sum is over the indices kk of all lines except the last one (we do not care if it has unused space).

Given a text, can you wrap it according to this method?

Input

Input consists of several cases, each one with ww, cc and nn, followed by nn words made up of between 1 and ww lowercase letters. You can assume 1w801 \le w \le 80, 1c21 \le c \le 2, and 1n1041 \le n \le 10^4.

Output

For every case, print the result of wrapping the text according to the method above. If there are several solutions with minimum total uglyness, choose the one that maximizes the number of words of the first line; in case of a tie, maximize the number of words of the second line, and so on. Print a line with ww dashes at the end of each case.

Public test cases
  • Input

    6 1 4
    aaa bb cc ddddd
    
    6 2 4
    aaa bb cc ddddd
    
    6 2 4
    aa bbb cc ddddd
    
    10 2 3
    xxxxx yyyy z
    
    2 1 2
    a a
    
    3 1 2
    a a
    

    Output

    aaa bb
    cc
    ddddd
    ------
    aaa
    bb cc
    ddddd
    ------
    aa bbb
    cc
    ddddd
    ------
    xxxxx yyyy
    z
    ----------
    a
    a
    --
    a a
    ---
    
  • Information
    Author
    Salvador Roura
    Language
    English
    Official solutions
    C++
    User solutions
    C++