POJ.3278 Catch That Cow (BFS)

POJ.3278 Catch That Cow (BFS)

题意分析

求最少的操作次数,暴力就用BFS。
这题坑点挺多,一开始交上去无限RE,摸不着头脑,后来发现后数组越界了。因为存在-1的操作和*2的操作 ,不加判断就直接越界。
这告诉我们一个道理,光把数组开大点,是没有用的。

代码总览

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cmath>
#define INF 0x3f3f3f3f
#define nmax 400010
#define MEM(x) memset(x,0,sizeof(x))
using namespace std;
int num, tar;
int ans;
struct s{
    int num;
    int time;
};
bool visit[nmax];
void bfs(int num,int time)
{
    queue<s> q;
    s now = {num,time},temp;
    visit[num] = true;
    q.push(now);
    while(!q.empty()){
        temp = q.front();q.pop();
        if(temp.num == tar){
            ans = temp.time;
            break;
        }
        if(!visit[temp.num+1]){
            now.num = temp.num+1;
            now.time = temp.time+1;
            visit[temp.num+1] = true;
            q.push(now);
        }
        if(temp.num-1>=0 && !visit[temp.num-1]  ){
            now.num = temp.num-1;
            now.time = temp.time+1;
            visit[temp.num-1] = true;
            q.push(now);
        }
        if(temp.num*2<nmax && !visit[temp.num*2] &&temp.num*2 >=0 ){
            now.num = temp.num*2;
            now.time = temp.time+1;
            visit[temp.num*2] = true;
            q.push(now);
        }
    }
}
int main()
{
    //freopen("in.txt","r",stdin);

    while(scanf("%d %d",&num,&tar)!=EOF){
       MEM(visit);
       ans = INF;
       bfs(num,0);
       printf("%d\n",ans);
    }
    return 0;
}
posted @ 2017-04-30 17:18  pengwill  阅读(97)  评论(0编辑  收藏  举报