• 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
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    zoj1137 poj1466
    poj3041
    zoj1455
    hdu1160 FatMouse's Speed
    zoj2770
    hdu1469
    hdu3169
    Mapped exception to response: 500 (Internal Server Error)
    Mapped exception to response: 500 (Internal Server Error)
    object is not a function
  • 原文地址:https://www.cnblogs.com/pengwill/p/7367095.html
Copyright © 2020-2023  润新知