Question:
Thoughts:
Definition
(1) Extra indicates the number of extra space characters at the end of the line.CubeAnd
(2) f [I, j] = m-J + I-sum (lk), I <= k <= J
(3) Len [I, j] indicates the minimum extra that can be obtained from the ith word to the J word.
Neat printing can be broken down into the following sub-problems:
(1) if F [I, j] <0, then Len [I, j] = min (LEN [I, K] + Len [k + 1, j]), I <= k <j
(2) if F [I, j]> 0 & J = N, Len [I, j] = 0
(3) If I = J, Len [I, j] = (F [I, j]) ^ 3
Code: For programming convenience,ProgramSlightly different from the description
# Include <iostream> # include <cmath> using namespace STD; # define M 10 // maximum length of a row # define N 10 // Number of words int s [N] [N]; void dp (int * Len) {int I, j, K, step, temp; For (step = 0; Step <n; Step ++) {for (I = 0; I <n; I ++) {temp = 0; j = I + step; If (j> = N) break; // calculate Len [I, j] For (k = I; k <= J; k ++) {If (K! = I) temp ++; temp = temp + Len [k]; If (temp> m) break;} If (temp> m) s [I] [J] = 0x7fffff; // if f [I, j]> 0 & J = N, then Len [I, j] = 0 else if (j = N-1) s [I] [J] = 0; // If I = J, then Len [I, j] = (F [I, j]) ^ 3 else s [I] [J] = POW (M * 1.0-temp, 3); // if f [I, j] <0, then Len [I, j] = min (LEN [I, K] + Len [k + 1, J]), I <= k <JFOR (k = I; k <j; k ++) if (s [I] [k] + s [k + 1] [J] <s [I] [J]) s [I] [J] = s [I] [k] + s [k + 1] [J];} cout <s [0] [N-1] <Endl;} void print () {int I, j; for (I = 0; I <n; I ++) {for (j = 0; j <n; j ++) cout <s [I] [J] <''; cout <Endl ;}} /* 1 2 3 1 2 3 1 2 3 1 */INT main () {int Len [N], I; // output data for (I = 0; I <n; I ++) CIN> Len [I]; DP (LEN); // print (); Return 0 ;}