zoukankan      html  css  js  c++  java
  • POJ3279 Catch That Cow(BFS)

    本文来源于:http://blog.csdn.net/svitter


    意甲冠军:给你一个数字n, 一个数字k。分别代表主人的位置和奶牛的位置,主任能够移动的方案有x+1, x-1, 2*x。求主人找到奶牛的时间(奶牛不移动)

    题解:最基础的BFS可是脑子犯抽WA了3遍- =

    注意:

    1.数组范围1~1<<5

    2.visit去重。(BFS最基础的)


    代码:

    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    #include <queue>
    
    using namespace std;
    
    bool visit[100010];
    
    struct step
    {
        int x;
        int t;
        step(){}
        step(int a, int b):x(a), t(b){}
    };
    
    inline bool judgeNum(int i)
    {
        if(i > 100000 || i < 0)
            return false;
        return true;
    }
    
    
    int main()
    {
        int n, k;
        queue <step> que;
        step top;
        int temp;
        
        while(~scanf("%d%d", &n, &k))
        {
            memset(visit, 0, sizeof(visit));
            visit[n] = 1;
            que.push(step(n, 0));
            while(!que.empty())
            {
                top = que.front();
                if(k == top.x)
                {
                    printf("%d
    ", top.t);
                    while(!que.empty())
                    {
                        que.pop();
                    }
                    break;
                }
                temp = top.x+1;
                if(judgeNum(temp) && !visit[temp])
                {
                    que.push(step(top.x+1, top.t+1));
                    visit[temp] = 1;
                }
    
                temp = top.x-1;
                if(judgeNum(temp) && !visit[temp])
                {
                    que.push(step(top.x-1, top.t+1));
                    visit[temp]= 1;
                }
    
    
                temp = top.x*2;
                if(judgeNum(temp) && !visit[temp])
                {
                    que.push(step(2*top.x, top.t+1));
                    visit[temp] = 1;
                }
    
                que.pop();
            }
            
        }
        return 0;
    }
    


  • 相关阅读:
    0425正则数组
    0424php函数
    0424php基础
    string类例题
    数组分为一维数组,二维数组,多为数组
    string类 截取的长度 是否包含某个数
    循环语句2
    /异常语句try,catch.
    string类
    循环语句
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5030026.html
Copyright © 2011-2022 走看看