hdoj 1008 - Elevator(简单数学计算)

原题链接: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(20)+5=17 秒。

样例 2:要依次去 2、3、1 楼;
0 ~ 2 楼,需要 6 ∗ ( 2 − 0 ) + 5 = 17 6*(2-0)+5=17 6(20)+5=17 秒;
2 ~ 3 楼,需要 6 ∗ ( 3 − 2 ) + 5 = 11 6*(3-2)+5=11 6(32)+5=11 秒;
3 ~ 1 楼,需要 4 ∗ ( 3 − 1 ) + 5 = 13 4*(3-1)+5=13 4(31)+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(afloor)+5 秒;
  • 如果 a < floor ,代表下楼,ans 增加 4 ∗ ( f l o o r − a ) + 5 4 * (floor - a) + 5 4(floora)+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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值