POJ3278 农夫追牛(BFS

上题目先:

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 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn=100010;
int vis[maxn+6];
int n,m;
struct cnmb
{
  int x,step;
};
queueq;
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

 

刷题吧弱鸡!

 

 

 

你可能感兴趣的:(POJ3278 农夫追牛(BFS)