Catch That Cow(BFS和queue()用法)
来源:互联网 发布:淘宝上如何买衣服 编辑:程序博客网 时间:2024/06/15 16:28
Catch That Cow
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
题意:
牛逃跑了,人要去抓回来这只牛,他们在一条直线上 ,现在牛的坐标是K,人的坐标是N,牛呆在原位置不动。人可移动X-1,X+1或2*X 的位置。每移动一步用一分钟,问人最少需要几分钟可以抓到牛。
思路:很明显的广搜题,有两种情况:一是牛在人的前面,即K<N,那么人只能一步一步的退着走,时间为N-K;第二种,牛在人的后面,那么人三种走法,这样搜下去即可,注意记录走过的坐标。
思路:很明显的广搜题,有两种情况:一是牛在人的前面,即K<N,那么人只能一步一步的退着走,时间为N-K;第二种,牛在人的后面,那么人三种走法,这样搜下去即可,注意记录走过的坐标。
代码如下:
#include<stdio.h>#include<string.h>#include<queue>#include<iostream>#define MAX 111111using namespace std;int vis[MAX];int f[MAX];int n,k;void BFS(){ vis[n]=1; queue<int> q; q.push(n); while(!q.empty()) { int x=q.front(); q.pop(); if(x==k) printf("%d\n",f[x]); if(x-1>=0&&!vis[x-1]) { vis[x-1]=1; q.push(x-1); f[x-1]=f[x]+1; } if(x+1<=MAX&&!vis[x+1]) { vis[x+1]=1; q.push(x+1); f[x+1]=f[x]+1; } if(x*2<=MAX&&!vis[x*2]) { vis[x*2]=1; q.push(x*2); f[x*2]=f[x]+1; } }}int main(){ while(~scanf("%d%d",&n,&k)) { memset(vis,0,sizeof(vis)); memset(f,0,sizeof(f)); BFS(); } return 0;}
0 0
- Catch That Cow(BFS和queue()用法)
- Catch That Cow(BFS)
- Catch That Cow(BFS)
- Catch That Cow (BFS)
- Catch That Cow (BFS)
- Catch That Cow(BFS)
- poj3278 Catch That Cow (BFS算法和队列)
- HDOJ 2717 Catch That Cow (BFS)
- poj 3278 Catch That Cow(bfs)
- poj Catch That Cow (Bfs)
- POJ 3278 Catch That Cow (BFS)
- poj3278 Catch That Cow(bfs搜索)
- POJ 3278 Catch That Cow(BFS)
- hdu 2717 Catch That Cow(bfs)
- POJ3279 Catch That Cow(BFS)
- POJ--3278:Catch That Cow (BFS)
- Catch That Cow(BFS 剪枝 )
- POJ 3278 - Catch That Cow(BFS)
- 搭建Node.js开发IDE环境WebStrom5
- 工程师手记-升级PNI以支持PHP7
- ionic2上实现跳转应用市场的功能
- Oracle 11g的安装步骤以及注意事项
- Coursera Machine Learning 第二周 quiz Linear Regression with Multiple Variables 习题答案
- Catch That Cow(BFS和queue()用法)
- Java将小写金额转换成大写
- 子进程和父进程是否共用同一个全局变量
- ALV 动态显示列Demo
- 源码剖析Yii错误 Invalid parameter number: no parameters were bound
- 1613-3-傅溥衍 总结《2016年11月9日》【连续四十天总结】
- SqlServer数据库定时删除系统日志
- Node.js入门学习笔记-IDE选择/配置之WebStorm(windows)
- uml(四) 包图