# 计蒜客–一维坐标的移动

1001-高同学

#include <iostream>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
int n,m;
struct Point
{
int x,step;
Point(int _x,int _step):
x(_x),step(_step) {}
};
int main()
{
int n,a,b;
cin>>n>>a>>b;
queue<Point>q;
q.push(Point(a,0));
if(a>b)
{
cout<<a-b<<endl;
return 0;
}
if(a==b)
{
cout<<0<<endl;
return 0;
}
int cnt = 0;
while(!q.empty())
{
int x = q.front().x;
int step = q.front().step;
q.pop();

if(x == b)
{
cnt = step;
break;
}
if(x+1 <= n && a<b)
{
//cout<<1<<" "<<x<<endl;
q.push(Point(x+1,step+1));
}
if(x*2 <=n && a<b)
{
//cout<<3<<endl;
q.push(Point(x*2,step+1));
}
}
//cout<<"cnt="<<cnt<<endl;
while(!q.empty())
q.pop();
q.push(Point(a,0));
while(!q.empty())
{
int x = q.front().x;
int step = q.front().step;
q.pop();
//cout<<step<<endl;
if(x == b)
{
if(cnt > step)
{
cnt = step;
}
break;
}

if(step > cnt)
break;
if(x-1 >=0)
{
q.push(Point(x-1,step+1));
}
if( x*2 == b )
{
q.push(Point(x*2,step+1));
}
if( x*2+1 == b )
{
q.push(Point(x*2+1,step+1));
}
}
cout<<cnt<<endl;
return 0;
}


Vieu3.3主题

Q Q 登 录