✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1008 Elevator (pintia.cn)
🔑中文翻译:电梯
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
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
- 1
Sample Output:
41
- 1
给定一个列表,记录着电梯需要一次到达的楼层,已知电梯上升一层需要 6
秒,下降一层需要 4
秒,在每层停留的时间为 5
秒,从第 0
层开始,需要计算电梯总花费时间。
注意:电梯可能在一层停留多次,每停留一次都要加 5
秒。
具体思路如下:
pre = 0
即电梯从第 0
层开始,且 cur
表示当前遍历到的楼层,以及 res
用来保存电梯总花费时间。cur
都计算一次花费的时间,如果上升就用 6
乘以上升楼层, 下降就用 4
乘以下降楼层,最后再加上楼层停留的时间 5
秒。res
。#include
using namespace std;
int main()
{
int n, pre = 0, cur, res = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> cur;
if (cur > pre) res += 6 * (cur - pre); //上升时间
else if (cur < pre) res += 4 * (pre - cur); //下降时间
res += 5; //停留时间
pre = cur;
}
cout << res << endl;
return 0;
}