一道BFS搜索题,给你两个位置n和k,n去寻找k,走路方式有+1,-1,x2,每种操作花费一单位的时间,为最短时间到达k是多少。
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
using namespace std;
int n, k, ans;
int used[500005];
struct l{
int x;
int step;
};
bool ff(int x)
{
if(x >= 0 && x <= 500005)
return true;
return false;
}
void BFS()
{
queue<l> q;
l f, s;
f.x = n;
f.step = 0;
q.push(f);
while(!q.empty()) {
f = q.front();
q.pop();
if(f.x == k) {
ans = f.step;
return;
}
for(int i = -1; i <= 1; i++) {
if(i != 0) s.x = f.x + i;
else s.x = f.x * 2;
s.step = f.step + 1;
if(ff(s.x) && !used[s.x]) {
used[s.x] = 1;
q.push(s);
}
}
}
}
int main()
{
while(cin >> n >> k) {
ans = 0;
memset(used, 0, sizeof(used));
BFS();
cout << ans << endl;
}
return 0;
}