题解:P11092 [ROI 2021] 莫斯科数字 (Day 2)

· · 题解

Solution

记字符集为 \alpha。

考虑 DP。设 f_{i, c} 表示后缀 i \sim n,最大的字符为 c 时能拼出的最大的数字。

枚举 j \in \alpha,转移分两种情况。

设这一位填 c,转移则为 f_{i, \max\{c, j\}} \gets \max\{f_{i, \max\{c, j\}}, f_{i + 1, j} + (-1)^{[c < j]}w_c\},其中 w_c 表示字符 c 对应的权值。

然而题目还需要给出方案,简单记录转移的来源即可。

时间复杂度 \Theta(n|\alpha|^2)。空间复杂度 \Theta(n|\alpha|)。

Code

注意初始值。

#include <algorithm>
#include <cstring>
#include <iostream>
#define MAXN 300003
#define LMX 0x3f3f3f3f3f3f3f3fLL
using namespace std;

struct Node
{
    long long val;
    int cur, pre;
    bool operator<(const Node &other) const
    {
        return val < other.val;
    }
};

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    static char str[MAXN];
    static Node dp[MAXN][26];
    static constexpr long long wmp[26] = {
        1,
        5,
        10,
        50,
        100,
        500,
        1000,
        5000,
        10000,
        50000,
        100000,
        500000,
        1000000,
        5000000,
        10000000,
        50000000,
        100000000,
        500000000,
        1000000000,
        5000000000,
        10000000000,
        50000000000,
        100000000000,
        500000000000,
        1000000000000,
        5000000000000,
    };
    int t, n;
    Node cur;
    cin >> t;
    while (t--)
    {
        cin >> str, n = (int)strlen(str);
        fill(dp[n], dp[n] + 26, Node{0, 0, 0});
        for (int i = n - 1, u; i >= 0; --i)
        {
            fill(dp[i], dp[i] + 26, Node{-LMX, 0, 0});
            if (str[i] != '?')
            {
                u = str[i] - 'A';
                for (int j = 0; j < 26; ++j)
                    dp[i][max(u, j)] = max(dp[i][max(u, j)], {dp[i + 1][j].val + (u >= j ? wmp[u] : -wmp[u]), u, j});
            }
            else
            {
                for (u = 0; u < 26; ++u)
                    for (int j = 0; j < 26; ++j)
                        dp[i][max(u, j)] = max(dp[i][max(u, j)], {dp[i + 1][j].val + (u >= j ? wmp[u] : -wmp[u]), u, j});
            }
        }
        cur = *max_element(dp[0], dp[0] + 26);
        cout << cur.val << '\n';
        for (int i = 0; i < n; ++i)
        {
            cout << (char)(cur.cur + 'A');
            cur = dp[i + 1][cur.pre];
        }
        cout << '\n';
    }
    return 0;
}