# 广度优先搜索，队列实现

#include<math.h>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<cmath>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<cmath>
//#define maxn 100000
using namespace std;
const int maxn=100005;
int n,m;
int visit[maxn+10];
struct node
{
int x;
int step;
};

int bfs()
{
memset(visit,0,sizeof(visit));
queue<node>q;
node now,next;
结构体变量

now.x=n;
now.step=0;
q.push(now);这个很重要
visit[now.x]=1;
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0; i<3; i++)
{
if(i==0)
next.x=now.x-1;
else if(i==1)
next.x=now.x+1;
else
next.x=now.x*2;
next.step=now.step+1;先输入再输出
if(now.x==m)
return now.step;
if(next.x>=0&&next.x<=maxn&&!visit[next.x])
{
q.push(next);
visit[next.x]=1;
}
}
}
return 0;
}

int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==m)
printf("0\n");
else
{
int i,j;
int g=bfs();
printf("%d\n",g);
}
}
return 0;
}

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客