Two Buttons CodeForces #520B 题解[C++]

题目来源


http://codeforces.com/contest/520/problem/B

题目描述


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?

大意是有一台神奇的机器. 机器有一红一绿两个按钮. 机器显示屏上一开始有一个神奇的数字 n, 按一下红色数字就变成 n-1, 按一下蓝色就变成 2*n. n 一开始给定是个正数, 但要是在按按钮的过程中 n<=0, 机器就会”duang”的一下爆炸.

现在给定 n 和要求的数字 m, 要求通过次数最少的按按钮操作把 n 变成 m.

解题思路


一开始下意识地把这道题当成动态规划来做, 即

d p [ n ] = 1 + m i n ( d p [ n 1 ) , d p [ 2 n ] )
, 但很不幸, 这个算法即使进行了剪枝和优化, 空间复杂度和时间复杂度都不能令人满意.

最后考虑采用宽度优先搜索来解决. 第一层宽搜只包含原始的 n, 第二层加入 n 裂解的 n-1 和 2*n, 以此类推. 当检测到

n == m
时停止并返回结果.

为了优化算法执行时间, 还可以进行一下剪枝:

  1. n 1 时, 剪掉 n 1 ;
  2. n m 时, 剪掉 2 n ;

按照以上我们很容易就能写出代码.

代码实现


#include <iostream>
#include <queue>
#include <map>
using namespace std;

map<int, bool> visit;

int main()
{
    int m, n, temp, ret = 0;
    scanf("%d%d", &n, &m);
    queue<int> bf;
    bf.push(n);
    bf.push(-1);
    while (true)
    {
        while ((temp = bf.front()) != -1)
        {
            if (temp == m) {
                printf("%d\n", ret);
                //system("PAUSE");
                return 0;
            }
            else {
                if (temp > 1 && visit.count(temp-1) == 0) {
                    bf.push(temp - 1);
                    visit[temp - 1] = true;
                }
                if (visit.count(temp*2) == 0 && temp < m ) { 
                    bf.push(temp * 2); 
                    visit[temp * 2] = true;
                }
            }
            bf.pop();
        }
        bf.pop();

        bf.push(-1);
        ret++;
    }
    return 0;
}

// dp[n,m]=1+min(dp[2n,m],dp[n-1,m])

代码的表现差强人意:
p1_ac

猜你喜欢

转载自blog.csdn.net/wayne_mai/article/details/80504131
今日推荐