POJ 3278 Catch That Cow(BFS)

来源:互联网 发布:上海网络借贷平台备案 编辑:程序博客网 时间:2024/05/22 12:37

Catch That Cow

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
题目大意:FJ的牛逃跑了,他想立即抓住它。FJ和牛都在一个数轴上,FJ在位置N,牛在位置K。FJ每分钟可以移动到N - 1、N + 1 或 2 * N 处,而牛却不会动。给出FJ和牛的位置,求FJ抓住牛所需要的最短时间。

解题思路:将每次FJ可能的移动情况入队,BFS即可。注意剪枝,先判断是否超出范围再判断是否访问过,如果顺序反过来的话,数组要开200000+,否则会RE。

代码如下:

#include <cstdio>#include <cstring>#include <algorithm>#include <queue>using namespace std;const int maxn = 100005;int posn,posk;int t[maxn];int bfs(){    memset(t,-1,sizeof(t));    queue<int> que;    que.push(posn);    t[posn] = 0;    int temp;    while(que.size()){        temp = que.front();        que.pop();        if(temp == posk){            break;        }        int next;        next = temp - 1;        if(0 <= next && next <= maxn - 5 && t[next] == -1){            que.push(next);            t[next] = t[temp] + 1;        }        next = temp + 1;        if(0 <= next && next <= maxn - 5 && t[next] == -1){            que.push(next);            t[next] = t[temp] + 1;        }        next = temp + temp;        if(0 <= next && next <= maxn - 5 && t[next] == -1){            que.push(next);            t[next] = t[temp] + 1;        }    }    return t[temp];}int main(){    while(scanf("%d %d",&posn,&posk) != EOF){        printf("%d\n",bfs());    }    return 0;}


0 0
原创粉丝点击