CCF NOI1078. 奇怪的电梯 (C++)

本文解析了一道名为奇怪的电梯的算法题,该题要求计算从A楼到B楼最少的按钮按压次数。电梯只能向上或向下移动等于当前楼层上的数字的层数,且有开、关、上、下四个按钮。通过递归方法解决此问题,并提供了一个C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1078. 奇怪的电梯

题目描述

大楼的每一层楼都可以停电梯,而且第i层楼(1<=i<=N)上有一个数字Ki(0<=Ki<=N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3 3 1 2 5代表了Ki(K1=3,K2=3,……),从一楼开始。在一楼,按“上”可以到4楼,按“下”是不起作用的,因为没有-2楼。那么,从A楼到B楼至少要按几次按钮呢?

输入

输入文件共有二行,第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N),第二行为N个用空格隔开的正整数,表示Ki。

输出

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

样例输入

5 1 5
3 3 1 2 5

样例输出

3

数据范围限制

C++代码

#include <iostream>
#include <cassert>

using namespace std;
    
const int max_N = 200;
int KiArray[max_N+1];
const int max_num_of_pressing_buttons = 200; // ??

int takeStrangeElevator(int fromFloor, int toFloor, int numOfPressingButtons);
    
int main()
{
    int N, A, B;

    cin >> N >> A >> B;

    assert(N>=1 && N<=max_N);
    assert(A>=1 && A<=N);
    assert(B>=1 && B<=N);

    for(int i=1; i<=N; i++)
    {
        cin >> KiArray[i];
        assert(KiArray[i]>=0 && KiArray[i]<=N);
    }

    int result = takeStrangeElevator(A, B, 0);
    cout << result << endl;

    return 0;
}

int takeStrangeElevator(int fromFloor, int toFloor, int numOfPressingButtons)
{
    if (numOfPressingButtons > max_num_of_pressing_buttons)
    {
        return -1;
    }
    else if (fromFloor == toFloor)
    {
        return 0;
    }
    else if ((fromFloor+KiArray[fromFloor] == toFloor) || 
             (fromFloor-KiArray[fromFloor] == toFloor))
    {
        return numOfPressingButtons+1;
    }
    else
    {   
        if (fromFloor+KiArray[fromFloor] < toFloor)     // Press Button UP
        {
            fromFloor += KiArray[fromFloor];
        }
        else if(fromFloor+KiArray[fromFloor] > toFloor) // Press Button DOWN
        {
            fromFloor -= KiArray[fromFloor];
        }

        // use recursive method to continue next button: UP or DOWN
        (void)takeStrangeElevator(fromFloor, toFloor, numOfPressingButtons+1);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值