最大數字
問題描述
給定一個正整數?NN?。你可以對?NN?的任意一位數字執行任意次以下 2 種操 作:
將該位數字加 1 。如果該位數字已經是 9 , 加 1 之后變成 0 。
將該位數字減 1 。如果該位數字已經是 0 , 減 1 之后變成 9 。
你現在總共可以執行 1 號操作不超過?AA?次, 2 號操作不超過?BB?次。 請問你最大可以將?NN?變成多少?
輸入格式
第一行包含 3 個整數:?N,A,BN,A,B?。
輸出格式
一個整數代表答案。
dfs流程
void dfs(int u) //u表示到第幾位 {if() {return;} //邊界st[i] = 1; // 改變條件dfs(u + 1); //下一步st[i] = 0; // 恢復現場}
代碼(通過率40%)
#include <bits/stdc++.h>
using namespace std;#define int long long
string n;
int a, b;
int l,mx,res;void dfs(int u)
{if(u == l) {mx = max(mx, res);cout << mx;return;}int t = n[u];int x = min(9-t, a);a-=x;res = res*10 + t + x; dfs(u+1);a+=x;if(b > t) {b-=(t+1);res = res*10 + 9;dfs(u+1);b+=t+1;}
}signed main()
{// 請在此輸入您的代碼cin >> n >> a >> b;l = n.size(); dfs(0); return 0;
}
ac代碼
#include <iostream>
#include <cmath>
using namespace std;
string n;
long long ans;
int a,b;
void dfs(int x,long long an){ //a代表每次遍歷的數 int t=n[x]-'0'; //位數轉為intif(n[x]){ //防止為空 int c=min(a,9-t);a-=c;dfs(x+1,an*10+t+c);a+=c;if(b>t){b=b-t-1;dfs(x+1,an*10+9);b=b+t+1;}}else{ans=max(ans,an);}
}
int main(){cin>>n>>a>>b;dfs(0,0); //0號字符 cout<<ans;return 0;
}