Catch That Cow (BFS)

题目:

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?InputLine 1: Two space-separated integers: N and KOutputLine 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

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.

题意:
人抓牛,数轴上人在点N处,牛在点K处,通过前进1,后退1,当前位置乘以2三种方式到达K处,牛在K处不动,求人从N处到牛的K处所经过的最少步数;

分析:
求最小路径,用BFS;
分为+1,-1,*2三种情况;
分为N在K之前或者在K上的情况和N在K之后的情况,N在K之前就只能通过-1的操作到达K
定义一个数组用于标记经过的位置坐标;
定义一个数组用于记录到达当前位置所需要的最少步数;
在三种情况下,满足范围即入队列,对当前的坐标进行标记,步数加1;

AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int Max=100005;
int n,k;
int f[Max];
int step[Max];
bool cmp(int x)
{
    return (x>=0&&x<=Max);
}
int a,b;
void bfs()
{
    queue<int>s;
    s.push(n);
    f[n]=1;
    step[n]=0;
    while (!s.empty())
    {
        a=s.front();
        s.pop();
     if (a==k)
            break;
        b=a-1;
        if (cmp(b)&&!f[b])
        {

            s.push(b);
            f[b]=1;
            step[b]=step[a]+1;
        }
          b=a+1;
        if (cmp(b)&&!f[b])
        {
            s.push(b);
         f[b]=1;
            step[b]=step[a]+1;
        }
          b=a*2;
        if (cmp(b)&&!f[b])
        {
            s.push(b);
             f[b]=1;
            step[b]=step[a]+1;
        }

    }
}
int main()
{

   while (scanf("%d %d",&n,&k)==2)
   {
       memset(f,0,sizeof(f));
        if (n>=k)
       printf("%d\n",n-k);
    else
        {
            bfs() ;
           printf("%d\n",step[k]);
        }
   }

    return 0;
}

 




posted @ 2017-07-26 14:48  你的女孩居居  阅读(227)  评论(0编辑  收藏  举报