poj 3278 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?
    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.

基础题就不写题解了~

#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;

int N, K;
const int mx = 100010;
bool vis[mx];

struct node{
    int x, step;
};

bool check(int x){
    if(x < 0 || x > 100000 || vis[x])
        return 1;
    return 0;
}

int bfs(){
    queue<node> q;
    node a, ne;
    q.push(node{N, 0});
    while(!q.empty()){
        a = q.front();
        q.pop();
        if(a.x == K)
            return a.step;
        for(int i = -1; i < 2; i+=2){
            ne.x = a.x + i;
            if(check(ne.x))
                continue;
            vis[ne.x] = 1;
            ne.step = a.step +1;
            q.push(ne);
        }
        ne.x = 2 * a.x;
        if(!check(ne.x)){
            vis[ne.x] = 1;
            ne.step = a.step +1;
            q.push(ne);
        }
    }
    return 0;
}

int main(){
    while(scanf("%d%d", &N, &K)!=EOF){
        memset(vis, 0, sizeof(vis));
        int s = bfs();
        printf("%d\n", s);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ling_wang/article/details/81346931