题目地址:https://www.patest.cn/contests/pat-a-practise/1017
将给出的数据按照时间的先后顺序排列,可以确定为他们服务的次序。
用优先队列去处理,如果队列还可以插入数据(即窗口没满),就直接插入;如果不能插入数据,就弹出优先队列的第一个元素,将要插入的数据与这个弹出来的元素进行比较,可以确定要插入数据等待的时间。
注意:8点前到达的要累加等待的实践,17点后到达的不处理。
#include <cstdio>
#include <queue>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
struct node {
int time, p;
};
bool cmp(struct node a, struct node b) {
return a.time < b.time;
}
int main() {
int n = 0, k = 0, cnt = 0, waiting = 0;
scanf("%d %d", &n, &k);
struct node *arr = new struct node [n];
for (int i = 0; i < n; i++) {
int hour = 0, minute = 0, second = 0;
scanf("%d:%d:%d %d", &hour, &minute, &second, &arr[i].p);
arr[i].time = hour * 3600 + minute * 60 + second;
arr[i].p *= 60;
}
sort(arr, arr + n, cmp);
priority_queue<int, vector<int>, greater<int> > q;
for (int i = 0; i < n; i++) {
if (arr[i].time > 17 * 3600) {
break;
} else {
cnt++;
if (q.size() < k) {
if (arr[i].time < 8 * 3600) {
waiting += 8 * 3600 - arr[i].time;
arr[i].time = 8 * 3600;
}
q.push(arr[i].time + arr[i].p);
} else {
int temp = q.top();
q.pop();
if (arr[i].time < temp) {
waiting += temp - arr[i].time;
q.push(temp + arr[i].p);
} else {
q.push(arr[i].time + arr[i].p);
}
}
}
}
printf("%.1f", waiting * 1.0 / cnt / 60);
delete [] arr;
return 0;
}