Heng_Xin 题解分享 · 2024/5/23
最大数字(编程题) - 题解
贪心, 就是看看各种条件下下誰可以最大, 注意当(n[i] == '4' && x >= 4 && y >= 4)情况下, 两种都可以选择, 因此都要试一下(n <= 17) 所以直接dfs就可以了 ```cpp #include <iostream> #include <string> #include <functional> using namespace std; int main() { string n, tmp, res; int a, b; cin >> n >> a >> b; res = tmp = n; // 操作第 i 位数, 剩下 1 操作 a 次, 2 操作 b 次 function<void(int, int, int)> dfs = [&](int i, int x, int y) { if (i >= n.size()) { res = max(res, tmp); return; } if (n[i] == '4' && x >= 4 && y >= 4) { tmp[i] = '9'; dfs(i + 1, x - 4, y); dfs(i + 1, x, y - 4); } else if ('9' - n[i] <= x && n[i] > '4' || n[i] < '4' && n[i] - '0' > y) { // 操作 1 if ('9' - n[i] <= x) { x -= '9' - n[i]; tmp[i] = '9'; } else { tmp[i] += x; x= 0; } dfs(i + 1, x, y); } else if (tmp[i] - '0' <= y) { // 操作2 y -= tmp[i] - '0'; tmp[i] = '9'; dfs(i + 1, x, y); } else { // 做不了 dfs(i + 1, x, y); } }; dfs(0, a, b); cout << res; return 0; } ```
查看全文
3 0 1 2