POJ - 3278 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.
 
大致题意:在0至100000的数轴上给定起点与目标点,可以进行左移右移和坐标翻倍的操作,时间花费均为1,输出最小的时间花费
 
其实就是从起点开始bfs,以0为下限,100000为上限,代码如下:
 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<string.h>
 4 #include<algorithm>
 5 #include<queue>
 6 using namespace std;
 7 int n,k,vis[100005];
 8 int move[2]={1,-1};
 9 struct node{
10     int x,t;
11 };
12 int bfs()
13 {
14     node now,next;
15     queue<node>q;
16     now.x=n,now.t=0,vis[n]=1;
17     q.push(now);
18     while(!q.empty())
19     {
20         now=q.front();
21         q.pop();
22         if(now.x==k) return now.t;
23         for(int i=0;i<3;++i)
24         {
25             if(i==0||i==1)
26             {
27                 next.x=now.x+move[i];
28                 if(next.x<0||next.x>100000||vis[next.x]) continue;
29                 next.t=now.t+1,vis[next.x]=1;
30                 q.push(next);
31             }
32             else
33             {
34                 next.x=now.x*2;
35                 if(next.x<0||next.x>100000||vis[next.x]) continue;
36                 next.t=now.t+1,vis[next.x]=1;
37                 q.push(next);
38             }
39         }
40     }
41     return 0;
42 }
43 int main()
44 {
45     scanf("%d%d",&n,&k);
46     printf("%d",bfs());
47     return 0;
48 }

猜你喜欢

转载自www.cnblogs.com/n0-b0dy/p/9382668.html
今日推荐