1. 程式人生 > >POJ - 3278 Catch That Cow

POJ - 3278 Catch That Cow

orm mod not div amp trie info owin 大致

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. 大致題意:在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 }

POJ - 3278 Catch That Cow