洛生& 2025-02-20 21:32 采纳率: 66.7%
浏览 19
已结题

奇怪的电梯(搜索)查错

奇怪的电梯
时间限制: 1.000 Sec 内存限制: 64 MB

题目描述
有一天桐桐做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼(1≤i≤N)上有一个数字K;(0≤Ki≤N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3 3 1 2 5代表了Ki (K1=3,K2=3,…),从一楼开始。在一楼,按“上,”可以到4楼,按“下”是不起作用的,因为没有-2楼。那么,从A楼到B楼至少要按几次按钮呢?
输入
第1行为三个正整数,表示N,A,B(1≤N≤200,1≤A,B≤N);
第2行为N个正整数,表示Ki。
输出
1行,即最少按键次数,若无法到达,则输出-1。
样例输入 Copy
5 1 5
3 3 1 2 5

样例输出 Copy
3
提示
上述答案得到方式如下:
从1楼按上,上到4楼
在4楼按下,到达2楼
在2楼按上,到达5楼
共3步

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int n, a, b;
int k[210];
int q[40040][3];
bool f[210];
int c[3] = { 0,-1,1 };
int head = 1, tail = 1;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> a >> b;
    for (int i = 1;i <= n;i++)
        cin >> k[i];
    q[1][1] = a;
    q[1][2] = 0;
    f[a] = true;
    if (a == b)
        cout << "0";
    int tx;
    while (head <= tail)
    {
        for (int i = 1;i <= 2;i++)
        {
            tx = q[head][1] + c[i] * k[q[head][1]];
            if (tx >= 1 && tx <= n && f[tx] == false)
            {
                tail++;
                q[tail][1] = tx;
                q[tail][2] = q[head][2] + 1;
                f[tx] = true;
                if (tx == b)
                {
                    cout << q[tail][2];
                    return 0;
                }
            }
        }
        head++;
    }
    cout << "-1";
}

能看看这段代码哪里错了啊

  • 写回答

3条回答 默认 最新

  • 码农阿豪@新空间 新星创作者: 前端开发技术领域 2025-02-20 22:36
    关注
    让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
    代码中存在一个问题:在判断是否能到达终点时,没有考虑到所有可能的情况。具体来说,应该在每一层楼判断当前楼层的上下按钮是否可用,而不仅仅是在向上或向下移动时判断。 下面是修改后的代码:
    #include <bits/stdc++.h>
    using namespace std;
    using ll = long long;
    int n, a, b;
    int k[210];
    int q[40040][3];
    bool f[210];
    int c[3] = { 0,-1, 1 };
    int head = 1, tail = 1;
    int main(){
        ios::sync_with_stdio(false);
        cin.tie(0);
        cout.tie(0);
        cin >> n >> a >> b;
        for (int i = 1; i <= n; i++)
            cin >> k[i];
        q[1][1] = a;
        q[1][2] = 0;
        f[a] = true;
        if (a == b){
            cout << "0";
            return 0;
        }
        while (head <= tail){
            for (int i = 0; i <= 2; i++){
                int tx = q[head][1] + c[i] * k[q[head][1]];
                if (tx >= 1 && tx <= n && !f[tx]){
                    tail++;
                    q[tail][1] = tx;
                    q[tail][2] = q[head][2] + 1;
                    f[tx] = true;
                    if (tx == b){
                        cout << q[tail][2];
                        return 0;
                    }
                }
            }
            head++;
        }
        cout << "-1";
    }
    

    这样修改后的代码会正确地判断所有情况,保证能够找到最少按键次数。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月1日
  • 已采纳回答 2月21日
  • 创建了问题 2月20日