c++有一个有n(1<n<105)个人的队伍,其中第i个人需要t[i](1<t[i]<109)分钟来服务,期间后面的人就要等着。如果一个人等待的时间大于了他被服务的时间,他就会失望。你的任务是重排队伍,使失望的人尽量的少,并只需输出不失望的人的数量的最大值(使用优先队列完成)
时间: 2024-11-17 11:30:00 浏览: 28
在C++中,你可以通过优先级队列(Priority Queue)来解决这个问题,这通常被称为“最短剩余时间”(Shortest Processing Time, SPT)调度算法,也称为贪心策略。这里是一个基本的步骤:
1. **数据结构选择**:使用`std::priority_queue`,它默认按照元素的值降序排列,非常适合处理这个场景,因为我们需要尽快服务等待时间最长的人。
2. **初始化**:创建一个优先队列,将每个人(表示为一个包含服务时间和索引的结构体或pair)加入队列。同时,设置一个变量`maxSatisfied`记录当前满足条件的人数,即服务时间小于等于等待时间的人。
3. **处理过程**:
- 从队列头部取出服务时间最短的人(等待时间最长),并更新`maxSatisfied`,如果这个人服务完之后他的等待时间仍然小于他被服务的时间,则加一。
- 如果这个人服务时间大于其等待时间,说明他的等待已经超过了服务,这时`maxSatisfied`保持不变,直接移除这个人。
- 然后将下一个等待时间最长的人加入队列,继续循环直到队列为空。
4. **结果返回**:最后返回`maxSatisfied`作为满足条件的人数的最大值。
```cpp
#include <queue>
using namespace std;
struct Person {
int serviceTime;
int index;
};
int minDisappointed(vector<int>& t, priority_queue<pair<int, int>>& pq) {
int maxSatisfied = 0;
for (int i = 0; i < t.size(); ++i) {
pq.push({t[i], i});
while (!pq.empty() && pq.top().first <= pq.top().second) {
pq.pop();
if (i - pq.top().second > pq.top().first) {
// 满足条件,人数加一
maxSatisfied++;
}
}
}
return maxSatisfied;
}
```
阅读全文
相关推荐


















