贪心

                    CF 520B Two Buttons

Description

Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n.

Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?

Input

The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .

Output

Print a single number — the minimum number of times one needs to push the button required to get the number m out of numbern.

Sample Input

Input
4 6
Output
2
Input
10 1
Output
9

Hint

In the first example you need to push the blue button once, and then push the red button once.

In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.


题意:给了两个数n和m;对n有两种操作:乘以2,减1,求n变成m的最小操作次数;

 

解题思路:

         常规思路是如题所述,使n变成m,但是会发现这么做的话是挺复杂的,我们可以逆向思考,让m变成n;这样的话就很容易了,就像我们玩走迷宫游戏一样,从起点到终点很困难,但从终点到起点就简单多了。

当我们要让m变为n时要注意,我们是在操作m,所以和操作n的操作方法是反的:除以2,加1;

首先我们很容易知道n>m时,最小操作次数就是n-m,因为n变为m的操作只有两种:乘以2,减1,显然只能让n一直减1直到n=m;

我们再来考虑n<m,这里就要用到我们的逆向的方法,我们发现,当n<m时,让m变为n,只有让m除以2才能让m接近n,那除不尽时咋办? 当然我们只能加1,然后继续除以2,这是最快的,换句话说,是操作次数最少的办法,记这部分的操作次数为cnt,当m除以2直到n>m时,我们发现这回到了n>m的情况,所以这部分的操作次数为n-m;那么总的操作次数就是cnt+n-m;

代码如下:

 

#include<cstdio>

int main()

{

   int n,m;

   while(~scanf("%d%d",&n,&m)){

       int cnt=0;

       while(n<m){

           if((m&1)==1) m++;

           else m=(m>>1);

           cnt++;

       }

       printf("%d\n",cnt+n-m);

    }

   return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值