题意:在同一行,由n到达k,有三种操作,每种操作花费1分钟:x+1,x-1,x*2。求所需最小时间。
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<queue>
#include<iostream>
#define M 100100
using namespace std;
bool vis[M];
int step[M];
queue<int> q;
int bfs(int n,int k)
{
int head,next;
q.push(n);
vis[n]=true;
step[n]=0;
while (!q.empty())
{
head = q.front();
q.pop();
for (int i=0;i<3;i++)//三种操作
{
if (i==0)
next = head - 1;
else if (i==1)
next = head + 1;
else
next = head * 2;
if (next > M|| next < 0 || vis[next])//超过边界或已访问
continue;
if (!vis[next])//未访问
{
q.push(next);
step[next]= step[head] + 1;//当前路径数
vis[next] = true;
}
if (next==k)//到达k
return step[next];
}
}
}
int main()
{
int n, k;
scanf("%d%d",&n,&k);
if (n >= k)
printf ("%d\n",n-k);
else
printf("%d\n",bfs(n,k));
return 0;
}