1008 Elevator【PAT (Advanced Level) Practice】

1008 Elevator【PAT (Advanced Level) Practice】

原题链接:预览题目详情 - 1008 Elevator (pintia.cn)

1.题目原文

The highest building in our city has only one elevator. A request list is made up with N N N positive numbers. The numbers denote at which floors the elevator will stop, in specified order. It costs 6 seconds to move the elevator up one floor, and 4 seconds to move down one floor. The elevator will stay for 5 seconds at each stop.

For a given request list, you are to compute the total time spent to fulfill the requests on the list. The elevator is on the 0th floor at the beginning and does not have to return to the ground floor when the requests are fulfilled.

Input Specification:

Each input file contains one test case. Each case contains a positive integer N N N, followed by N N N positive numbers. All the numbers in the input are less than 100.

Output Specification:

For each test case, print the total time on a single line.

Sample Input:

3 2 3 1

Sample Output:

41

2. 题目翻译

这个城市最高的建筑只有一部电梯。一个请求列表由 N N N个正整数组成。这些数字表示电梯将在指定顺序停靠的楼层。每上升一层需要6秒,每下降一层需要4秒。电梯在每个停靠点停留5秒。

对于给定的请求列表,你需要计算完成列表上的请求所花费的总时间。电梯在开始时位于第0层,并且在完成请求时不必返回到底层。

输入规范:

每个输入文件包含一个测试用例。每个案例包含一个正整数 N N N,后面跟着 N N N个正整数。输入中的所有数字均小于100。

输出规范:

对于每个测试用例,在一行上输出总时间。

示例输入:

3 2 3 1

示例输出:

41

3.解题思路

3.1题目分析

计算电梯按照给定请求列表移动所需的总时间。

3.2基本思路

模拟电梯在每个楼层的停留和移动过程,并根据上升或下降的方向计算时间,最终得到电梯完成请求列表所需的总时间。

3.3详解步骤

  1. 初始化变量: 初始化电梯所在楼层 f 为0,总时间 time 为0。

  2. 遍历请求列表: 对于每个请求,读取楼层信息 fi

  3. 计算电梯移动楼层数: 计算电梯移动的楼层数,即 f -= fi

  4. 计算时间: 根据电梯是上升还是下降,分别计算上升或下降所需的时间,并将其加到总时间 time 中。

    • 如果 f 小于0,表示电梯在上升,计算上升时间 (5 - f * 6)
    • 如果 f 大于等于0,表示电梯在下降,计算下降时间 (5 + f * 4)
  5. 更新电梯所在楼层: 更新电梯所在楼层 f 为当前请求的楼层 fi

  6. 输出结果: 打印总时间 time

4.参考答案

#include <stdio.h>
#include <math.h>

int main() {
    
    
    int n, fi, f, time; // n: 请求列表中的元素数量, fi: 当前请求的楼层, f: 当前电梯所在的楼层, time: 记录总时间
    int i; // 循环计数器

    scanf("%d", &n);

    f = 0; // 初始电梯楼层为0
    time = 0; // 初始总时间为0
    
    for (i = 0; i < n; i++) {
    
    
        scanf("%d", &fi); // 读取请求列表中的楼层
        
        f -= fi; // 计算电梯移动的楼层数(上升为负数,下降为正数)
        
        if (f < 0)
            time += (5 - f * 6); // 电梯上升,计算上升所需时间
        else
            time += (5 + f * 4); // 电梯下降,计算下降所需时间
        
        f = fi; // 更新电梯所在楼层
    }

    printf("%d\n", time); // 输出总时间

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40171190/article/details/134754808