#include<iostream>
#include<queue>
using namespace std;
#define M 100001
#define INF 10000000
struct POINT
{
int pos;
int step;
} now, next;
int n, k;
queue<POINT>Q;
bool visited[M];
int main()
{
int bfs();
while (cin >> n >> k)
{
memset(visited, false, sizeof(visited));
if (n < k) cout << bfs() << endl;
if (n == k) cout << 0 << endl;
if (n > k) cout << n - k << endl;
}
return 0;
}
int bfs()
{
while (!Q.empty())
Q.pop();
now.pos = n;
now.step = 0;
visited[now.pos] = true;
Q.push(now);
while (!Q.empty())//队列非空
{
now = Q.front();
Q.pop();//队列首元素出站
next = now;
for (int i = 0; i < 3; i++)
{
if (i == 0) //前进1步
next.pos = now.pos + 1;
if (i == 1) //后退1步
next.pos = now.pos - 1;
if (i == 2) //前进2倍
next.pos = now.pos * 2;
next.step = now.step + 1;//总步数
if (next.pos == k) //抓住了
return next.step;//返回步数
if (next.pos < 0 || next.pos > M)
continue;//越界 跳出
if (!visited[next.pos])//未访问这个状态
{
visited[next.pos] = true;//标记
Q.push(next);//入队列
}
}
}
}
HDU 3278 Catch That Cow(简单bfs)
最新推荐文章于 2020-06-25 23:35:05 发布