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

猜你喜欢

转载自www.cnblogs.com/huhusw/p/9350838.html