每日一题 -- 堆
857. 雇佣 K 名工人的最低成本
857. 雇佣 K 名工人的最低成本
分析
- 首先根据 q/w 质量除以底薪,得到的就是每位员工的工作效率,也就是单位钱能干的活,可以以性价比来替代
- 我们都想用性价比高的员工,但是现在要求所有员工这个性价比必须一致,多劳多得,而这个性价比呢得至少满足其中一位员工的期望底薪
- 所以我们先将性价比排个序,性价比低的能,就是底薪高干活少,所以只要满足低性价比人,高性价比的人就只需要挑相对来说干活没那么强的人(以前性价比高,是要钱少,现在按比例涨价,这些性价比高的瞬间就成了废物,要多补很多钱;因为之前要的钱太少,现在补贴太多,公司都不愿意要,所以啊,做人不能太低估自己,不然政策也保护不了你;打工人就是苦啊;)
- 所以根据质量维护一个大顶堆,然后用排序好的性价比作为基数,每当超出了 K 个值,就从大顶堆中推出质量最高的,保证最后用钱最少。
- 其实这个问题和现实的倒挂现象很相似,新来的应届生效率没你好,但是时薪比你高,当你要拿一样的时薪的时候,公司就会干掉你,这说明有一些不能单纯用效率来体现性价比的东西影响了老板的判断,比方说,年龄???
var mincostToHireWorkers = function(quality, wage, K) {
let res = Infinity
let total = 0
const heap = new Heap()
let rates = []
for(let i = 0;i<quality.length;i++){
rates.push([quality[i]/wage[i],quality[i]])
}
rates.sort((a,b)=>b[0]-a[0])
for(let i = 0;i<rates.length;i++){
const [rate,q] = rates[i]
heap.heappush(-q)
total += q
if(heap.data[0] > K){
total -= -heap.heappop()
}
console.log(heap,res,total,rate)
if(heap.data[0] === K) {
res = Math.min(res,total/rate)
}
}
return res
};
const Heap = function () {
this.data = []
this.data.push(0)
}
Heap.prototype.heappush = function (val) {
this.data.push(val)
this.data[0] += 1
this.up(this.data[0])
}
Heap.prototype.heappop = function () {
this.swap(1, this.data[0])
const res = this.data.pop()
this.data[0] -= 1
this.down()
return res
}
Heap.prototype.swap = function (a, b) {
[this.data[a], this.data[b]] = [this.data[b], this.data[a]]
}
Heap.prototype.down = function (index = 1) {
if (index*2 > this.data[0]) return
const left = 2 * index
const right = 2 * index + 1
let target = index
if (left<=this.data[0] &&this.data[left] < this.data[target]) {
target = left
}
if (right<=this.data[0] &&this.data[right] < this.data[target]) {
target = right
}
if (target !== index) {
this.swap(target, index)
this.down(target)
}
}
Heap.prototype.up = function (index) {
if (index < 2) return
const fatherIndex = Math.floor(index / 2)
if (this.data[index] < this.data[fatherIndex]) {
this.swap(index, fatherIndex)
this.up(fatherIndex)
}
}