PAT (Advanced Level) Practice 1008 Elevator

电梯路径时间计算
本文介绍了一个简单的算法问题,即计算电梯在给定楼层列表中移动所需的总时间。考虑到上升、下降及停留时间,通过计算升降楼层数来得出总耗时。

题目如下:

The highest building in our city has only one elevator. A request list is made up with 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, followed by 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

题目的意思很简单,一栋大厦只有一台电梯,需要计算电梯在给定的路线下耗费的时间,上升一个楼层耗时6s,下降一个耗时4s,停留时间为5s,题目中的案例正好是41s。
思路也很简单,将上升和下降的楼层数求出来乘以相对应的时间得到的和就是答案,这里用到了前两天刚看到的一个pair,正好熟悉一下pair的使用方法,下面是代码:
 1 #include <iostream>
 2 
 3 using namespace std;
 4 pair<int,int> compu(int a[],int n){
 5     int raise=0,down=0;         //上升、下降的楼层
 6     for(int i = 1; i <= n; i++){
 7         if(a[i]-a[i-1] > 0) raise += a[i]-a[i-1];
 8         else down += a[i]-a[i-1];
 9     }
10     return make_pair(raise,-down);
11 }
12 int floor[101] = {0};
13 int main()
14 {
15     pair<int,int> x;
16     int n;
17     cin >> n;
18     for(int i = 1; i <= n; i++){
19         cin >> floor[i];
20     }
21     x = compu(floor,n);
22     int sum = 0;
23     sum += 6*x.first + 5*n + 4*x.second;
24     cout << sum;
25     return 0;
26 }

比较简单,其中的pair用法不是那么熟练,感觉用到的机会还是挺多的,可以简单学习一下。

 

 

题目地址:https://pintia.cn/problem-sets/994805342720868352/problems/994805511923286016

转载于:https://www.cnblogs.com/huhusw/p/9350838.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值