排队论顾客来源有限制排队模型 C++代码
时间: 2024-05-15 09:13:24 浏览: 15
以下是一个简单的排队论顾客来源有限制排队模型的 C++ 代码示例,其中使用了队列和随机数生成器:
```c++
#include <iostream>
#include <queue>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL)); // 初始化随机数生成器
const int MAX_TIME = 100; // 模拟时间
const int ARRIVAL_INTERVAL = 10; // 顾客到达间隔时间
const int SERVICE_TIME_MIN = 1; // 最小服务时间
const int SERVICE_TIME_MAX = 5; // 最大服务时间
const int SOURCE_LIMIT = 5; // 顾客来源限制
queue<int> q; // 队列
int total_wait = 0; // 总等待时间
int total_customers = 0; // 总顾客数
int served_customers = 0; // 已服务顾客数
int clock = 0; // 计时器
int next_arrival = ARRIVAL_INTERVAL; // 下一个顾客到达时间
while (clock < MAX_TIME) {
if (next_arrival == clock) {
if (q.size() >= SOURCE_LIMIT) { // 超过顾客来源限制,顾客离开
cout << "Customer leaves at " << clock << endl;
} else {
q.push(clock); // 顾客进入队列
cout << "Customer arrives at " << clock << endl;
}
next_arrival += ARRIVAL_INTERVAL; // 更新下一个顾客到达时间
}
if (!q.empty()) {
int service_time = rand() % (SERVICE_TIME_MAX - SERVICE_TIME_MIN + 1) + SERVICE_TIME_MIN; // 随机生成服务时间
int start_service_time = clock; // 开始服务时间
int end_service_time = clock + service_time; // 结束服务时间
int wait_time = start_service_time - q.front(); // 等待时间
total_wait += wait_time; // 更新总等待时间
total_customers++; // 更新总顾客数
served_customers++; // 更新已服务顾客数
q.pop(); // 从队列中移除顾客
cout << "Customer starts service at " << start_service_time << endl;
cout << "Customer ends service at " << end_service_time << endl;
}
clock++; // 计时器加一
}
cout << "Average wait time: " << (double) total_wait / total_customers << endl;
cout << "Served customers: " << served_customers << endl;
cout << "Unserved customers: " << q.size() << endl;
return 0;
}
```
这个程序模拟了 100 个单位时间内的顾客排队情况,其中顾客到达间隔时间为 10 个单位时间,服务时间在 1 到 5 个单位时间之间随机生成。当队列中有顾客时,程序会开始服务第一个顾客,直到服务结束。如果顾客到达时队列已经满了,顾客将离开。程序最后输出了平均等待时间、已服务顾客数和未服务顾客数。