Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 36079 | Accepted: 11123 |
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
Output
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.
【题目来源】
#include<iostream> #include<cstring> #include<queue> using namespace std; int N,K; struct now { int x; int step; }; bool vis[1000010]; int BFS(int x) { int tx; now ans,tp; queue<now> que; ans.x=x,ans.step=0; vis[x]=true; que.push(ans); while(!que.empty()) { tp=que.front(); que.pop(); tx=tp.x+1; //no.1 if(tx<0||tx>1000000); else { if(!vis[tx]) { vis[tx]=true; ans.x=tx,ans.step=tp.step+1,que.push(ans); if(ans.x==K) return ans.step; } } tx=tp.x-1; //no.2 if(tx<0||tx>1000000); else { if(!vis[tx]) { vis[tx]=true; ans.x=tx,ans.step=tp.step+1,que.push(ans); if(ans.x==K) return ans.step; } } tx=tp.x*2; //no.3 if(tx<0||tx>1000000); else { if(!vis[tx]) { vis[tx]=true; ans.x=tx,ans.step=tp.step+1,que.push(ans); if(ans.x==K) return ans.step; } } } } int main() { while(cin>>N>>K) { if(N==K) { cout<<"0"<<endl; continue; } memset(vis,false,sizeof(vis)); cout<<BFS(N)<<endl; } return 0; }
当然还可以剪枝一下,比如说:如果人的坐标大于牛的坐标,这时就只需要做-1这一步就可以了。