Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 114140   Accepted: 35715

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 - 1 or + 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.

Source

 
终于A掉这道题,BFS新认知。
 
#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<vector>
#include<cmath>
#include<cstring>
#include<string> #define N 100010 using namespace std; void in(int &x){
register char c=getchar();x=0;int f=1;
while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}
while(isdigit(c)){x=x*10+c-'0';c=getchar();}
x*=f;
} int a,b,ans;
struct Step{
int v,w;//位置,步数
Step(int xx,int s):v(xx),w(s){ }
};
bool vis[N];
queue<Step>Q; void BFS(){
memset(vis,0,sizeof(vis));
vis[a]=1;Q.push(Step(a,0));
while(!Q.empty()){
Step s=Q.front();Q.pop();
if(s.v==b) {
ans=s.w;break;
}
else {
if(s.v-1>=0 && !vis[s.v-1]){
Q.push(Step(s.v-1,s.w+1));
vis[s.v-1]=1;
}if(s.v+1<=N &&!vis[s.v+1]){
Q.push(Step(s.v+1,s.w+1));
vis[s.v+1]=1;
}if(s.v*2<=N && !vis[s.v*2]){
Q.push(Step(s.v*2,s.w+1));
vis[s.v*2]=1;
}
}
}
} int main()
{
in(a);in(b);
BFS();
printf("%d\n",ans);
return 0;
}

  

最新文章

  1. 提高MYSQL百万条数据的查询速度
  2. Cortex-M3中C与汇编的交互
  3. OpenCV学习笔记——OpenCV安装
  4. 我的cookie读写
  5. Oracle数据库入门——如何根据物化视图日志快速刷新物化视图
  6. html之texteara
  7. Routed Events【pluralsight】
  8. Npoi 导出Excel 下拉列表异常: String literals in formulas can&#39;t be bigger than 255 Chars ASCII
  9. 新建线程与UI线程间的通信
  10. 使用border-image实现类似iOS7的1px底边
  11. mysql相关日志汇总
  12. windows 命令行打开浏览器
  13. AngularJS + RequireJS
  14. monkey自定义脚本实践
  15. Oracle命令行中显示:ORA-04076: 无效的 NEW 或 OLD 说明
  16. 0. General-purpose tools (通用工具 8个)
  17. Django之setting文件
  18. GreenTrend
  19. Mysql—(2)—
  20. springmvc jpa

热门文章

  1. 修改Cygwin的默认启动目录
  2. cojs1101. [Vijos1369] 难解的问题==codevs 2188 最长上升子序列
  3. SQL server触发器中 update insert delete 分别给写个例子被。
  4. Olddriver’s books
  5. UNDO表空间不足解决方法
  6. iOS通讯录(纯纯的干货)
  7. Countries in War(强连通分量及其缩点)
  8. webpack的初步使用(01)
  9. longpo的回文
  10. lua_string_pattern