cdoj第13th校赛初赛F - Fabricate equation

http://acm.uestc.edu.cn/#/contest/show/54

 

F - Fabricate equation

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

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

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

Input

Only one integer Y(0Y1018).

Output

The minimal K.

Sample input and output

Sample InputSample Output
1
1
191
2

 

 

思路:贪心。倒着扫描,遇到0就忽略,因为对应被减数的该位也设0就好;遇到9,这个特殊,因为比如290-191=99,后面进位后,9这个位也可以使得被减数与结果的该位相同,这样的情况需要两个条件:必须后面可以进位。假如减数那位为0,不论结果为什么,都无法产生进位。第二个条件是,被减数的前一位可以借位,也就是说9这种情况完成后,即便前面遇到减数那位为0,也不能再忽略,只能当一般情况处理。一般情况自然就是k++。

官方题解:

代码:

 1 #include <fstream>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cstdio>
 5 #include <cstring>
 6 #include <cmath>
 7 #include <cstdlib>
 8 #include <vector>
 9 
10 using namespace std;
11 
12 #define PI acos(-1.0)
13 #define EPS 1e-10
14 #define lll __int64
15 #define ll long long
16 #define INF 0x7fffffff
17 
18 char c[25];
19 
20 int main(){
21     //freopen("D:\\input.in","r",stdin);
22     //freopen("D:\\output.out","w",stdout);
23     scanf("%s",c+1);
24     int l=strlen(c+1),k=0;
25     c[l+1]='0';c[0]='0';
26     for(int i=l;i>0;i--){
27         if(c[i]=='0')   continue;
28         if(c[i]=='9'){
29             if(c[i+1]=='0'){
30                 k++;
31                 continue;
32             }else{
33                 if(c[i-1]=='0') c[i-1]++;//把前面的0毁掉
34                 continue;
35             }
36         }else{
37             k++;
38         }
39     }
40     if(c[0]!='0')   k++;
41     printf("%d\n",k);
42     return 0;
43 }
View Code

 

posted @ 2015-03-30 23:42  jiu~  阅读(395)  评论(0编辑  收藏  举报