poj_3278 Catch That Cow(bfs)

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 79009   Accepted: 24912

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 - 1 or + 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.

一维bfs,就算是一维也要注意数组不要越界。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <stack>
#include <bitset>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#define FOP freopen("data.txt","r",stdin)
#define inf 0x3f3f3f3f
#define maxn 100010
#define mod 1000000007
#define PI acos(-1.0)
#define LL long long
using namespace std;

int s, e;

int path[maxn];
bool vis[maxn];

void bfs()
{
    memset(vis, 0, sizeof(vis));
    memset(path, 0, sizeof(path));
    queue<int> Q;
    Q.push(s), vis[s] = 1;

    while(!Q.empty())
    {
        int t = Q.front();
        Q.pop();
        if(t == e) break;
        int t1 = t + 1, t2 = t - 1, t3 = t * 2;

        if(t1 >= 0 && t2 <= 100000 && !vis[t1]) Q.push(t1), vis[t1] = 1, path[t1] = path[t] + 1;
        if(t2 >= 0 && t2 <= 100000 && !vis[t2]) Q.push(t2), vis[t2] = 1, path[t2] = path[t] + 1;
        if(t3 >= 0 && t3 <= 100000 && !vis[t3]) Q.push(t3), vis[t3] = 1, path[t3] = path[t] + 1;
    }
}

int main()
{
    while(~scanf("%d%d", &s, &e))
    {
        bfs();
        printf("%d\n", path[e]);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/christry_stool/article/details/53065543
今日推荐