新建的思源楼高达200层,构成了交大新的地标。楼里面有一部可以通达所有楼层的电梯,每上一层楼需要 u秒钟,下一层楼需要d秒,每个楼层会停s秒。目前电梯在第 N(1≤N≤200)层的地面上。若某个楼层没有上下需求,则电梯运行中会跳过该楼层。电梯沿某个方向运行到该方向最后一个需要上下人的楼层后,若下方或上方没有请求但另一方方向有用梯需求,则转向运行。若电梯不需要上下运行,则会忽略该请求。 现有若干个楼层需要上下人,则满足这些请求最少需要耗费多长时间(包括最后的停留时间)?用c++写
时间: 2024-03-09 18:51:00 浏览: 45
以下是一个简单的C++代码示例,用于找到满足所有请求的最小时间:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, u, d, s;
cin >> n >> u >> d >> s;
vector<int> floors(n);
vector<int> up(n);
vector<int> down(n);
for (int i = 0; i < n; i++) {
cin >> floors[i];
cin >> up[i];
cin >> down[i];
}
int time = 0;
int curr_floor = floors[0];
int curr_dir = 1;
int next_floor = -1;
while (true) {
// look for next floor with requests
next_floor = -1;
for (int i = 0; i < n; i++) {
if (up[i] > 0 || down[i] > 0) {
if (floors[i] == curr_floor) {
next_floor = floors[i];
break;
}
else if (floors[i] > curr_floor && curr_dir == 1) {
next_floor = floors[i];
}
else if (floors[i] < curr_floor && curr_dir == -1) {
next_floor = floors[i];
}
}
}
// if no next floor, check for requests in other direction
if (next_floor == -1) {
curr_dir *= -1;
for (int i = 0; i < n; i++) {
if (up[i] > 0 || down[i] > 0) {
if (floors[i] == curr_floor) {
next_floor = floors[i];
break;
}
else if (floors[i] > curr_floor && curr_dir == 1) {
next_floor = floors[i];
}
else if (floors[i] < curr_floor && curr_dir == -1) {
next_floor = floors[i];
}
}
}
}
// if still no next floor, we are done
if (next_floor == -1) {
break;
}
// move to next floor
int travel_time = (next_floor - curr_floor) * (curr_dir == 1 ? u : d);
time += travel_time;
// update requests and direction
if (curr_dir == 1) {
up[floor_to_index[next_floor]] = 0;
} else {
down[floor_to_index[next_floor]] = 0;
}
curr_floor = next_floor;
curr_dir = 1;
// wait at current floor
time += s;
}
cout << time << endl;
return 0;
}
```
这个程序会读入楼层数量 `n`,上升和下降的时间 `u` 和 `d`,以及停留时间 `s`。然后,它会读取每个楼层的需求,并使用贪心算法找到最小时间。最后输出所需的总时间。