点击打开链接
//一维bfs
#include <iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
const int maxn=1e5+5;
int d[maxn];
int n,k;
void bfs()
{
memset(d,-1,sizeof(d));
d[n]=0;
queue<int>pq;
pq.push(n);
while(!pq.empty())
{
int ss=pq.front();
pq.pop();
if(ss==k) return;
int le=ss-1,ri=ss+1,tro=2*ss;
if(le>=0&&le<=1e5&&d[le]==-1) { d[le]=d[ss]+1; pq.push(le); }
if(ri>=0&&ri<=1e5&&d[ri]==-1) { d[ri]=d[ss]+1; pq.push(ri); }
if(tro>=0&&tro<=1e5&&d[tro]==-1) { d[tro]=d[ss]+1; pq.push(tro); }
}
}
int main()
{
while(scanf("%d%d",&n,&k)==2)
{
bfs();
printf("%d\n",d[k]);
}
return 0;
}
POJ 3278
最新推荐文章于 2025-08-18 15:35:46 发布