只对了5个测试点,其他的都超时了。
这是代码:
#include <bits/stdc++.h>
using namespace std;
bool flag[100005];//flag数组用来标记点有没有走过
struct point{
int px, step;
};
int bfs(int x, int y) {
point p;
queue<point> q;//广搜用的队列
memset(flag, false, sizeof(flag));
flag[x] = true;
p.px = x;
p.step = 0;
q.push(p);
while (!q.empty()) {//开始广搜
p = q.front();
q.pop();
if (p.px == y)
return p.step;
if (p.px * 2 < 100005 && !flag[p.px * 2]) {
q.push((point){p.px * 2, p.step + 1});
flag[p.px * 2] = true;
}
if (p.px + 1 < 100005 && !flag[p.px + 1]) {
q.push((point){p.px + 1, p.step + 1});
flag[p.px + 1] = true;
}
if (p.px - 1 >= 0 && !flag[p.px - 1]) {
q.push((point){p.px - 1, p.step + 1});
flag[p.px - 1] = false;
}
}
return 0;
}
int t, x, y;
int main() {
cin >> t;
while (t--) {
cin >> x >> y;
cout << bfs(x, y) << endl;
}
return 0;
}
我能力有限,只能想到加一个flag数组来优化了。 请问还能对它怎么优化?