Fabricate equation(dfs + 模拟)

Fabricate equation

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

Given an integer YY, you need to find the minimal integer KK so that there exists a XX satisfying XY=Z(Z0)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 101≠0 and 090≠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(0Y1018).Y(0≤Y≤1018).

Output

The minimal KK.

Sample input and output

Sample InputSample Output
1
1
191
 

题解:

XY=Z(Z0),已知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[25];
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] == 0){
        if(kg != 9 && !(cur == tp - 2 && a[tp - 1] == 9))dfs(cur + 1, cnt + 1, tp, 0);
        else dfs(cur + 1, cnt, tp, 1);
    }
    else if(a[cur] == 9){
        if((kg == 1 || kg == 9) && cur != tp - 1 && cur != 0)
            dfs(cur + 1, cnt + 1, tp, 9);
        else
            dfs(cur + 1, cnt, tp, 1);
    }
    else
        dfs(cur + 1, cnt, tp, 1);
}
int main(){
    LL Y;
    while(~scanf("%lld", &Y)){
        int tp = 0;
        while(Y){
            a[tp++] = Y % 10;
            Y /= 10;
        }
        ans = 0;
        dfs(0, 0, tp, 1);
        printf("%d\n", tp - ans);
    }
    return 0;
}

 

posted @ 2016-05-08 14:52  handsomecui  阅读(203)  评论(0编辑  收藏  举报