Codeforces #520B Two buttons

本文介绍了一种算法,用于计算将数字n通过一系列操作转换为另一个数字m所需的最少步骤数。这些操作包括将数字乘以2或减1,且目标是在保持数字始终为正的前提下完成转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【问题描述】

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 number n.

Examples
input
Copy
4 6
output
Copy
2
input
Copy
10 1
output
Copy
9
Note

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只能通过乘2或减1转换成数字m。

如果n>m,则n只能通过减1得到m。

否则,可使用贪心算法。

将n多次乘2直至n>m,然后再通过“减1”进行调整得到m。

但问题在于减1的位置有多种,因为m可能在乘2的过程中进行减1。

所以,我们可以引入三个变量——

(1)mulcounter:乘2计数器,记录乘2的次数;

(2)subcounter:减1计数器,记录减1的次数;

(3)subpos:减1的位置,即表示在第(mulcounter - subpos + 1)次乘2之后进行减1。

在此基础上,解题步骤如下:

(1)多次乘2直至n>m。

(2)subpos初始化为mulcounter。

(3)如果n - m > 2^subpos,那么n就应该在第(mulcounter - subpos + 1)次乘2之后减1,否则subpos减1。当n = m时,循环结束。


【代码实现】

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int m, n; 
    cin >> n >> m;
    int mulcounter = 0;	// 记录乘2次数 
    while(n < m)
    {
        n *= 2;
        mulcounter++;
    }
    int subcounter = 0;	// 记录减1次数
    int subpos = mulcounter; 	// 减1相对于乘2的位置 
    while(true)
    {
	    while(n - m >= pow(2, subpos))
	    {
	        n -= pow(2, subpos);
	        subcounter++;
	    }
	    if(n == m)
	    	break;
	    subpos--;
	}
    cout << mulcounter + subcounter <<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值