题意:给两个数n和m,对n能进行两种操作:将这个数*2,将这个数-1,最后使得这个数可以等于给的另一个数m。问最少需要用多少步。
思路:贪心,转换思维,可以视为让m不断靠近n,首先需要判断n和m的大小,如果n比m大那只能通过n-m步对n进行–操作,这就是这种情况的答案。
如果m>n,那就尽量让n*2靠近m,也就是m/2,当m为偶数的时候就这样操作,奇数则m++,这样操作直到n>=m,再加上此时n-m(即n–)的步骤就是答案。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
int a,b,n;
void solve()
{
n = 0;
if(b < a)
cout << a-b << endl;
else{
while(a < b)
{
if(b%2)
{
b++;
n++;
}
else
{
b/=2;
n++;
}
}
n += abs(a-b);
cout << n << endl;
}
}
int main()
{
#ifdef H_R
freopen("in.txt","r",stdin);
#endif // H_R
ios::sync_with_stdio(false);
cin.tie(false);
while( cin >> a >> b )
{
solve();
}
return 0;
}