Poj_3278 Catch That Cow(BFS)

题意:

约翰在N,牛在K。约翰可以花一分钟从x走到x+1,x-1或者2*x。问约翰最少花多少时间找到牛。

思路:

最少时间,想到用BFS。用结构体存储约翰的状态(pos,time),TLE了之后又开了一个数组标记到过的点,然后AC。这道题好像做过。。。

代码实现:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int MAX = 100010;

struct Node{
    int pos;
    int times;
    Node(int pos,int times){
        this->pos = pos;
        this->times = times;
    };
    Node(){}
};

int N,K;
int res;
bool tag[MAX];
queue<Node> que;
int main()
{
    scanf("%d%d",&N,&K);
    res = 0;
    Node tmp;
    tmp.pos = N;
    tmp.times = 0;
    que.push(tmp);
    memset(tag,false,sizeof(tag));
    while( !que.empty() ){
        tmp = que.front();
        que.pop();
        if( tag[tmp.pos] == true ){
            continue;
        }
        tag[tmp.pos] = true;
        if( tmp.pos == K ){
            res = tmp.times;
            break;
        }
        if( tmp.pos+1 < MAX ){
            que.push(Node(tmp.pos+1,tmp.times+1));
        }
        if( tmp.pos-1 >= 0 ){
            que.push(Node(tmp.pos-1,tmp.times+1));
        }
        if( tmp.pos*2 < MAX ){
            que.push(Node(tmp.pos*2,tmp.times+1));
        }
    }
    printf("%d\n",res);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值