1. 程式人生 > >【BFS】Catch That Cow(POJ3278)

【BFS】Catch That Cow(POJ3278)

med ror run spa push wal names 特殊 space

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

USACO 2007 Open Silver 題目大意
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

【BFS】Catch That Cow(POJ3278)