Job 2412 divide the finger

Source: Internet
Author: User

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]);
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.