Question: divide a number no more than 16 digits into M portions and obtain the maximum product. Example: Split 12345 into two parts: 1234 | 5, 123 | 45...... But the maximum value is 1234*5 = 6170
Idea: Dynamic Planning. f (I, j, T) indicates the maximum I-to-J digits and splits them into the T-part. Equation: f (I, j, t) = max {f (I, k, 1) * F (k + 1, J, t-1)}, K = I .. (J-t + 1 );
That is, the maximum product of T, is equal to the maximum value of 1 to the left and the maximum of the remaining t-1. ----- Principle of optimization. Decision K divides the problem into two subproblems
Code:
Code
# Include < Cstdio >
# Include < Cstring >
Using Namespace STD;
Int N, m;
Char Num [ 20 ];
Long Long DP [ 20 ] [ 20 ] [ 20 ];
Long Long Str_int ( Int I, Int J ){ // I <= J
Long Long B, S;
B = 1 ;
S = 0 ;
For ( Int K = J; k > = I; -- K ){
S + = (Num [k] - ' 0 ' ) * B;
B * = 10 ;
}
Return S;
}
Void Process (){
Int I, j, T, K;
Long Long Max, TMP;
For (I = 1 ; I <= N; ++ I)
For (J = I; j <= N; ++ J)
DP [I] [J] [ 1 ] = Str_int (I, j );
For (T = 2 ; T <= M; ++ T) // Into TB
For (I = 1 ; I <= N; ++ I)
For (J = I + T - 1 ; J <= N; ++ J ){
Max = 0 ;
For (K = I; j - K + 1 > = T; ++ K ){
TMP = DP [I] [k] [ 1 ] * DP [K + 1 ] [J] [t - 1 ];
If (TMP > Max)
Max = TMP;
}
DP [I] [J] [T] = Max;
}
}
Int Main (){
// Freopen ("in", "r", stdin );
While (Scanf ( " % S % d " , & Num [ 1 ], & M) ! = EOF ){
N = Strlen ( & Num [ 1 ]);
Process ();
Printf ( " % LLD \ n " , DP [ 1 ] [N] [m]);
}
}