这是刚刚写bfs的时候就做过的题了,可是我居然不会写了。意识到这个问题的时候真的好崩溃F**K
本来是想按照逻辑写的,可是没有想到正确的写法,记录走的步骤需要用到结构体,表示走到这一位置至少要经过多少步
每一个走到的位置都需要记录走的步骤数,然后走到终点输出步数
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<set>
#include<queue>
#include<map>
using namespace std;
int vis[200005],cnt,ed;
struct cow
{
int pos,step;//位置还有步数
};
cow a[100005];
void bfs(int st)
{
cow start;
start.pos=st;
start.step=0;
queue<cow>q;//存放结构体的队列
while(!q.empty())q.pop();
q.push(start);
vis[st]=1;
while(!q.empty())
{
cow now=q.front(),temp;//现在的位置
q.pop();
//cout<<now.pos<<" "<<now.step<<endl;
if(now.pos==ed)
{
printf("%d\n",now.step);
break;
}
int t=now.pos;//t表示位置
if(t+1>=0&&t+1<=100000&&!vis[t+1])
{
temp.pos=t+1;
temp.step=now.step+1;//步数等于现在的步数加一
q.push(temp);
vis[t+1]=1;//标记为走过了
}
if(t-1>=0&&t-1<=100000&&!vis[t-1])
{
temp.pos=t-1;
temp.step=now.step+1;
q.push(temp);
vis[t-1]=1;
}
if(t*2>=0&&t*2<=100000&&!vis[2*t])
{
temp.pos=t*2;
temp.step=now.step+1;
q.push(temp);
vis[2*t]=1;
}
}
}
int main()
{
int st;
while(scanf("%d%d",&st,&ed)==2)
{
memset(vis,0,sizeof(vis));
bfs(st);
}
return 0;
}