尽管简单,但是忘了写边界条件,翻车了,记录一下。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e7 + 10;
int t, x, y;
struct node {
int x, step; // 一定得有这个step属性,步数连带着走
node(int x_, int step_) {
x = x_;
step = step_;
}
};
queue<node> qq;
int vis[N];
int bfs(int start, int end) {
// reset
while (!qq.empty()) {
qq.pop();
}
for (int i = 0; i < N; i++) {
vis[i] = 0;
}
qq.push(node(start, 0));
vis[start] = 1;
while (!qq.empty()) {
node f = qq.front();
qq.pop();
if (f.x == end) {
return f.step;
}
if (f.x+1 >= 0 && f.x+1 <= 1e5 && !vis[f.x+1]) {
qq.push(node(f.x+1, f.step+1));
vis[f.x+1] = 1;
}
if (f.x-1 >= 1 && f.x-1 <= 1e5 && !vis[f.x-1]) {
qq.push(node(f.x-1, f.step+1));
vis[f.x-1] = 1;
}
if (2*f.x >= 0 && 2*f.x <= 1e5 && !vis[2*f.x]) {
qq.push(node(2*f.x, f.step+1));
vis[2*f.x] = 1;
}
}
}
int main() {
cin >> t;
for (int i = 0; i < t; i++) {
cin >> x >> y;
cout << bfs(x, y) << endl;
}
return 0;
}