ACACACAC

许诺  •  1个月前


#include <iostream>
#include <vector>
#include <string>

using namespace std;

vector convert(const string &s) {

int start = 0;
while (start < s.size() && s[start] == '0') start++;
if (start == s.size()) return {0};
string valid = s.substr(start);
vector<int> res;
for (int i = valid.size() - 1; i >= 0; i--) {
    res.push_back(valid[i] - '0');
}
return res;

}

vector multiply(const vector &a, const vector &b) {

if (a.empty() || b.empty()) return {0};
if ((a.size() == 1 && a[0] == 0) || (b.size() == 1 && b[0] == 0)) return {0};
vector<int> res(a.size() + b.size(), 0);
for (int i = 0; i < a.size(); i++) {
    for (int j = 0; j < b.size(); j++) {
        res[i + j] += a[i] * b[j];
        res[i + j + 1] += res[i + j] / 10;
        res[i + j] %= 10;
    }
}
while (res.size() > 1 && res.back() == 0) res.pop_back();
return res;

}

int compare(const vector &a, const vector &b) {

if (a.size() > b.size()) return 1;
if (a.size() < b.size()) return -1;
for (int i = a.size() - 1; i >= 0; i--) {
    if (a[i] > b[i]) return 1;
    if (a[i] < b[i]) return -1;
}
return 0;

}

int main() {

int n, k;
string s;
cin >> n >> k >> s;
k += 1;
vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(k + 1));

for (int i = 1; i <= n; i++) {
    string sub = s.substr(0, i);
    dp[i][1] = convert(sub);
}

for (int j = 2; j <= k; j++) {
    for (int i = j; i <= n; i++) {
        vector<int> max_val;
        for (int m = j - 1; m < i; m++) {
            string sub = s.substr(m, i - m);
            vector<int> num = convert(sub);
            vector<int> product = multiply(dp[m][j - 1], num);
            if (max_val.empty() || compare(product, max_val) > 0) {
                max_val = product;
            }
        }
        dp[i][j] = max_val;
    }
}

vector<int> result = dp[n][k];
for (int i = result.size() - 1; i >= 0; i--) {
    cout << result[i];
}
cout << endl;
return 0;

}


评论:

请先登录,才能进行评论