Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 94444 | Accepted: 29624 |
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.
题目大意:告诉农夫和牛的初始位置,农夫要抓住牛,每次只能向左或者向右或者向乘以2的地方走,牛是不动的,问最少多少步能抓住
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
#define N 100000
int vis[N+10];//标记
struct Step{
int x;//存位置
int steps;//存步数
Step(int xx,int ss):x(xx),steps(ss){
}
};
queue<Step> q;
int main(){
int n,m;
cin>>n>>m;
memset(vis,0,sizeof(vis));
q.push(Step(n,0));
vis[n]=1;
while(!q.empty()){//BFS
Step s = q.front();
q.pop();
if(s.x==m){
cout<<s.steps<<endl;
return 0;
}
else{
if(s.x-1>=0&&!vis[s.x-1]){//向左
q.push(Step(s.x-1,s.steps+1));
vis[s.x-1]=1;
}
if(s.x+1<=N&&!vis[s.x+1]){//向右
q.push(Step(s.x+1,s.steps+1));
vis[s.x+1]=1;
}
if(s.x*2<=N&&!vis[s.x*2]){//*2
q.push(Step(s.x*2,s.steps+1));
vis[s.x*2]=1;
}
}
}
return 0;
}