广度优先对于求最短路劲是非常有效的
#include <iostream>
#include <queue>
#define SIZE 100001
using namespace std;
queue<int> x;
bool visited[SIZE];
int step[SIZE];
int bfs(int n, int k)
{
int head, next;
//起始节点入队
x.push(n);
//标记n已访问
visited[n] = true;
//起始步数为0
step[n] = 0;
//队列非空时
while (!x.empty())
{
//取出队头
head = x.front();
//弹出队头
x.pop();
//3个方向搜索
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 > SIZE || next < 0)
continue;
//判重
if (!visited[next])
{
//节点入队
x.push(next);
//步数+1
step[next] = step[head] + 1;
//标记节点已访问
visited[next] = true;
}
//找到退出
if (next == k)
return step[next];
}
}
return 0;
}
int main()
{
int n, k;
cin >> n >> k;
if (n >= k)
cout << n - k << endl;
else
cout << bfs(n, k) << endl;
return 0;
}