第一次用BFS的方法去做模拟题,值得纪念。
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int n, k;
int vis[200000];
struct node
{
int x;
int step;
};
int BFS()
{
queue <node> q;
node cur;
cur.x = n;
cur.step = 0;
q.push(cur);
while (!q.empty())
{
cur = q.front();
q.pop();
node next;
if (cur.x == k)
return cur.step;
next.x = cur.x - 1;
if (next.x >= 0 && next.x <= 100000&& !vis[next.x])
{
vis[next.x] = 1;
next.step = cur.step+1;
q.push(next);
}
next.x = cur.x + 1;
if (next.x <= 100000 && !vis[next.x])
{
next.step = cur.step+1;
vis[next.x] = 1;
q.push(next);
}
next.x = cur.x * 2;
if (next.x <= 100000 && !vis[next.x])
{
next.step = cur.step+1;
vis[next.x] = 1;
q.push(next);
}
}
return -1;
}
int main()
{
while (cin >> n >> k)
{
memset(vis,0,sizeof(vis));
int ans = BFS();
cout << ans<< endl;
}
return 0;
}