csu 1958: 数字游戏

1958: 数字游戏

        Time Limit: 2 Sec     Memory Limit: 128 Mb     Submitted: 134     Solved: 19    


Description

小明今年才上一年级,加减法只会算加一和减一。老师就是喜欢看小明写不出题目的样子,所以给小明出了个难题:给出两个数字x,y,每次可以让数字的某一位加一或者减一(0减1变成9,9加1变成0)。问从x变到y至少要几次操作?小明虽然数学不好但是编程很强呀,他很快就得出了正确答案,现在看你的了~
注意:每次变换只能变动除前导零的数位。例如1109变成0109后不能变再成1109或者9109,但是单就一个数字0可以变成1或9。

Input

第一行是一个数字T(T<=10)表示数据组数
接下来T行,每行两个数字x,y(0<=x,y<=100000)
x和y不包含前导零

Output

输出包括T行,第i行对应第i组数据的答案.
如果x无法变成y,输出-1

Sample Input

3
10 11
99 100
52 75

Sample Output

1
-1
5

Hint

Source

2017年6月月赛-暨中南大学暑期集训选拔赛第二场

Author

卢铭威

题解:这个题目我是没有想明白  为什么要2sec   0ms的事情

先比较一下这个 数字的长度    判断前一个数字可不可以转变成第二个   如果可以的话

从最后一位可以变   一个循环遍历所有位就可以了   数据最大才6位数

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<math.h>
 4 #include<algorithm>
 5 #include<stdlib.h>
 6 using namespace std;
 7 int main()
 8 {
 9     int n,x,y,num1,num2,ans;
10     scanf("%d",&n);
11     while(n--)
12     {
13         ans=0;
14         scanf("%d%d",&x,&y);
15         int temp1=x,temp2=y;
16         num1=num2=0;
17         while(temp1>0)
18         {
19             temp1/=10;
20             num1++;
21         }
22         while(temp2>0)
23         {
24             temp2/=10;
25             num2++;
26         }
27         if(num1<num2)
28         {
29             printf("-1
");
30             continue;
31         }
32         for(int i=0;i<num1;++i)
33         {
34             temp1=x%10;
35             temp2=y%10;
36             int h=abs(temp1-temp2);
37             ans+=min(h,10-h);
38             x/=10;
39             y/=10;
40         }
41         printf("%d
",ans);
42     }
43     return 0;
44 }
原文地址:https://www.cnblogs.com/52why/p/7461443.html