题目描述:
There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].
Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:
1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.
2. Every worker in the paid group must be paid at least their minimum wage expectation.
Return the least amount of money needed to form a paid group satisfying the above conditions.
Example 1:
Input: quality = [10,20,5], wage = [70,50,30], K = 2
Output: 105.00000
Explanation: We pay 70 to 0-th worker and 35 to 2-th worker.
Example 2:
Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
Output: 30.66667
Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately.
Note:
1. 1 <= K <= N <= 10000, where N = quality.length = wage.length
2. 1 <= quality[i] <= 10000
3. 1 <= wage[i] <= 10000
4. Answers within 10^-5 of the correct answer will be considered correct.
class worker{
public:
int quality;
int wage;
double rate; // rate=quality/wage
worker(int q, int w, double r):quality(q), wage(w), rate(r){}
};
class Solution {
public:
static bool comp(worker a, worker b)
{
if(a.rate<b.rate) return true;
else return false;
}
double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int K) {
vector<worker> workers;
for(int i=0;i<quality.size();i++)
{
worker w(quality[i],wage[i],(double)wage[i]/(double)quality[i]);
workers.push_back(w);
}
sort(workers.begin(),workers.end(),comp);
double min_cost=(double)INT_MAX;
int quality_sum=0;
priority_queue<int,vector<int>,less<int>> pq; // 用less定义最大堆
int i=-1;
while(pq.size()<K) // 前构造长度为K的优先队列
{
i++; // i为当前遍历的worker
pq.push(workers[i].quality);
quality_sum+=workers[i].quality;
}
while(i<workers.size())
{
// worker[i]为当前K个worker中rate最大的,不断遍历i的目的就是针对每个rate[i]都找到对应的最小quality_sum
// 从而计算cost,注意对于一个rate[i]不需要考虑它之后的worker,因为他们的rate都更大,加入之后就会改变当前考虑的rate
min_cost=min(min_cost,quality_sum*workers[i].rate);
i++;
pq.push(workers[i].quality);
quality_sum+=workers[i].quality;
quality_sum-=pq.top();
pq.pop();
}
return min_cost;
}
};