您的位置:首页 > 其它

Catch That Cow

2015-08-06 14:22 218 查看

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 9344    Accepted Submission(s): 2929


[align=left]Problem Description[/align]
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?
 

 

[align=left]Input[/align]
Line 1: Two space-separated integers: N and K
 

 

[align=left]Output[/align]
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
 

 

[align=left]Sample Input[/align]

5 17

 

 

[align=left]Sample Output[/align]

4

 

 

/*

题意::

  输入两个在同一条直线上的点N,K,要从N到K,问消耗最小时间是多少

  从N到K有三种走法::

  1、N+1,

  2、N-1;

  3、2*N

  每种走法消耗的时间相同。

解题思路::

  运用优先队列会更简单点,因为它会自动排序。

  首先让N进队列,判断N是否==K,若等于则直接结束,输出结果。否则,按那三种

  走法给N付一个新的值,然后进队列,每付一次值,时间就要加1。直到N==K时输出

难点::

  但怎么能输出最小消耗时间哪?

  因为这是广搜,他每走一步都有3种选择,计算机就会分三种情况,也就是三个分支

  这三个分支都会存在,然后走下一步,还是三个分支,以此类推,只要他到达K,就及时

  输出结果,那么此时结果就是最小的了,其他分支还没到达K,所以他们的消耗的时间

  肯定多了,就没必要再算了。

  

  

*/

#include<stdio.h>

#include<string.h>

#include<queue>

#include<algorithm>

using namespace std;

int a[100100];

int n,m;

void bfs()

{

 queue<int>q;

 q.push(n);

 a
=1;

 while(!q.empty() )

 {

  int t=q.front();

  q.pop() ;

  if(t==m)

   break;

  else//分三种情况

  {

   int next=t-1;

   if(next>=0&&!a[next])

   {

    q.push(next);

    a[next]=a[t]+1;

   }

   next=t+1;

   if(next>=0&&!a[next])

   {

    q.push(next);

    a[next]=a[t]+1;

   }

   next=t*2;

   if(next<=100000&&!a[next])

   {

    q.push(next);

    a[next]=a[t]+1;

   }

  }

 }

}

int main(){

 while(scanf("%d%d",&n,&m)!=EOF)

 {

  if(n>=m)//如果n>m,肯定是按N-1这种方法走。

   a[m]=n-m+1;

  else

   bfs();

   printf("%d\n",a[m]-1);

 }

 return 0;

}

搜索
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: