POJ3278 农夫追牛(BFS

本文介绍了一道经典的算法题目,即如何利用最少步骤从给定起点捕捉到静止目标。通过对三种移动方式的分析,采用广度优先搜索(BFS)策略解决了问题,并对比了深度优先搜索(DFS)的应用场景。

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

上题目先:

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.

 

题目大概意思是给你农夫其实位置(一维 ),然后另一个数是奶牛的坐标,就是问你农夫有三种方式

1:向前走1(+1

2:向后走1(-1

3:坐车做到当前位置的2倍(*2

上面这三种耗时都是1,问最快什么时候抓住奶牛(奶牛不动的

最初我以为这题是DFS的  真的和白书DFS模板题太像了  也一直在想怎么用DFS来过,但是后来真的只能做到判断,实在无法求出他的最佳耗时,然后就在网上看题解都是用BFS做的,然后就寻思这把BFS学了在做,现在来看这个问题也明朗了很多,还是通过队列来保存最优解的分步。

 

主要是给了我一个关于DFS与BFS的教训:求最优解(最短路径。最少操作应该往BFS想,而想白书模板那种问是否存在的才真正应该用DFS解决 

AC截图:

 

AC CODE:

/*
Sample Input
5 17
Sample Output
4
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=100010;
int vis[maxn+6];
int n,m;
struct cnmb
{
  int x,step;
};
queue<cnmb>q;
int main()
{
  scanf("%d%d",&n,&m);
  memset(vis,0,sizeof(vis));
  cnmb wmw;
  wmw.x=n;
  wmw.step=0;
  q.push(wmw);
  vis[n]=1;
  while(!q.empty()){
    cnmb wyh=q.front();
    if(wyh.x==m){
      printf("%d\n",wyh.step);
      return 0;
    }
    if(wyh.x-1>=0&&!vis[wyh.x-1])
    {
      cnmb lxc;
      lxc.x=wyh.x-1;
      lxc.step=wyh.step+1;
      q.push(lxc);
      vis[wyh.x-1]=1;
    }
    if(wyh.x+1<maxn&&!vis[wyh.x+1])
    {
      cnmb xjw;
      xjw.x=wyh.x+1;
      xjw.step=wyh.step+1;
      q.push(xjw);
      vis[wyh.x+1]=1;
    }
    if(wyh.x*2<maxn&&!vis[wyh.x*2])
    {
      cnmb sb;
      sb.x=wyh.x*2;
      sb.step=wyh.step+1;
      q.push(sb);
      vis[wyh.x*2]=1;
    }
    q.pop();
  }
  //return 0;
}

 

刷题吧弱鸡!

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值