PAT甲级1008 Elevator (20分)|C++实现

tech2023-02-08  91

一、题目描述

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

二、解题思路

20分题,不难,搞清逻辑关系即可。样例中的解释:第一个数是要停的层数,后面的数就是要停的楼层。上升要6秒,下降要4秒,每个楼层停留5秒。样例中答案的计算即为: ( 2 − 0 ) × 6 + 5 + ( 3 − 2 ) × 6 + 5 + ( 3 − 1 ) × 4 + 5 = 41 (2-0)\times6+5+(3-2)\times6+5+(3-1)\times4+5 = 41 (20)×6+5+(32)×6+5+(31)×4+5=41 我这里使用了一个vector< int >来存放要停留的楼层,遍历这个vector,通过判断当前楼层与前一楼层的相对大小,决定是上升还是下降,随后利用计算公式进行计算即可。

三、AC代码

#include<iostream> #include<cstdio> #include<algorithm> #include<vector> using namespace std; int main() { vector<int> v; int N, tmp, ans = 0; scanf("%d", &N); for(int i=0; i<N; i++) { scanf("%d", &tmp); v.push_back(tmp); } ans += 6*v[0] + 5; for(int i=1; i<N; i++) { if(v[i] >= v[i-1]) ans += 6*(v[i]-v[i-1]) + 5; else ans += 4*(v[i-1]-v[i]) + 5; } printf("%d", ans); return 0; }
最新回复(0)