Fabricate equation(dfs + 模拟)

时间:2023-03-09 14:11:33
Fabricate equation(dfs + 模拟)

Fabricate equation

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
Submit Status

Given an integer YY, you need to find the minimal integer KK so that there exists a XX satisfying X−Y=Z(Z≥0)X−Y=Z(Z≥0) and the number of different digit between XX and ZZis KK under decimal system.

For example: Y=1Y=1, you can find a X=100X=100 so that Z=99Z=99 and KK is 33 due to 1≠01≠0 and 0≠90≠9. But for minimization, we should let X=1X=1 so that Z=0Z=0 and KK can just be 11.

Input

Only one integer Y(0≤Y≤1018).Y(0≤Y≤1018).

Output

The minimal KK.

Sample input and output

Sample Input Sample Output
1
1
191
 

题解:

X−Y=Z(Z≥0),已知Y,求最小K,K定义为Z与X不相同的位置的个数;例如280 - 191 = 89;

X - Z = Y;

根据减法运算我们可以想到Xi - Zi = Yi; 如果数字相同我们可以得到 Xi = Zi;

即 Xi - Xi = Yi; 所以Yi 为0的位置肯定能找到满足的;再者有可能进位,即:10 +Xi -Xi -1 = 9;

所以9也能得到,但是这两者相互影响,取09相邻只能取一个,还有特殊情况9在最后一位,最高的退位,90000对0的影响。。。考虑清就好了;

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
int a[];
int ans;
void dfs(int cur, int cnt, int tp, int kg){
// printf("%d %d\n", cur, tp);
if(cur >= tp){
ans = max(ans, cnt);
return;
}
if(a[cur] == ){
if(kg != && !(cur == tp - && a[tp - ] == ))dfs(cur + , cnt + , tp, );
else dfs(cur + , cnt, tp, );
}
else if(a[cur] == ){
if((kg == || kg == ) && cur != tp - && cur != )
dfs(cur + , cnt + , tp, );
else
dfs(cur + , cnt, tp, );
}
else
dfs(cur + , cnt, tp, );
}
int main(){
LL Y;
while(~scanf("%lld", &Y)){
int tp = ;
while(Y){
a[tp++] = Y % ;
Y /= ;
}
ans = ;
dfs(, , tp, );
printf("%d\n", tp - ans);
}
return ;
}