HDU 2717 Catch That Cow【BFS】
来源:互联网 发布:开淘宝店身份证照片 编辑:程序博客网 时间:2024/04/30 07:38
Catch That Cow
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12291 Accepted Submission(s): 3816
Problem 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?
* 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
4HintThe 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.
题意:牛和农夫在一条直线上,给定他们的位置分别为n,m。农夫有三种走法分别是往前走1步,往后走1步,瞬移到n*2的位置上。问农夫最少几步走到牛的位置上。
题解:直接bfs遍历每一种走法,走到牛的位置停止即可。注意记录步数,标记走过的位置,即数组下标大小即可。
代码:
#include<stdio.h>#include<string.h>#include<queue>#include<algorithm>using namespace std;int step[100010];int n,m;void bfs(int n,int m){memset(step,0,sizeof(step));queue<int>q;q.push(n);while(!q.empty()){int now=q.front();q.pop();if(now==m) break;for(int i=0;i<3;i++){int next;if(i==0) next=now+1;if(i==1) next=now-1;if(i==2) next=now*2;if(next>=0&&next<=100000&&!step[next]){step[next]=step[now]+1;q.push(next);}}}}int main(){while(scanf("%d%d",&n,&m)!=EOF){bfs(n,m);printf("%d\n",step[m]);}return 0;}
0 0
- hdu 2717 Catch That Cow bfs
- hdu 2717 Catch That Cow(bfs)
- HDU 2717 Catch That Cow (BFS)
- HDU 2717--Catch That Cow【BFS】
- HDU 2717:Catch That Cow 【bfs】
- hdu-2717 Catch That Cow (BFS)
- hdu 2717 Catch That Cow(BFS)
- HDU 2717 Catch That Cow(BFS)
- HDU 2717 Catch That Cow 水题BFS
- HDU 2717 Catch That Cow [BFS]
- HDU 2717 Catch That Cow(BFS)
- HDU 2717 Catch That Cow (BFS)
- HDU 2717 Catch That Cow (BFS)
- 【HDU 2717】Catch That Cow(BFS)
- hdu 2717 Catch That Cow (BFS)
- HDU 2717 Catch That Cow【BFS】
- HDU 2717 Catch That Cow【BFS】
- 【HDU】-2717-Catch That Cow(BFS)
- 关于Eclipse中遇到的经常性参数报错问题总结
- 使用 gcc 和 CMake 编译简单的 OpenCV 程序
- Cron 表达式详解
- poj3899 The Lucky Numbers 模拟+数学
- ubuntu/var/log/下各个日志文件
- HDU 2717 Catch That Cow【BFS】
- 提交文件路径
- Linux安装yum命令
- [Android]FloatingText仿点赞+1等效果
- 编写sql sever存储过程随笔
- linux代码风格
- Android EventBus源码解析 带你深入理解EventBus
- poj 1062 昂贵的聘礼 (dijkstra)
- JS闭包的使用