• poj3278 Catch That Cow


    Description

    Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

    * Walking: FJ can move from any point X to the points - 1 or + 1 in a single minute
    * Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

    If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

    Input

    Line 1: Two space-separated integers: N and K

    Output

    Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

    Sample Input

    5 17

    Sample Output

      4

     

    题目大意:

             FJ要抓奶牛。

             开始输入N(FJ的位置)K(奶牛的位置)。

             FJ有三种移动方法:1、向前走一步,耗时一分钟。

                                                  2、向后走一步,耗时一分钟。

                                                 3、向前移动到当前位置的两倍N*2,耗时一分钟。

           问FJ抓到奶牛的最少时间。PS:奶牛是不会动的。

    思路:典型的广度优先搜索,用队列存下农民每走一步所有可能到达的位置然后出队列搜索,并用标志数组存下当前访问这个位置时所需要的步数,当所在的位置与奶牛重合时,输出标志数组中下标与这个位置相对应的值。即为需要的步数

    #include<iostream>
    
    #include<stdio.h>
    #include<string.h>
    #include<queue>
    #define MAX 100005
    using namespace std;
    
    int cnt[MAX];
    
    int posFJ,posCOW;
    int bfs(){
    memset(cnt,-1,sizeof(cnt));
    queue<int> Q;
    Q.push(posFJ);
    int ans;
    cnt[posFJ]=0;//将FJ所在的位置入队列,并将该位置的标志数组记为0
    
    while(Q.size()){
    
        ans=Q.front();
        Q.pop();//将初始位置赋给某个变量后出队列
        if(ans==posCOW)
            break;//判断该位置是否与奶牛的位置相等
        int next;
        next=ans-1;
        if(next>=0&&next<=MAX-5&&cnt[next]==-1)
            {Q.push(next);
             cnt[next]=cnt[ans]+1;
             }
        next=ans+1;
        if(next>=0&&next<=MAX-5&&cnt[next]==-1)
            {Q.push(next);
             cnt[next]=cnt[ans]+1;
             }
        next=ans+ans;
        if(next>=0&&next<=MAX-5&&cnt[next]==-1)
            {Q.push(next);
             cnt[next]=cnt[ans]+1;
             }
       //以上三步是核心,将三种情况下所到达的位置分别入队列,并且相应标志数组+1代表这是走完第一步后到达的位置
        通过while循环这些位置都会被作为初始位置分别去访问下一步所到达的位置并最终寻找出奶牛所在的位置 }
    return cnt[ans]; } int main(){ while(scanf("%d %d",&posFJ,&posCOW)!=EOF) { int fa = bfs(); cout<<fa<<endl; } return 0; }
  • 相关阅读:
    UML系列图--用例图
    扩展方法
    POJ3254 Corn Fields(状压DP)
    POJ2836 Rectangular Covering(状压DP)
    POJ2817 WordStack(状压DP)
    POJ2441 Arrange the Bulls(状压DP)
    HDU2167 Pebbles(状压DP)
    HDU1561 The more, The Better(树形DP)
    POJ3659 Cell Phone Network(树上最小支配集:树型DP)
    UVa10917 A Walk Through the Forest(SPFA+记忆化搜索)
  • 原文地址:https://www.cnblogs.com/jokerspace/p/6752981.html
Copyright © 2020-2023  润新知