Catch That Cow
2016-01-03 13:25
330 查看
算法: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
代码:
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
代码:
#include <iostream> #include <stdio.h> #include <cstring> #include <iomanip> #include <algorithm> #include <queue> using namespace std; int a[400005]; struct dot { int x,step; }; void bfs(int n,int m) { memset(a,0,sizeof(a)); queue<dot>que; dot cur,loer; cur.x=n; cur.step=0; a =1; que.push(cur); while(que.size()) { loer=que.front(); que.pop(); if(loer.x==m) { cout<<loer.step<<endl; break; } for(int i=0;i<3;i++) { if(i==0) cur.x=loer.x+1; else if(i==1) cur.x=loer.x-1; else cur.x=loer.x*2; if(cur.x>=0&&!a[cur.x]&&cur.x<200005)//一定要加上cur.x<200005 { cur.step=loer.step+1; a[cur.x]=1; que.push(cur); } } } } int main() { int n,m,i,j,k; while(cin>>n>>m) bfs(n,m); return 0; }
相关文章推荐
- roslaunch文件中的局部参数与全局参数
- vim 基础学习之查找
- Java笔记---MD5 加密的实现
- feof & ferror & clearerr 的使用...
- NSData所有API学习
- docker export import
- 基于javascript实现窗口抖动效果
- 九章算法面试题87 最小子数组
- 解决brew update执行失败的方法
- ViewController的View创建过程
- myeclipse如何修改jsp的默认编码
- CocosForWinWithFramework-v2.3.3的bug
- 九章算法面试题86 合并排序数组
- 2016的渲染
- Git 版本控制 在 WIN 下的一些使用方法
- 应用程序进入后台之后的延时操作
- 后端学习资料分享
- 文件随机读写实现...fseek
- 九章算法面试题85 搜索区间
- bug 长整型陷阱