codeforces 520B

题目:http://codeforces.com/problemset/problem/520/B

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.

Examples
input
4 6
output
2
input
Copy
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,输入初始数字n和目标数字m,计算最少需要几步使n变成m。

当n>=m时,需要n-m步,

当n<m时,我们可以从m逆推n,因为需要的步数最少,那么肯定乘法的运用相比减法要优先,但如果从n推m,我们很难知道是先减小n还是先做乘法,而m到n的话就可以将m一直缩小到比n小,然后和n比较。

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

猜你喜欢

转载自www.cnblogs.com/chenruijiang/p/8979200.html