zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    验证码处理函数
    Apache2.2下载及安装
    centos6.4、6.5、7.0环境下载及安装
    数据库实务 实务隔离级别
    InnoDB 锁
    索引常见问题处理
    数据库索引 B-Tree索引 hash索引
    JVM学习-(2)
    jvm学习-(1)
    linux杂记
  • 原文地址:https://www.cnblogs.com/orion7/p/7246139.html
Copyright © 2011-2022 走看看