POJ 3278 Catch That Cow (BFS)

来源:互联网 发布:vb数值型 编辑:程序博客网 时间:2024/05/16 23:45
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<cstring>#include<queue>using namespace std;const int M = 1e6 + 10;bool book[M];int ans;int n,k;struct Node{    int x,s;};queue<Node> q;void bfs(int x){    while(!q.empty())        q.pop();    Node tmp, next;    tmp.x = x;    tmp.s = 0;    book[x] = true;    q.push(tmp);    while(!q.empty())    {        tmp = q.front();        q.pop();        if(tmp.x==k)        {            printf("%d\n", tmp.s);            break;        }        next.x = tmp.x + 1;        next.s = tmp.s + 1;        if(next.x>=0&&next.x<M&&!book[next.x])//因为没有这句,MLE了好几次。。        {            q.push(next);            book[next.x] = true;        }        next.x = tmp.x - 1;        next.s = tmp.s + 1;        if(next.x>=0&&next.x<M&!book[next.x])        {            q.push(next);            book[next.x] = true;        }        if(tmp.x<k)        {            next.x = tmp.x*2;            next.s = tmp.s + 1;           if(next.x>=0&&next.x<M&&!book[next.x])            {                q.push(next);                book[next.x] = true;            }        }    }}int main(){    while(~scanf("%d%d", &n, &k))    {        memset(book, false, sizeof(book));        bfs(n);    }    return 0;}


原创粉丝点击