思路
bfs() + 结构体queue (包含queue头文件)
queue:
1. empty()
2. size()
3. push()
4. pop()
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
struct pos
{
int x, step;
};
queue<pos> q;
int n, k;
bool vis[N];
void bfs()
{
while(!q.empty())
q.pop();
pos now, nxt;
now.x = n;
now.step = 0;
q.push(now);
while(q.size())
{
now = q.front();
q.pop();
vis[now.x] = 1;
if(now.x == k)
{
cout << now.step << endl;
return ;
}
for(int i = 1; i <= 3; i ++ )
{
if(i == 1)
nxt.x = now.x + 1;
if(i == 2)
nxt.x = now.x - 1;
if(i == 3)
nxt.x = now.x * 2;
if(nxt.x < 0 || nxt.x > N || vis[nxt.x])
continue;
vis[nxt.x] = 1;
nxt.step = now.step + 1;
q.push(nxt);
}
}
}
int main()
{
while(cin >> n >> k)
{
memset(vis, 0, sizeof vis);
if(n >= k)
cout << n - k << endl;
else
bfs();
}
return 0;
}