zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    CentOS7安装mysql-8
    zabbix监控规划及实施
    集群技术
    自动化脚本-配置LVS(DR模式)
    Pacemaker+ISCSI实现Apache高可用-配置
    创建集群corosync
    我的第一个python程序——猜数字
    质量报告
    新需求测试与回归测试
    冒烟测试
  • 原文地址:https://www.cnblogs.com/pengwill/p/7367095.html
Copyright © 2011-2022 走看看