原题链接:Problem - 1008
题目描述
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.
输入格式
There are multiple test cases. Each case contains a positive integer N, followed by N positive numbers. All the numbers in the input are less than 100. A test case with N = 0 denotes the end of input. This test case is not to be processed.
输出格式
Print the total time on a single line for each test case.
输入样例
1 2
3 2 3 1
0
输出样例
17
41
题意
在大楼里有一部电梯,它上一层楼需要花费 6 秒,下一层楼需要花费 4 秒,到达某层楼开门时会停留 5 秒。现在给定一个请求队列,表示电梯依次要去哪些楼层,计算总共需要花费多少时间。已知电梯的初始位置是 0 层楼,最后不必返回初始位置。
样例解释
样例 1:要去 2 楼,需要 6 ∗ ( 2 − 0 ) + 5 = 17 6*(2-0)+5=17 6∗(2−0)+5=17 秒。
样例 2:要依次去 2、3、1 楼;
0 ~ 2 楼,需要
6
∗
(
2
−
0
)
+
5
=
17
6*(2-0)+5=17
6∗(2−0)+5=17 秒;
2 ~ 3 楼,需要
6
∗
(
3
−
2
)
+
5
=
11
6*(3-2)+5=11
6∗(3−2)+5=11 秒;
3 ~ 1 楼,需要
4
∗
(
3
−
1
)
+
5
=
13
4*(3-1)+5=13
4∗(3−1)+5=13 秒;
总共需要
17
+
11
+
13
=
41
17+11+13=41
17+11+13=41 秒。
解题思路
定义变量 ans
,代表总共需要的时间,初值为 0;变量 floor
代表当前在第几层楼,初值为 0,变量 a
代表接下来将要去那一层楼。
对于每一组测试用例,循环读入 a
,并与当前楼层号 floor
进行比较:
- 如果
a > floor
,代表上楼,ans
增加 6 ∗ ( a − f l o o r ) + 5 6 * (a - floor) + 5 6∗(a−floor)+5 秒; - 如果
a < floor
,代表下楼,ans
增加 4 ∗ ( f l o o r − a ) + 5 4 * (floor - a) + 5 4∗(floor−a)+5 秒; - 如果
a == floor
,代表仍然在此层停留,ans
增加 5 秒(可以合并到上面任一种情况中)。
程序代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(cin >> n)
{
if(n == 0) break;
int ans = 0;
int floor = 0;
int a;
while(n--)
{
cin >> a;
if(a > floor)
ans += 6 * (a - floor) + 5;
else
ans += 4 * (floor - a) + 5;
floor = a;
}
cout << ans << endl;
}
return 0;
}