习题8.1 银行排队问题之单队列多窗口服务 (25point(s))
假设银行有K个窗口提供服务,窗口前设一条黄线,所有顾客按到达时间在黄线后排成一条长龙。当有窗口空闲时,下一位顾客即去该窗口处理事务。当有多个窗口可选择时,假设顾客总是选择编号最小的窗口。
本题要求输出前来等待服务的N位顾客的平均等待时间、最长等待时间、最后完成时间,并且统计每个窗口服务了多少名顾客。
Example:
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
typedef struct CustomerType {
int arrive;
int used;
int wait;
} *Customer;
typedef struct WindowType {
int sum;
int final;
} *Window;
int main()
{
int N;
cin >> N;
Customer c = new CustomerType[N];
for(int i = 0; i < N; i++) {
cin >> c[i].arrive >> c[i].used;
if(c[i].used > 60) c[i].used = 60;
}
int K;
cin >> K;
Window w = new WindowType[K];
for(int i = 0; i < K; i++) w[i].final = 0;
for(int i = 0; i < N; i++) {
for(int h = 0; h < K; h++) {
if(w[h].final < c[i].arrive) {
w[h].final = c[i].arrive;
}
}
int idle = 0;
int minvalue = w[idle].final;
for(int h = 1; h < K; h++) {
if(w[h].final < minvalue) {
idle = h;
minvalue = w[h].final;
}
}
w[idle].sum++;
c[i].wait = w[idle].final - c[i].arrive;
w[idle].final = w[idle].final + c[i].used;
}
int maxvalue = 0;
int sum = 0;
for(int i = 0; i < N; i++) {
sum += c[i].wait;
if(c[i].wait > maxvalue) maxvalue = c[i].wait;
}
printf("%.1f %d", (double)sum/N, maxvalue);
maxvalue = 0;
for(int h = 0; h < K; h++) {
if(w[h].final > maxvalue) maxvalue = w[h].final;
}
cout << ' ' << maxvalue << endl;
bool space = false;
for(int h = 0; h < K; h++) {
if(!space) space = true;
else cout << ' ';
cout << w[h].sum;
}
delete[] w;
delete[] c;
return 0;
}
思路:
记录每个窗口的结束时间,先跟下一个顾客的到达时间比较,更新时间,然后从K个窗口选择最早结束的为idle窗口,并更新结束时间。