带后悔贪心问题
[JSOI2007]建筑抢修
https://ac.nowcoder.com/acm/problem/20154
看了题解,这是个带后悔贪心问题,这里给出python3答案。
如果不使用优先级队列,会超时!
python3 优先级队列在queue中,为了避免定制一个q = queue.PriorityQueue() 还是用小顶堆heapq吧
1、heappush(heap, x):向堆中添加元素
2、heappop(heap):弹出堆中最小的元素,并且维持剩余元素的堆结构
4、heapreplace(heap, x):弹出堆中最小的元素,然后将新元素插入。
5、nlargest(n, iter)、nsmallest(n, iter):用来寻找任何可迭代对象iter中的前n个最大的或前n个最小的元素。
python没有提供大顶堆的实现,想要使用大顶堆需要一些trick。heappush(e)改为heappush(-e),heappop(e)为-heappop(e),也就是说存入和取出的数都是相反数,其他逻辑和TopK相同。
注意!!!弹出的是负数!!!弹出的是负数!!!。。。
import sys
from heapq import *
n=int(input())
a=[]
for i in range(n):
line = sys.stdin.readline().strip()
ai=tuple(map(int,line.split()))
a.append(ai)
a=sorted(a,key=lambda x:x[1], reverse=False)
cost=0
f=[]
for i in range(n):
#f.append(a[i][0])
heappush(f, -a[i][0])
cost=cost+a[i][0]
if cost>a[i][1]:
#regret=max(f)
#f.remove(regret)
regret=heappop(f)
cost=cost-(-regret)
print(len(f))
查看6道真题和解析