[关闭]
@guxier 2022-03-24T13:11:58.000000Z 字数 1867 阅读 398

洛谷-P1135 奇怪的电梯

洛谷


原题链接

题目描述

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第 iii 层楼(1≤i≤N1 \le i \le N1≤i≤N)上有一个数字 KiK_iKi​(0≤Ki≤N0 \le K_i \le N0≤Ki​≤N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如: 3,3,1,2,53, 3, 1, 2, 53,3,1,2,5 代表了 KiK_iKi​(K1=3K_1=3K1​=3,K2=3K_2=3K2​=3,……),从 111 楼开始。在 111 楼,按“上”可以到 444 楼,按“下”是不起作用的,因为没有 −2-2−2 楼。那么,从 AAA 楼到 BBB 楼至少要按几次按钮呢?

输入格式

共二行。

第一行为三个用空格隔开的正整数,表示

第二行为 NNN 个用空格隔开的非负整数,表示 ​。

输出格式

一行,即最少按键次数,若无法到达,则输出 -1。

输入输出样例

输入 #1
  1. 5 1 5
  2. 3 3 1 2 5
输出 #1
  1. 3
说明/提示

对于 的数据,


算法1

(DFS)

结果

C++ 代码

  1. #include <bits/stdc++.h>
  2. #define ios ios::sync_with_stdio(false), cin.tie(0)
  3. #define rep(i, a, n) for (int i = a; i <= n; i++)
  4. #define per(i, a, n) for (int i = n; i >= a; i--)
  5. #define debug(x) cout << #x << ": " << x << endl
  6. #define MOD 1000000007
  7. #define INF 0x3f3f3f3f
  8. typedef long long LL;
  9. using namespace std;
  10. const int N = 1e3 + 10;
  11. int n , a, b, m[N];
  12. bool st[N];
  13. int ans = INF;
  14. void dfs(int i ,int sum)
  15. {
  16. if(i == b) ans = min(sum, ans);
  17. if(sum > ans) return ;
  18. st[i] = true;
  19. if(i + m[i] <= n && !st[i + m[i]])
  20. dfs(i + m[i], sum + 1);
  21. if(i - m[i] >= 1 && !st[i - m[i]])
  22. dfs(i - m[i] , sum + 1);
  23. st[i] = false; //回溯
  24. }
  25. int main()
  26. {
  27. cin >> n >> a >> b;
  28. rep(i, 1, n)
  29. cin >> m[i];
  30. st[a] = true;
  31. dfs(a, 0);
  32. if(ans == INF) cout << -1;
  33. else cout << ans;
  34. return 0;
  35. }

算法2

(BFS)

结果

C++ 代码

  1. #include <bits/stdc++.h>
  2. #define ios ios::sync_with_stdio(false), cin.tie(0)
  3. #define rep(i, a, n) for (int i = a; i <= n; i++)
  4. #define per(i, a, n) for (int i = n; i >= a; i--)
  5. #define debug(x) cout << #x << ": " << x << endl
  6. #define MOD 1000000007
  7. #define INF 0x3f3f3f3f
  8. typedef long long LL;
  9. using namespace std;
  10. const int N = 1e3 + 10;
  11. int n , a, b, ans = INF , m[N];
  12. bool st[N];
  13. queue<int> qx , qstep; //qx存储当前楼层 qstep存储按键次数
  14. void bfs()
  15. {
  16. while(!qx.empty())
  17. {
  18. int x = qx.front();
  19. int t = qstep.front();
  20. qx.pop(); qstep.pop();
  21. if(x == b) ans = min(t, ans);
  22. if(x + m[x] <= n && !st[x + m[x]])
  23. {
  24. qx.push(x + m[x]);
  25. qstep.push(t + 1);
  26. st[x + m[x]] = true;
  27. }
  28. if(x - m[x] >= 1 && !st[x - m[x]])
  29. {
  30. qx.push(x - m[x]);
  31. qstep.push(t + 1);
  32. st[x - m[x]] = true;
  33. }
  34. }
  35. }
  36. int main()
  37. {
  38. cin >> n >> a >> b;
  39. rep(i, 1, n)
  40. cin >> m[i];
  41. qx.push(a);
  42. qstep.push(0);
  43. bfs();
  44. if(ans == INF) cout << -1;
  45. else cout << ans;
  46. return 0;
  47. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注