TAG
- 芝士水题、算法 − 【算法 − D F S 、贪心】 芝士水题、算法 - 【算法 - DFS、贪心】 芝士水题、算法−【算法−DFS、贪心】时间复杂度
- O ( ∗ ) O(\ast) O(∗)
//
#include <bits/stdc++.h>
using namespace std;
#define int long long
string s;
int cntA, cntB, ans;
void dfs(int idx, int sum) {
if (idx >= s.size()) {
ans = max(ans, sum);
return ;
}
int tt = s[idx] - '0';
int needA = min(9 - tt, cntA);
int needB = tt + 1;
if (cntA >= needA) {
cntA -= needA;
dfs(idx + 1, sum * 10 + tt + needA);
cntA += needA;
}
if (cntB >= needB) {
cntB -= needB;
dfs(idx + 1, sum * 10 + 9);
cntB += needB;
}
// dfs(idx + 1, sum * 10 + tt); // 要用就用在位置靠前的(贪心)
}
void solve() {
cin >> s >> cntA >> cntB;
dfs(0, 0);
cout << ans << endl;
}
signed main() {
int t = 1;
// scanf("%lld", &t);
while (t--) solve();
return 0;
}
实现细节
- `
参考示意图
-
`
参考链接
- `
作者 | 乐意奥AI