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.
别忘记剪枝啊!要不然超时和超内存多难受TAT
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<vector> 5 #include<cstring> 6 #include<string> 7 #include<algorithm> 8 #include<map> 9 #include<cmath> 10 #include<math.h> 11 using namespace std; 12 13 int n,k,res; 14 bool vis[200005]; 15 16 struct node 17 { 18 int p,t;//p是当前位置,t是所用时间 19 }a; 20 21 void bfs() 22 { 23 node tmp,next; 24 queue<node>Q; 25 Q.push(a); 26 while(!Q.empty()) 27 { 28 tmp=Q.front(); 29 Q.pop(); 30 if(tmp.p==k) 31 { 32 if(tmp.t<res) 33 res=tmp.t; 34 } 35 else if(tmp.t>res) 36 continue; 37 else 38 { 39 next.t=tmp.t+1; 40 //往前 41 if(tmp.p<=k&&!vis[tmp.p+1]) 42 { 43 next.p=tmp.p+1; 44 Q.push(next); 45 vis[next.p]=true; 46 } 47 //往后 48 if(tmp.p>=1&&!vis[tmp.p-1]) 49 { 50 next.p=tmp.p-1; 51 Q.push(next); 52 vis[next.p]=true; 53 } 54 //乘2 55 if(tmp.p<=k&&!vis[tmp.p*2]) 56 { 57 next.p=tmp.p*2; 58 Q.push(next); 59 vis[next.p]=true; 60 } 61 62 } 63 64 } 65 } 66 67 int main() 68 { 69 while(~scanf("%d%d",&n,&k)) 70 { 71 res=abs(k-n); 72 a.p=n; 73 a.t=0; 74 memset(vis,false,sizeof(vis)); 75 vis[n]=true; 76 bfs(); 77 printf("%d\n",res); 78 } 79 return 0; 80 }