Catch That Cow(POJ-3278)

本文解析了POJ-3278问题,通过使用宽度优先搜索(bfs)来寻找农夫抓到逃跑奶牛的最短时间。介绍了bfs的基本原理,并给出了详细的实现代码。

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

POJ - 3278 传送门

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 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.

分析

博主第一次写搜索题
先介绍一下 bfs() 和 dfs() 的区别

  • bfs() :指的是从起点向多个方向同时出发,多个方向一起搜,最先搜到的即为最优解
  • dfs() :指的是从起点出发,一层一层的往下走,碰到这个点可以走,就深入走下去,直到搜到为止
     

这道题博主是用的 bfs() 解题
从题意中我们得知,有三种方向供选择,由于等下可能会重复,故我们要记录每个点是否已经走过
用 for 循环每次试水一种走法,并判断是否满足条件,若满足则标记后放入队列,miu 加 1
每种走法会对应很多种分支走法,我们这里的miu对应的就是每种走法所耗费的时间
当触碰到奶牛的位置时候,即为最优解,因为是用最少的时间到达的

Code

#include<iostream>
#include<algorithm>
#include<queue>
#include<string.h>
using namespace std;
const int maxn = 100002;
int miu[maxn];
int vis[maxn];
int bfs(int n,int m)
{
    int now,next;
    miu[n]=0;//记录起点
    vis[n]=1;//起点已经走过
	queue<int>q;
    q.push(n);//放入起点 :农夫的位置
    while(!q.empty())
	{
        now=q.front();//当前位置
        q.pop();//弹出	
//		cout<<"----------------------------------------------------"<<endl;
        for(int i = 1 ; i <= 3 ; i++)// 三种走法
		{
		
            if(i == 1)		next=now-1;//试水第一种走法
            else if(i == 2)	next=now+1;//试水第二种走法
            else if(i == 3)	next=now*2;//试水第三种走法
            if(next<0 || next>maxn) continue;//越界了,不往下走了,继续i++
            if(vis[next] == 0)//还没走过这个点
			{
                vis[next]=1;	//标记已走
                q.push(next);	//放进队列:新的一个位置
                miu[next]=miu[now]+1;//花了一分钟 
//				cout<<"测试 : now = "<<now<<"  next = "<<next<<"  miu["<<next<<"] = "<<miu[next]<<endl;
            }
            if(next == m) return miu[next];//到达了目标点,返回到达目标点所花费的时间
        }
    }
}
int main()
{
	memset(vis,0,sizeof(vis));
	memset(miu,0,sizeof(miu));
    int fj,cow;
    cin>>fj>>cow;
    if(fj>=cow)
	{
		cout<<fj-cow<<endl;
	}
    else
	{
		cout<<bfs(fj,cow)<<endl;
	}
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值