题目大意:输入两个数n,k两个数,问从n到k最少经过多少步,对于一个数x有三种走法,x-1,x+2,2*x。
思路:简单BFS,需要注意的是,先进行判断x-1,x+2,2*x是否有超出范围,再判断标记数组vis的值,不然会RE到你哭……不懂原因,读者若知道请务必留言告诉我,拜谢……
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn=200300;
int vis[maxn],N,K;
int bfs()
{
vis[N]=0;
queue<int>q;
q.push(N);
while(!q.empty())
{
int t=q.front();
q.pop();
if(t==K)return vis[K];
if(2*t<maxn && vis[2*t]==-1 )
{
vis[2*t]=vis[t]+1;
q.push(t*2);
}
if(t-1>=0 && vis[t-1]==-1 )
{
vis[t-1]=vis[t]+1;
q.push(t-1);
}
if( t+1<maxn && vis[t+1]==-1)
{
vis[t+1]=vis[t]+1;
q.push(t+1);
}
}
}
int main()
{
while(~scanf("%d%d",&N,&K))
{
memset(vis,-1,sizeof(vis));
printf("%d\n",bfs());
}
return 0;
}