POJ 3278 Catch That Cow

思路很直接也很简单的一个bfs,但必须反思一下自己的是竟然在写bfs忘了修改visited,导致了tle,尼玛之前申请了visited的数组竟然没有用!

写bfs时会很习惯的申请bfs,但却没有习惯的去使用,好吧,该死!该tle!

/*
POJ: 3278 Catch That Cow
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>

using namespace std;

const int M = 200005;

struct Node {
    int a;
    int step;
    
    Node(int _a, int _step) : a(_a), step(_step) {}
};

int n, k;
queue<struct Node> que;
bool visited[M];

int getPlace(int i, int x)
{
    if(i == 1)
        return x - 1;
    if(i == 2)
        return x + 1;
    if(i == 3)
        return x << 1;
}

bool check(int x)
{
    if(x >= 0 && x <= 200000)
        return true;
    return false;
}

int bfs()
{
    while(!que.empty())
        que.pop();
    memset(visited, false, sizeof(visited));
    
    que.push(Node(n, 1));
    visited[n] = true;
    while(!que.empty()) {
        struct Node tmp = que.front();
        que.pop();
        for(int i = 1; i <= 3; i++) {
            int x = getPlace(i, tmp.a);
            if(check(x) && !visited[x]) {
                if(x == k)
                    return tmp.step;
                else {
                    que.push(Node(x, tmp.step + 1));
                    visited[x] = true;
                }
            }
        }
    }
    return 0;
}

int main()
{
    //freopen("data.in", "rb", stdin);
    while(scanf("%d%d", &n, &k) != EOF) {
        if(n >= k)
            printf("%d\n", n - k);
        else
            printf("%d\n", bfs());
    }
    
    return 0;
}
        


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值