poj-Catch That Cow(排位赛8-c)

来源:互联网 发布:音频信号发生器软件 编辑:程序博客网 时间:2024/05/21 12:47

                  Catch That Cow

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.


题意:
   阿尔默约翰已被告知逃离母牛的位置,并希望立即赶上她。 他在数线上开始点N(0≤N≤100000),母牛在相同数量线上的点K(0≤K≤100000)。 约翰农夫有两种交通方式:步行和远程传送。


*步行:FJ可以在一分钟内从任何点X移动到点X-1或X + 1
*传送:FJ可以在一分钟内从任何点X移动到点2×X。


如果没有意识到它的追求的牛,根本不动,农夫约翰要多久才能收回呢?


输入
行1:两个空格分隔的整数:N和K
输出
第1行:农民约翰抓住逃离母牛所需的时间(分钟)最少。
样品输入
5 17
样品输出
4
暗示
农民约翰到达逃亡牛的最快方法是沿着以下路径行进:5-10-9-18-17,需要4分钟


思路:
   广搜,对所有情况进行搜索,最快到达,所以时间最短。
代码:
   
#include<iostream>#include<stdio.h>#include<queue>#include<string.h>using namespace std;const int maxn=1e6;int book[maxn+10];int m,n;struct node{int x;int step;};int judge(int x){if(x<0||x>=1000000||book[x])//判断是否能走   return 0;return 1;}void bfs(int x){memset(book,0,sizeof(book));node now,next;queue<node>q;now.x=x;now.step=0;book[now.x]=1;q.push(now);//初始化队列 while(!q.empty()){now=q.front();//取出队首元素 q.pop();//删除队首元素 if(now.x==m){printf("%d\n",now.step);return ;}//对每种情况进行搜索 next.x=now.x+1;//加1的方向搜索 if(judge(next.x)){next.step=now.step+1;book[next.x]=1;//标记     q.push(next);}next.x=now.x-1;//减1方向搜 if(judge(next.x)){next.step=now.step+1;book[next.x]=1;//标记   q.push(next);}next.x=now.x*2;//乘2 if(judge(next.x)){next.step=now.step+1;book[next.x]=1;  q.push(next);}}return ;}int main(){while(scanf("%d%d",&n,&m)!=EOF){bfs(n);}return 0;}

0 0
原创粉丝点击