• Codeforces 520B Two Buttons (DFS+模拟)


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

    两种解法:

    1.DFS(深度优先搜索)

    #include<iostream>
    #include<cstring>
    using namespace std;
    int dp[20005],m;
    bool vis[20005];
    int dfs(int n)
    {
        if(n<=0)
            return 99999999;
        if(n>=m)
            return dp[n]=n-m;
        if(vis[n])
            return dp[n];
        vis[n]=true;
        return dp[n]=min(dfs(n-1),dfs(2*n))+1;
    }
    int main()
    {
        int n;
        while(cin>>n>>m)
        {
            memset(dp,0x3f3f3f3f,sizeof(dp));
            memset(vis,false,sizeof(vis));
            cout<<dfs(n)<<endl;
        }
        return 0;
    }

    2.

    #include<iostream>
    using namespace std;
    int main()
    {
        int n,m;
        while(cin>>n>>m)
        {
            int t=0;
            if(n>m)
            {
                cout<<n-m<<endl;
            }
            else
            {
                if(m%2)
                {
                    t++;
                    m++;
                }
                while(n<m)
                {
                    if(m%2)
                    {
                        t++;
                        m++;
                    }
                    m/=2;
                    t++;
                }
                cout<<t+n-m<<endl;
            }
        }
        return 0;
    }
  • 相关阅读:
    数组
    css动画
    mui 常用手势
    ejs 用到的语法
    css 高度塌陷
    SQL 用到的操作符
    position: relative;导致页面卡顿
    h5 图片生成
    li之间的间隙问题
    虚拟机扩容mac
  • 原文地址:https://www.cnblogs.com/orion7/p/7246139.html
Copyright © 2020-2023  润新知