题目链接:点击打开链接
代码:
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
#include<queue>
struct qq
{
int x,y;
} w;
queue<qq >q;
int k;
int e[200010];
void dfs(int n)
{
w.x=n;
w.y=0;
while(!q.empty())
{
q.pop();
}
q.push(w);
while(!q.empty())
{
qq n1=q.front();
q.pop();
for(int i=0; i<3; i++)
{
qq n2;
if(i==0)
n2.x=n1.x*2;
else if(i==1)
n2.x=n1.x-1;
else
n2.x=n1.x+1;
if(n2.x<0||n2.x>100000||e[n2.x])
continue;
n2.y=n1.y+1;
e[n2.x]=1;
if(n2.x==k)
{
printf("%d\n",n2.y);
return ;
}
q.push(n2);
}
}
return ;
}
int main()
{
int n;
scanf("%d%d",&n,&k);
if(n==k)
printf("0\n");
else if(n>k)
printf("%d\n",n-k);
else
{
memset(e,0,sizeof(e));
e[n]=1;
dfs(n);
}
return 0;
}
简单题