第一次提交超时:
我觉得是每次调用walk函数,每次都要构造节点,这样比较费时。还有一些细节没把控好。各位怎么看,欢迎留言~~~
// run time error
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
struct Node {
int x, step;
Node(int x, int step) : x(x), step(step) {}
};
int n, k;
int vis[100010];
Node walk(int i, Node n) {
if (i == 0) {
return Node(n.x + 1, n.step + 1);
}
else if (i == 1) {
return Node(n.x - 1, n.step + 1);
}
else
return Node(n.x * 2, n.step + 1);
}
int main() {
//freopen("input.txt", "r", stdin);
scanf("%d%d", &n, &k);
memset(vis, 0, sizeof(vis));
queue<Node> qu;
qu.push(Node(n, 0));
vis[n] = 1;
while (!qu.empty()) {
Node t = qu.front(); qu.pop();
if (t.x == k) {
printf("%d\n", t.step);
break;
}
if (t.x > 0 && !vis[t.x-1]) {
qu.push(walk(1, t));
vis[t.x-1] = 1;
}
if (!vis[t.x + 1]) {
qu.push(walk(0, t));
vis[t.x+1] = 1;
}
if (!vis[t.x * 2]) {
qu.push(walk(2, t));
vis[t.x * 2] = 1;
}
}
return 0;
}
于是我对上述的代码做了些修改,不用生成辣么多生成节点。
虽然代码比较丑但AC了(;
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn = 1e5 + 5;
struct Node {
int x, step;
};
int n, k;
int vis[maxn];
int main() {
//freopen("input.txt", "r", stdin);
scanf("%d%d", &n, &k);
memset(vis, 0, sizeof(vis));
queue<Node> qu;
Node t;
t.x = n;
t.step = 0;
qu.push(t);
vis[n] = 1;
while (!qu.empty()) {
Node temp = qu.front(); qu.pop();
if (temp.x == k) {
printf("%d\n", temp.step);
break;
}
for(int i = 0; i < 3; i++) {
if (i == 0) t.x = temp.x - 1;
else if (i == 1) t.x = temp.x + 1;
else if (i == 2) t.x = temp.x * 2;
if (t.x >= 0 && t.x < maxn && !vis[t.x]) {
t.step = temp.step+1;
qu.push(t);
vis[t.x] = 1;
}
}
}
return 0;
}