B. Two Buttons

https://codeforces.com/problemset/problem/520/B

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.ExamplesinputCopy

4 6

outputCopy

2

inputCopy

10 1

outputCopy

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*2和m的关系,对于前面的和后面的用不等式找到了一定的关系,然后去做。但是这么做是不全面的。因为不一定n*2<m的时候先*2就是最优的。然后一直wa

//int main(void)
//{
//  cin.tie(0);std::ios::sync_with_stdio(false);
//  LL x,y;
//  cin>>x>>y;
//  LL sum=0;
//  if(x>y) cout<<x-y<<endl;
//  else
//  {
//	  while(x*2<y) x*=2,sum++;
//	  if(x*2==y) cout<<sum+1<<endl;
//	  else if(y%2==1)
//	  {
//	  	 sum+=1;
//	  	// sum+=x-(y+1)/2;
//	  	 sum+=x-(y+1)/2+(y+1)/2*2-y;
//	  	 cout<<sum<<endl;
//	  }
//	  else if(y%2==0)
//	  {
//	  	sum+=1;
//	  	sum+=x-(y+1)/2;
//	  	cout<<sum<<endl;
//	  }
//  }	
//return 0;
//}

正确思路:反向思考。那么对m来说只有+1和m/2的操作。

如果n>m,那么只有+1的操作

那么剩下的是n<m的情况了。具体来说是 n<m<2*n的情况。

如果m为奇数,那么肯定是+1的(不能整除而且正向思考的时候是*2乘不到的,只能靠最后的-1取到0

那么剩下m的偶数,有两种走法。m到2*n再/2,或者m/2再加到n。对这两个进行加减。 2n-m+1-( n-m/2+1 )== n-m/2 。

又因2n > m > n ,所以 n > m/2 > n/2,则 n-m/2 > 0 

所以第二种先/2更优。

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e5;
typedef long long LL;
int main(void)
{
	LL n,m;cin>>n>>m;
	if(n>=m) cout<<n-m<<endl;
	else//m>n的情况 
	{
		LL sum=0;
		while(n!=m)  
		{
			if(m<n) m++;//先判此时m是否<n,不然除没有意义,越除越小 
			else if(m%2==1) m++;
			else if(m%2==0) m/=2;	
	//		else if(m<n) m++;
			sum++;
		}
		cout<<sum<<endl;
	} 
return 0;	
}
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页