poj 3728 Catch That Cow

基本的BFS搜索
1.记得每次都要清空队列,因为忘清空了卡了很久
2.hdu和poj上的数据输入方式是不一样的

#include<iostream>
#include<queue>
#include<cstdio>
#include<string.h>
using namespace std;
const int N = 1e5+5;
int vis[N], step[N];
queue <int> q;
int BFS(int n, int k){
    int now, next;
    vis[n] = 1; step[n] = 0;
    q.push(n);
    while(!q.empty()){
        now = q.front();
        q.pop();
        for(int i=0; i<3; ++i){
            if(i == 0) next = now - 1;
            else if(i == 1) next = now + 1;
            else if(i == 2) next = now * 2;
            if(next < 0 || next > N) continue;
            if(!vis[next]){
                vis[next] = 1;
                step[next] = step[now] + 1;
                q.push(next);
            }
            if(next == k) return step[next];
        }
    }
}
int main(){
    int n, k;
    while(scanf("%d%d",&n,&k)!=EOF){
        memset(vis, 0, sizeof(vis));
        memset(step, 0, sizeof(step));
        while(!q.empty()) q.pop();
           printf("%d\n",BFS(n, k));    
    }
}
全部评论

相关推荐

喵_coding:这实习干啥了? 没写出来一点产出啊 好好回忆一下干了啥 问问ai 问问大佬 准备些话术就好了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务