题意:
需要从给定的楼层序列中计算电梯运行时间,从背景信息中可以看出,电梯每上升一层楼耗时6s, 开门耗时5s, 下降一层楼耗时4s。注意:电梯一开始在第0层,而且不用计算电梯完成序列后返回的时间。
分析:
只需遍历输入的序列,当前楼层如果比前一次电梯停靠的楼层高的话就计算上升时间,如果低的话就计算下降时间。因为每到一层都要开门,所以可以把开门时间初始化到结果中。
代码:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
const int up=6;
const int down=4;
const int open=5;
int total=0;
int n;
cin>>n;
vector<int>list;
int temp;
while(n-->0)
{
cin>>temp;
list.push_back(temp);
}
total+=list.size()*open;
temp=0;
for(auto it=list.begin();it!=list.end();++it)
{
if(*it>temp)
{
total+=(*it-temp)*up;
}
else
{
total+=(temp-*it)*down;
}
temp=*it;
}
cout<<total;
return 0;
}