跳到正文

题解

P8801 [蓝桥杯 2022 国 B] 最大数字

AveMujica约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年4月1日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 4 分钟
题目
P8801

版本

  1. v1当前

一个自认为更合理的dp递推代码

C++
#include <bits/stdc++.h>
#define debug(a) cout<<#a<<"="<<a<<"\n"
#define EPS 1e-8
#define IOS ios::sync_with_stdio(0),cin.tie(0)
#define all(v) v.begin(),v.end()
using namespace std;
using i64 = long long;
using ull = unsigned long long;
using pi = pair<int,int>;
using pl = pair<long long,long long>;
static constexpr int ALPHABET_SIZE = 26;
static constexpr i64 N = 1000000 + 5;
static constexpr int MOD = 998244353;

i64 ksm(i64 base, i64 exp) {
    i64 res = 1;
    while (exp) {
        if (exp & 1) {
            res *= base;
        }
        base *= base;
        exp >>= 1;
    }
    return res;
}

void solve() {
    // dp[i][j][k]: 前i位还剩下j次加操作和k次减操作的时候,能变成的最大数字
    i64 n, a, b;
    cin >> n >> a >> b;
    vector<i64> p;
    while (n) {
        p.emplace_back(n % 10);
        n /= 10;
    }
    int sz = p.size();
    reverse(all(p));
    vector dp(sz + 1, vector(a + 1, vector<i64>(b + 1, LONG_LONG_MIN)));
    dp[0][a][b] = 0;
    for (int i = 1; i <= sz; i++) {
        // 当前原始位
        i64 cur = p[i - 1];
        for (int np = cur; np <= 9; np++) {
            // a, b
            int plus = np - cur, sub = 10 - np + cur;
            i64 sum = np * ksm(10, sz - i);
            for (int j = 0; j <= a; j++) {
                for (int k = 0; k <= b; k++) {
                    if (j + plus <= a) {
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + plus][k] + sum);
                    }
                    if (k + sub <= b) {
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][k + sub] + sum);
                    }
                }
            }
        }
    }
    i64 res = -1;
    for (int i = 0; i <= a; i++) {
        for (int j = 0; j <= b; j++) {
            res = max(res, dp[sz][i][j]);
        }
    }
    cout << res;
}
int main()
{
    IOS;
    int t = 1;
    // cin >> t;
    while(t--) {
        solve();
    }
    return 0;     
}
原文