考虑广搜,枚举x可以走的每一步,什么时候到了y就输出答案。可以用时间戳记录是否用过没。
参考代码
#include <bits/stdc++.h>
using namespace std;
queue<int> q;
const int maxn = 1000000;
int dis[maxn];
int main() {
int t;
int x, y;
cin >> x >> y;
// dis[x]=0;
q.push(x);
while (!q.empty()) {
t = q.front();
q.pop();
if (t == y) {
printf("%d\n", dis[y]);
return 0;
}
if (t + 1 <= maxn && !dis[t + 1] && t + 1 != x)
dis[t + 1] = dis[t] + 1, q.push(t + 1);
if (t - 1 >= 0 && !dis[t - 1] && t - 1 != x)
dis[t - 1] = dis[t] + 1, q.push(t - 1);
if (t * 2 <= maxn && !dis[2 * t] && 2 * t != x)
dis[t * 2] = dis[t] + 1, q.push(t * 2);
// for(int i=0;i<=17;i++)cout<<dis[i]<<" ";
// cout<<endl;
}
return 0;
}