Catch That Cow

Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Submit Status

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. 

#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<queue>
#include<stack>
using namespace std;
#define N 100010
int time[N], maps[N], s, e;//将这些宏定义是为了避免传参;
void BFS();
int main()
{
while(scanf("%d%d", &s, &e)!=EOF)
{
memset(time, 0, sizeof(time));//定义的时间数组,初始化为零;本身定义了结构体,其中包含了位置location、时间time、标记变量flag。却发现flag无法初始化
memset(maps, 0, sizeof(maps));//标记是否走过
if(s==e)
printf("0\n");
else
BFS();
}
return 0;
}
void BFS()
{
queue<int>que;
int i, x, dir;
maps[s]=1;
que.push(s);
while(!que.empty())
{
x=que.front();
que.pop();
for(i=0; i<3; i++)
{
switch(i)//用switch更简便;
{
case 0: dir=x-1; break;
case 1: dir=x+1; break;
case 2: dir=x*2; break;
}
if(dir==e)//结束条件。其实也可放在for循环外,只不过是多进行了几步而已
{
printf("%d\n", time[x]+1);
return;
}
if(maps[dir]==0&&dir<N&&dir>=0)//这也算是剪枝,减少了重复
{
que.push(dir);
maps[dir]=1;
time[dir]=time[x]+1;
}
}
}
}

最新文章

  1. 存储程序(1)——MYSQL
  2. 使用page object模式抓取几个主要城市的pm2.5并从小到大排序后写入txt文档
  3. MVC中的BASE.ONACTIONEXECUTING(FILTERCONTEXT) 的作用
  4. c指针与数组,传参问题,指针数组与数组指针的区别,二维数组动态内存分配
  5. js Module模式
  6. poj 2240 Arbitrage (Floyd)
  7. android 50 进程优先级
  8. 服务器端javascript——Rhino和Node
  9. 【iOS】Resumable Doanloads(断点下载)
  10. Android的AsyncTask类的解读
  11. MVC EF 增 删 改 查
  12. PAT (Advanced Level) 1021. Deepest Root (25)
  13. Android开发之AsyncTask示例Demo
  14. vs 修改活动解决方案配置后无法调试,不生成pdb文件,“当前不会命中断点 还没有为该文档加载任何符号” 解决方法
  15. CF527E Data Center Drama(构造+欧拉回路)
  16. bitnami下webmin安装
  17. python测试开发django-19.admin后台自定义显示
  18. DWZ主从表界面唯一性验证(自写js)(一)
  19. OpenACC parallel
  20. 微信小程序 --01

热门文章

  1. Android 完整开源应用大全,完整开源项目
  2. nginx限速
  3. 【Linux 驱动】设备驱动程序再理解
  4. Atitit.跨语言&#160;java&#160;c#.net&#160;php&#160;js常用的codec&#160;encode算法api&#160;兼容性&#160;&#160;应该内置到语言里面
  5. [转]Ubuntu Server命令行更换软件源
  6. 为什么jdbc中的resultset只能取一次去第二次就报错了
  7. busybox下inittab中runlevel解析
  8. nginx proxy_pass 里的”/”
  9. 在ListView的GroupItem头中显示每列的Summary
  10. mac地址绑定