超市排队问题(多窗口服务时间)
要求
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,萌新勿喷.