1028 Catch That Cow(bfs+队列)

Catch That Cow
Time Limit: 2000 ms Memory Limit: 65536 KiB

Problem 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 X - 1 or X + 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
Hint
poj3278 有链接提示的题目请先去链接处提交程序,AC后提交到SDUTOJ中,以便查询存档。
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
Source

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
using namespace std;
int vis[100001],step[100001];
queue<int>q;
int bfs(int n,int k)
{
    int head,next;
    q.push(n);//入队
    step[n]=0;//当前步数为0;
    vis[n]=1;//标记已经走过
    while(!q.empty())
    {
        head=q.front();
        q.pop();
        for(int i=0;i<3;i++)//每次可能走的情况
        {
            if(i==0)next=head-1;
            else if(i==1)next=head+1;
            else if(i==2)next=head*2;
            if(next<0||next>=100001)continue;//判断是否越界
            if(!vis[next])//没有走过的话就进入
            {
                q.push(next);
                vis[next]=1;
                step[next]=step[head]+1;
            }
            if(next==k)return step[next];//如果找到了就输出,并退出
        }
    }
}
int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    memset(vis,0,sizeof(vis));
    memset(step,0,sizeof(step));
    if(n>=k)printf("%d\n",n-k);
    else printf("%d\n",bfs(n,k));
    return 0;
}

题意:有头牛跑了,一个人去追,这个人有三种走法,向前走一步,向后走一步,或者走到当前位置的两倍的位置,每次花费的时间都是1分钟,直到追到牛为止;
思路:用bfs和队列,如果人的位置比牛的位置远,只有一步步的往后退,直接输出n-k就行;反之,就要用bfs

猜你喜欢

转载自blog.csdn.net/bhliuhan/article/details/80617820