Catch That Cow-广度优先搜索-POJ3278

本文探讨了农夫John在追踪逃逸奶牛时的最优路径选择问题,通过使用广度优先搜索算法来最小化到达奶牛所需的时间。具体介绍了算法实现细节,包括农夫的移动方式(步行和瞬移)以及如何利用队列结构进行搜索,最终找到了从初始位置到奶牛位置的最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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.
题意:农夫在坐标x,牛在坐标k不变,现在农夫有三种走法(x+1,x-1,x*2),问农夫最少走几步能找到牛。
这题参考了LYH的代码,虽然以前学过广搜,都忘了。。。今天回顾一下,顺便记录下来。
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
struct node
{
    int x,step;     //x为农夫的坐标,step为农夫走的步数
};
int n,k;
const int N=200005;  
queue<node> q;
int vis[N];     //vis为标记数组,记录农夫是否走过这个点
void bfs()
{
    int x1,ste;
    while(!q.empty())
    {
        node temp=q.front();
        q.pop();
        x1=temp.x;
        ste=temp.step;
        if(x1==k)
        {
            printf("%d\n",temp.step);
            return ;
        }
        if(x1-1>=0&&!vis[x1-1])     //要保证x1-1有意义
        {
            node tt;
            tt.step=temp.step+1;
            tt.x=temp.x-1;
            vis[x1-1]=1;
            q.push(tt);
        }
        if(x1<k&&!vis[x1+1])
        {
            node tt;
            tt.step=temp.step+1;
            tt.x=temp.x+1;
            vis[x1+1]=1;
            q.push(tt);
        }
        if(x1<k&&!vis[2*x1])
        {
            node tt;
            tt.step=temp.step+1;
            tt.x=temp.x*2;
            vis[x1*2]=1;
            q.push(tt);
        }
    }
}
int main()
{
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        while(!q.empty())       //每次把队列置空
            q.pop();
        memset(vis,0,sizeof(vis));
        node t;
        t.x=n;
        t.step=0;
        vis[n]=1;
        q.push(t);
        bfs();
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值