题解
【基础】奇怪的电梯
2 条题解
-
0
1. 解题思路
把楼层看作图的顶点,按一次按键一条边做广度优先搜索。从起点入队,分别尝试当前楼层加减Ki;首次到达合法且未访问的楼层时,记录前一层距离加1并入队。
2. 坑点和注意事项
楼层编号始终是1到N,能为0的是楼层上标记的跳跃数Ki。入队时就记录距离,Ki为0也不会重复进入同一楼层;起点等于终点答案为0,不能到达时保留−1。N≤200,普通数组队列能保存全部楼层。
3. 复杂度
- 时间复杂度:O(n),每个楼层最多入队一次,每次检查两个方向。
- 空间复杂度:O(n),保存跳跃数、距离和普通数组队列。
/* 思路:用广度优先搜索逐层扩展向上或向下能够到达的楼层。 关键:每次按键代价相同,首次访问即得到最短步数。 坑点:楼层数字可以为0,必须入队时标记,不能反复加入同一楼层。 时间复杂度:O(n)。 空间复杂度:O(n);最多200层,普通数组队列不使用queue。 */ #include <bits/stdc++.h> using namespace std; int a[201], d[201], q[200]; int main() { int n, x, y; cin >> n >> x >> y; for (int i = 1; i <= n; i++) { cin >> a[i]; d[i] = -1; } int h = 0, t = 1; q[0] = x; d[x] = 0; while (h < t) { int u = q[h++]; for (int i = -1; i <= 1; i += 2) { int v = u + i * a[u]; // 入队时记录距离,每层至多入队一次,零跳跃也不会死循环。 if (v >= 1 && v <= n && d[v] == -1) { d[v] = d[u] + 1; q[t++] = v; } } } cout << d[y] << endl; return 0; } -
0
#include <bits/stdc++.h> using namespace std; long long n, a, b; long long c[210]; bool f [330]; struct s{ long long floor; long long step; }; void bfs (){ queue <s> p; s temp; temp.floor = a; temp.step = 0; p.push (temp); while (!p.empty()){ s now = p.front (); long long floor = now.floor, step = now.step; long long sh = floor + c[floor], xi = floor - c[floor]; p.pop (); if (floor == b){ cout << step; return ; } if (sh >= 1 && sh <= n && !f[sh]){ f[sh] = true; s temp; temp.floor = sh; temp.step = step + 1; p.push (temp); } if (xi >= 1 && xi <= n && !f[xi]){ f[xi] = true; s temp; temp.floor = xi; temp.step = step + 1; p.push (temp); } } cout << -1; return ; } int main(){ cin >> n >> a >> b; for (int i=1;i<=n;i++){ cin >> c[i]; } if (a == b){ cout << 0; return 0; } bfs (); return 0; }
- 1