问题描述
输入
10 2 7
输出
3
代码实现
#include <iostream>
#include <queue>
using namespace std;
queue<pair<int,int> > q;
bool vis[5005];
int main()
{
int n,A,B,step,now;
cin>>n>>A>>B;
q.push(make_pair(A,0));
vis[A]=true;
while(!q.empty()){
now=q.front().first;
step=q.front().second;
q.pop();
if(now==B){
cout<<step<<endl;
break;
}
if(now+1<=n&&!vis[now+1]){
q.push(make_pair(now+1,step+1));
vis[now+1]=true;
}
if(now-1>=0&&!vis[now-1]){
q.push(make_pair(now-1,step+1));
vis[now-1]=true;
}
if(now*2<=n&&!vis[now*2]){
q.push(make_pair(now*2,step+1));
vis[now*2]=true;
}
}
return 0;
} // namespace std;