520B. Two Buttons【这题好魔性 greedy 反推】

来源:互联网 发布:洛克人网络争霸战ed 编辑:程序博客网 时间:2024/05/24 01:22
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 numbern.

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


题意:一个数,就是输入的第一个数,让它变成第二个数最少用几步。可以点红色按钮,蓝色按钮来改变数字,红色:*2,蓝色:-1,如果变成负数,就变成原来的数。

思路:当然是*2可以掠过的步数更少啦,如果n是输入,m是输出。

如果n大于m,不能使用红色按钮,很容易看出,步数就是n-m。

如果n比m小,如果m是偶数的话,m/2,如果m是奇数,m+1,这样一直循环判断n是不是还比m小,不符合就跳出循环,进入第一个如果。


贪心的思想:其实如果m比n大 ,n肯定有*2,问题就是先减再乘还是先乘再减。这是正常人的思路。

但是反过来推,如果m是奇数,一定是减一造成的,如果是偶数,更快的办法是*2造成的。就这么寻欢做下去知道遇到m=n。

#include<iostream>#include<cstdio>#include<cstring>#include<ctime>#include<algorithm>#include <map>using namespace std;//520B  substract 减去扣除  我去!!!int n, m, a;int main(){cin >> n >> m;while(n<m)m%2?m++:m/=2, a++;cout << a+n-m;return 0;}


0 0