【打CF,学算法——二星级】CF 520B Two Buttons

【CF简介】

提交链接:Two Buttons


题面:


B. Two Buttons
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Sample test(s)
input
4 6
output
2
input
10 1
output
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>=m,直接输出n-m。当n<m时,m若为偶数除2,m为奇数+1除以2,一直分解m到1,并记录这个过程中m分解的过程。然后将n减到最近的m分解过程中的m上。感觉很不靠谱,纯瞎想,结果别人敲了一下说是对的。不过没必要这么复杂,循环 m是偶数  除以2 计数值+1 ;m是奇数 加一除以2  计数值+2  直到m<n 。 最后计数值加上n-m就好了 虽然不知道为什么这样就对,但是感觉是让减法尽量早减,这样就可以减少减法的次数。


代码:

#include <iostream>
using namespace std;
int main()
{
	int n,m,cnt=0,t,ans=0,last;
	cin>>n>>m;
	if(n>=m)cout<<n-m<<endl;
	else
	{
		while(m>n)
		{
			if(m%2==0)
			{
				ans++;
				m/=2; 
			}
			else
			{
				m=(m+1)/2;
				ans+=2;
			}
		}
		ans+=(n-m);
		cout<<ans<<endl;
	}
	return 0;
}


法二:

看了一篇题解,说是spfa爆搜,顿时给跪了。感觉好奇怪,我也没看具体题解,想了一下,是不是建一张图,10000个数,减法由x到x-1建立一条权值为1的边,乘法由n到2*n建立一条权值为1的边,最后只要搜索n到m的最短路就好了。这是我自己的想法,感觉很巧妙,但是不会超复杂度吗?然而边不是矩阵存储的,因为10000个数,最多不会超过20000条边。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值