zoukankan      html  css  js  c++  java
  • 184. go 实现大顶堆操作(力扣502. IPO)

    package main
    
    import (
    	"container/heap"
    	"sort"
    )
    
    func findMaximizedCapital(k, w int, profits, capital []int) int {
    	n := len(profits)
    	type pair struct {
    		c, p int
    	}
    	arr := make([]pair, n) // 开辟空间
    	for i, p := range profits {
    		arr[i] = pair{capital[i], p}
    	}
    	sort.Slice(arr, func(i, j int) bool {
    		return arr[i].c < arr[j].c
    	})
    
    	h := &hp{}
    	for cur := 0; k > 0; k-- {
    		for cur < n && arr[cur].c <= w {
    			heap.Push(h, arr[cur].p)
    			cur++
    		}
    		if len(h.IntSlice) > 0 {
    			w += heap.Pop(h).(int)
    		} else {
    			break
    		}
    	}
    	return w
    }
    
    type hp struct{ sort.IntSlice }
    
    //https://pkg.go.dev/container/heap
    // 实现Less方法, 因为要通过小于方法实现大顶堆,所以需要进行反向判断,将小于改成大于
    func (this hp) Less(i, j int) bool {
    	return this.IntSlice[i] > this.IntSlice[j]
    }
    
    // 实现Push方法, 跟着官网做就好了
    func (this *hp) Push(v interface{}) {
    	this.IntSlice = append(this.IntSlice, v.(int))
    }
    
    // 神奇的操作
    func (this *hp) Pop() interface{} {
    	a := this.IntSlice
    	v := a[len(a)-1]
    	this.IntSlice = a[:len(a)-1]
    	return v
    }
    
    
  • 相关阅读:
    [IOI1994][USACO1.5]数字三角形 Number Triangles
    和为给定数
    小凯的疑惑
    棋盘
    【2020NOI.AC省选模拟#2】C. 送分题
    【NOI OL #2】涂色游戏
    【NOI OL #3】小结
    【NOI OL #1】最小环
    【NOI OL #1】冒泡排序
    【NOI OL #1】序列
  • 原文地址:https://www.cnblogs.com/liuzhanghao/p/15243595.html
Copyright © 2011-2022 走看看