BFSCatch That Cow(POJ3278)

Posted 路人姜。

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BFSCatch That Cow(POJ3278)相关的知识,希望对你有一定的参考价值。

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

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

 
题目大意
FJ 要找他的牛,FJ和牛在一条线上,FJ的坐标为x,其可以x+1,x-1,或x*2,每次走都耗时1分钟,问怎么才能花最少的时间找到牛
 
分析
 我之前做的都是在图里的广搜,这个题相当于是在x轴上求从起点到终点的最短路径,还有一些特殊情况在代码中标注了。
 
参考代码
#include <iostream>
#include <cstdio>
#include <queue>

using namespace std;

queue <int> que;
int times[100001];//记录花费的时间
int visited[100001];//标记数组,比如x*2已经到达的地方标记下来,x+1到达时就不需要走这了,因为x*2更快
int bfs(int n,int k);

int main()
{
    int N,K;//N:FJ,K:cow
    scanf("%d%d",&N,&K);
    que.push(N);
    times[N]=0;
    visited[N]=1;
    printf("%d\n",bfs(N,K));
    return 0;
}
int bfs(int n,int k){

    while(!que.empty()){
        int t1=que.front();
        que.pop();
        int t;
        for(int i=0;i<3;i++){//遍历三种方式,相当于在图中遍历四个方向
            t=t1;
            if(i==0){
                t=t+1;
            }
            else if(i==1){
                t=t-1;
            }
            else{
                t=t*2;
            }
            //因为N的范围是0~100000所以可能越界
            ///刚开始我没考虑到,就runtime error了。。
            if(t<0||t>100001)
                continue;

            if(visited[t]==0){
                que.push(t);
                visited[t]=1;
                times[t]=times[t1]+1;
            }

            if(t==k){
                return times[t];
            }
        }
    }
}

参考自:http://blog.csdn.net/freezhanacmore/article/details/8168265

 

以上是关于BFSCatch That Cow(POJ3278)的主要内容,如果未能解决你的问题,请参考以下文章

poj 3278 Catch That Cow

POJ 3278 Catch That Cow

POJ 3278 - Catch That Cow - [BFS]

poj3278Catch That Cow

POJ 3278: Catch That Cow

POJ 3278 Catch That Cow(模板——BFS)