Solution
记字符集为 。
考虑 DP。设 表示后缀 ,最大的字符为 时能拼出的最大的数字。
枚举 ,转移分两种情况。
- 若 ,则这一位可以自由选择 进行转移。
- 否则,这一位只能选择 转移。
设这一位填 ,转移则为 ,其中 表示字符 对应的权值。
然而题目还需要给出方案,简单记录转移的来源即可。
时间复杂度 。空间复杂度 。
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;
}