洛谷 P1018 乘积最大(NOIp2000提高组第二题)

DP

f[i][j]表示在前i个数字中插入j个乘号时乘积的最大值

//P1018 乘积最大
//2017.5.22

#include 
using namespace std;

int n, k;
string s;
long long f[42][7];

int sub(int x, int y){
    int num = 0;
    for (int ii = 0; ii <= y - x; ii++)
        num = num * 10 + s[x + ii] - '0';
    return num;
}

int main(){
    cin >> n >> k;
    cin >> s;

    for (int i = 0; i < n; i++){
        f[i][0] = sub(0, i);
//      cout << f[i][0] << "  ";
    }
//  cout << endl;

    for (int i = 0; i < n; i++)   //在前i个字串中 
        for (int j = 1; j <= min(k, i); j++)   //插入j个× 
            for (int p = 0; p < i; p++)   //尝试在p的后边加一个× 
                f[i][j] = max(f[i][j], f[p][j - 1] * sub(p + 1, i));

//  for (int i = 0; i < n; i++)
//      for (int j = 0; j <= min(k, i); j++)
//          cout << i << " " << j << " : " << f[i][j] << endl;

    cout << f[n - 1][k];

    return 0;
} 

你可能感兴趣的:(洛谷)