超市排队问题(多窗口服务时间)
要求
There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!
input
- customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amount of time they require to check out.
- n: a positive integer, the number of checkout tills.
output
The function should return an integer, the total time required.
样例
queueTime(std::vector<int>{5,3,4}, 1)
// should return 12
// because when n=1, the total time is just the sum of the times
queueTime(std::vector<int>{10,2,3,3}, 2)
// should return 10
// because here n=2 and the 2nd, 3rd, and 4th people in the
// queue finish before the 1st person has finished.
queueTime(std::vector<int>{2,3,10}, 2)
// should return 12
我的实现方式
#include <algorithm>
#include <vector>
long queueTime(std::vector<int> customers,int n){
std::vector<int> windows(n,0); //用向量表示n个窗口
int Num_Customers = customers.size(); //存储顾客的数量
for ( int i = 0; i < Num_Customers ; i++ )
{
int position = min_element(windows.begin(),windows.end()) - windows.begin();
//找到最小窗口的对应位置
windows[position] += customers[i];
}
long MaxValue = *max_element(windows.begin(),windows.end());
return MaxValue;
这里通过了使用vector和algorithm用来进行操作是因为可以利用min_element,和max_element函数可以实现直接找出vector中的极值元素的指针或迭代器,再利用极值元素的地址减去.begin()的地址,即可获得所需元素的下标.
另:之前在看别人的blog中看到vector下标表示只能调用不能赋值,今日亲测是可以赋值的,可能是C++后期标准允许了这一操作.
第一次写Blog,萌新勿喷.
本文探讨了一个常见的超市排队问题,即如何优化多窗口的服务时间,以减少所有顾客的总等待时间。通过使用C++的vector和algorithm库,实现了一种有效的算法来解决这一问题。该算法首先初始化n个窗口的时间为0,然后遍历顾客队列,将每个顾客分配到当前服务时间最短的窗口,最后返回所有窗口中服务时间最长的那个窗口的时间。
1709

被折叠的 条评论
为什么被折叠?



