简单的bfs,访问记录,队列实现
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
int pos;
int step;
};
queue<node> q;
int v[120000];
bool judge(node n)
{
if (n.pos < 0 || n.pos > 100000)
return false;
if (v[n.pos] == 1)
return false;
return true;
}
int main()
{
int n,k;
node s,t,tn;
scanf("%d%d",&n,&k);
while (!q.empty())
q.pop();
memset(v,0,sizeof(v));
s.pos=n;
s.step=0;
q.push(s);
v[n]=1;
while (1)
{
t=q.front();
q.pop();
if (t.pos == k)
{
break;
}
tn.pos=t.pos-1;
tn.step=t.step+1;
if (judge(tn))
{
v[tn.pos]=1;
q.push(tn);
}
tn.pos=t.pos+1;
tn.step=t.step+1;
if (judge(tn))
{
v[tn.pos]=1;
q.push(tn);
}
tn.pos=t.pos*2;
tn.step=t.step+1;
if (judge(tn))
{
v[tn.pos]=1;
q.push(tn);
}
}
printf("%d\n",t.step);
}