codeforces 520B Two Buttons

没想到连水题都过不了了。。。
一开始用 IDA* 做,栈深度貌似太大
后来改用 BFS,继续挂,才发现自己连记忆化这种最简单的剪枝都没想到。。。

#include <iostream>
#include <string>
#include <cstring>
#include <queue>

using namespace std;

int n, m;

struct node
{
    node(int s, int v):step(s), val(v){}
    int step, val;
};

bool vis[20005];
queue<node> q;

int main()
{
    while (cin>>n>>m) {
        if (m <= n) {
            printf("%d\n", n-m);
            continue;
        }

        while(!q.empty()) q.pop();
        q.push(node(0, n));

        memset(vis, 0, sizeof(vis));

        int ans = 0;
        while (!q.empty()) {

            node cur = q.front();
            q.pop();

            if(cur.val == m){
                ans = cur.step;
                break;
            }

            if(cur.val <= 0)
                continue;

            if (vis[cur.val]) {
                continue;
            }

            if(cur.val > m)
            {
                q.push(node(cur.step+1, cur.val-1));
                continue;
            }

            vis[cur.val] = true;

            q.push(node(cur.step+1, cur.val*2));
            q.push(node(cur.step+1, cur.val-1));
        }

        printf("%d\n", ans);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值