poj 3278 Catch That Cow

题目链接:Catch That Cow

题目大意:给你一个起点,一个终点,一共有三种操作,向前走一步,向后走一步,前进到当前位置两倍的位置,问最少需要多少步从起点到终点

题目思路:直接bfs就好,特判一下越界的情况

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>

using namespace std;
const int maxn = 1e5+1;

int step[maxn];
bool vis[maxn];
queue<int>q;

int bfs(int n,int k){
    int head,next;
    q.push(n);
    vis[n] = true;
    step[n] = 0;
    while(!q.empty()){
        head = q.front();
        q.pop();
        for(int i = 0;i < 3;i++){
            if(i == 0) next = head-1;
            else if(i == 1) next = head*2;
            else next = head+1;
            if(next < 0||next >= maxn) continue;
            if(!vis[next]){
                vis[next] = true;
                step[next] = step[head]+1;
                q.push(next);
            }
            if(next == k) return step[next];
        }
    }
    return -1;
}

int main(){
    int n,k;
    while(~scanf("%d%d",&n,&k)){
        memset(step,0,sizeof(step));
        memset(vis,0,sizeof(vis));
        while(!q.empty()) q.pop();
        if(n >= k) printf("%d\n",n-k);
        else printf("%d\n",bfs(n,k));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值