题解:P1018 [NOIP 2000 提高组] 乘积最大
问题分析
给定一个长度为 的数字串,用 个乘号将其成 部分,求各部分乘积的最大值。
数字可能很大(长度可达 ),直接使用整数类型会溢出,需用字符串处理大数运算(乘法和比较)。
动态规划思路
- 状态定义: 表示前 个数字用 个乘号分割时的最大乘积(字符串表示)。
- 初始条件: 为前 个数字的子串(无乘号,即单一数字串)。
- 状态转移: 对于每个乘号数 ,枚举最后一个乘号的位置 (前 个数字用 个乘号,剩余 到 为一个部分),计算两部分乘积并更新最大值:
- 预处理: 存储从第 到第 个字符的子串,方便快速获取。
大数运算实现
- 乘法(multiply):模拟竖式乘法,处理每一位的乘积和进位,返回结果字符串。
- 比较(is_greater):先比较长度(长的数更大),长度相同则按字典序比较。
:
#include <bits/stdc++.h>
#define int long long
using namespace std;
bool pd(const string &a,const string &b){// 判断字符串 a 是否大于 b
if (a.size() > b.size()) return true;
if (a.size()<b.size()) return false;
return a > b;
}
string mul(const string &a,const string &b){//高精度
int lenA=a.size(),lenB=b.size();
vector<int> res(lenA+lenB,0);
for (int i=lenA-1;i >= 0;--i){
for (int j=lenB-1;j >= 0;--j){
res[i+j+1]+= (a[i]-'0') * (b[j]-'0');
res[i+j]+= res[i+j+1] / 10;
res[i+j+1] %= 10;
}
}
int i=0;
while (i<res.size() && res[i]==0) i++;
if (i==res.size()) return "0";
string result;
while (i<res.size()){
result+= to_string(res[i]);
i++;
}
return result;
}
signed main(){
int n,k;
string s;
cin >> n >> k >> s;
vector<vector<string>> subStr(n+2,vector<string>(n+2,""));
for (int i=1;i <= n;++i){
for (int j=i;j <= n;++j){
subStr[i][j]=s.substr(i-1,j-i+1);
}
}
vector<vector<string>> dp(n+2,vector<string>(k+2,""));
for (int i=1;i <= n;++i){
dp[i][0]=subStr[1][i];
}
for (int j=1;j <= k;++j){
for (int i=j+1;i <= n;++i){
for (int m=j;m<i;++m){
string prod=mul(dp[m][j-1],subStr[m+1][i]);
if (dp[i][j].empty() || pd(prod,dp[i][j])){
dp[i][j]=prod;
}
}
}
}
cout << dp[n][k] << endl;
return 0;
}