【打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条边。

posted @ 2017-06-03 09:38  yxysuanfa  阅读(188)  评论(0编辑  收藏  举报