POJ3278 Catch That Cow(BFS)

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.
 
感受:1.BFS求最短路这点没想到啊,周赛的时候拼命的去想DFS,然后就是TLE,RE,根本没有想到BFS求最短路。
        2.要加标记数组,不然会死循环。
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>
using namespace std;

const int INF=0x3f3f3f3f;
const double eps=1e-10;
const double PI=acos(-1.0);
#define maxn 220000
int n,k;
int vis[maxn];

struct Node
{
    int x, time;

}node[maxn];

void bfs()
{
    queue<Node> Q;
    Node r,t,f;
    r.time = 0; r.x = n;
    vis[n] = 1;
    Q.push(r);
    while(!Q.empty())
    {
        f = Q.front();
        Q.pop();
        if(f.x == k)
        {
            printf("%d\n", f.time);
            return;
        }
        if(f.x < k&&!vis[f.x*2])
        {
            t.x = f.x*2;
            vis[t.x] = 1;
            t.time = f.time+1;
            Q.push(t);
        }
        if(f.x+1<=k && !vis[f.x+1])
        {
            t.x = f.x+1;
            vis[t.x] = 1;
            t.time = f.time+1;
            Q.push(t);
        }
        if(f.x-1>=0 && !vis[f.x-1])
        {
            t.x = f.x-1;
            vis[t.x] = 1;
            t.time = f.time+1;
            Q.push(t);
        }
    }
}
int main()
{
    while(~scanf("%d%d", &n, &k))
    {
        if(k <= n)
        {
            printf("%d\n", n-k);
            continue;
        }
        memset(vis, 0, sizeof vis);
        bfs();
    }
    return 0;
}

 

       
posted @ 2015-11-09 09:24  JoneZP  阅读(130)  评论(0编辑  收藏  举报