Catch That Cow

来源:互联网 发布:成都办公软件电脑培训 编辑:程序博客网 时间:2024/06/09 14:28

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 14417    Accepted Submission(s): 4393


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?
 

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和k,农夫在n这个位置,奶牛在k那个位置,农夫要抓住奶牛。

这是一个深搜的题,向三个方向搜索,找到最短路径。

代码参考:

#include<stdio.h>#include<queue>#include<string.h>#include<iostream>using namespace std;int n,k;int visit[100010];struct node{int x;int temp;};int bfs(int x){queue<node>q;node p;p.x=x;p.temp=0;q.push(p);visit[x]=1;while(!q.empty()){p=q.front();q.pop();if(p.x==k) return p.temp;if(p.x+1<100010&&!visit[p.x+1]){visit[p.x+1]=1;node pre;pre.x=p.x+1;pre.temp=p.temp+1;q.push(pre);}if(p.x-1>=0&&!visit[p.x-1]){visit[p.x-1]=1;node pre;pre.x=p.x-1;pre.temp=p.temp+1;q.push(pre);}if(p.x*2<=100010&&!visit[p.x*2]){visit[p.x*2]=1;node pre;pre.x=p.x*2;pre.temp=p.temp+1;q.push(pre);}}return -1;}int main(){while(~scanf("%d%d",&n,&k)){int sum;memset(visit,0,sizeof(visit));sum=bfs(n);printf("%d\n",sum);}return 0;} 


0 0