HDU2717 Catch That Cow (BFS)
来源:互联网 发布:美猎推荐 知乎 编辑:程序博客网 时间:2024/05/18 21:48
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.
经典BFS。对所有情况进行一次搜索,最先找到的就是解。
代码如下:
#include <iostream>#include <queue>#include <cstring>using namespace std;const int N=1000000;int map[N+10],n,k;struct point{int x,step;} ; int check(int x){ if(x<0||x>N||map[x]) { return 0; }return 1;} int bfs(int x){queue<point> q; //队列 point now,next;now.x=x;now.step=0; map[x]=1; //标记 q.push(now); //将now插入队列while(!q.empty()){now=q.front(); //将先进入队列的元素取出存入nowq.pop(); //取出后删除if(now.x==k) return now.step;next=now;next.x=now.x+1;//三种情况 if(check(next.x)){ next.step=now.step+1; //步数加一; map[next.x]=1;//标记 q.push(next);}next.x=now.x-1;if(check(next.x)){next.step=now.step+1;map[next.x]=1;q.push(next);}next.x=now.x*2;if(check(next.x)){next.step=now.step+1;map[next.x]=1;q.push(next);} } return -1; } int main(){scanf("%d%d",&n,&k);memset(map,0,sizeof(map));//标记为0(表示未搜索过)cout<<bfs(n)<<endl;return 0; }博客已搬:洪学林博客
0 0
- HDU2717:Catch That Cow(BFS)
- HDU2717 Catch That Cow BFS
- HDU2717:Catch That Cow(BFS)
- hdu2717 catch that cow【BFS】
- HDU2717 Catch That Cow(BFS)
- HDU2717 Catch That Cow (BFS)
- Hdu2717 Catch That Cow (BFS)
- hdu2717 Catch That Cow----BFS
- HDU2717 Catch That Cow BFS
- hdu2717 Catch That Cow BFS简单题
- hdu2717 Catch That Cow(bfs水)
- HDU2717 Catch That Cow (BFS)
- Hdu2717 Catch That Cow(BFS) ---Java版
- HDU2717 Catch That Cow(bfs)
- 【HDU2717】-Catch that cow
- HDU2717:Catch That Cow
- HDU2717 Catch That Cow
- HDU2717 Catch That Cow
- App Bar 点击返回按钮自动返回上一个指定的Activity
- iOS开发svnserver的搭建
- iOS应用性能调优的25个技巧
- IP解析工具类
- BZOJ_P1007&Codevs_P2324 [HNOI2008]水平可见直线(计算几何+单调栈)
- HDU2717 Catch That Cow (BFS)
- Android中onSaveInstanceState注意事项
- JSP中内置对象的getAttribute()和getParameter()
- Android群英传之Android绘图机制与处理技巧
- 开发自定义控件的步骤
- Android应用主题动态切换
- Stimulsoft.Report 2、 web报表的使用
- 新浪微博 分享功能 handleWeiboResponse(intent, response); 不回调的解决办法
- phpstudy www文件夹下面的项目文件夹名字不能为中文