zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    mac的端口被占用
    php中的运算符、控制结构
    文档模式影响浏览器的渲染
    ubuntu 命令 tips 来自于 ubuntu中文论坛
    用好 Emacs 中的 register
    [转载] Rsync命令参数详解
    使用 python 遍历目录下的文件
    灵活的左移位( << )操作
    使用 iperf 测试两台机器间的最大带宽
    Emacs server 新启动方式 (仅在emacs daemon未启动时才启动daemon)
  • 原文地址:https://www.cnblogs.com/chenruijiang/p/8979200.html
Copyright © 2011-2022 走看看