给N给K 有三种操作 N+1 N-1 N*2 让N==K 输出步骤数
宽搜。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n,k;
struct node
{
int deep; //记录步骤数
int w; //记录数值
}queue[1000005];
int vis[1000005];
int main()
{
while(scanf("%d%d",&n,&k)!=EOF)
{
int head=0,tail=0;
memset(vis,0,sizeof(vis));
vis[n]=1;
queue[tail].deep=0;
queue[tail++].w=n;
while(head < tail)
{
node t = queue[head++];
if(t.w == k)
{
printf("%d\n",t.deep);
break;
}
if(t.w-1 >= 0 && !vis[t.w-1])
{
queue[tail].w = t.w-1;
queue[tail++].deep = t.deep+1;
vis[t.w-1]=1;
}
if(t.w <= k && !vis[t.w*2])
{
queue[tail].w = t.w*2;
queue[tail++].deep = t.deep+1;
vis[t.w*2]=1;
}
if(t.w <=k && !vis[t.w+1])
{
queue[tail].w = t.w+1;
queue[tail++].deep = t.deep+1;
vis[t.w+1]=1;
}
}
}
return 0;
}