题解:P16289 [蓝桥杯 2026 省 Python A 组] 购电优化

· · 题解

反悔贪心,每次都把容量装满,用两个堆存储,堆里面表示的是当前购买的组合,一个堆堆顶存最大价格,用于表示反悔:遇到更便宜的就把堆顶弹出,另一个存最小价格,表示每次先从存储的电中取出价格最便宜的电来用,我这里引入tag应该是冗余的,比赛有点紧张写的,直接用rm置零也能表示还能不能用

import heapq
import sys
def solve():
    def generator():
        for line in sys.stdin:
            for part in line.split():
                yield int(part)
    gen=generator()
    def scan():
        return next(gen)
    n,k=scan(),scan()
    w=[0]+[scan() for _ in range(n)]
    c=[0]+[scan() for _ in range(n)]
    q1=[]
    q2=[]
    tag=[0 for _ in range(n+1)]
    rm=[0 for _ in range(n+1)]
    tot=0
    res=0
    for i in range(1,n+1):
        #反悔,弹出劣质电
        while q1 and (tag[q1[0][1]]!=1 or -q1[0][0]>c[i]):
            pri,idx=heapq.heappop(q1)
            if tag[idx]!=1:
                continue
            pri=-pri
            tag[idx]=-1
            tot-=rm[idx]
            res-=pri*rm[idx]
        nd=w[i]
        #优先使用之前买的便宜的电
        while nd>0 and q2:
            pri,idx=heapq.heappop(q2)
            if tag[idx]!=1:
                continue
            if nd>=rm[idx]:
                nd-=rm[idx]
                tot-=rm[idx]
                tag[idx]=-1
            else:
                rm[idx]-=nd
                tot-=nd
                nd=0
                heapq.heappush(q2,[pri,idx])
        if nd>0:
            res+=c[i]*nd
        #贪心,先全部买下来
        t=k-tot
        heapq.heappush(q1,[-c[i],i])
        heapq.heappush(q2,[c[i],i])
        tag[i]=1
        rm[i]=t
        res+=c[i]*t
        tot=k
    #反悔,剩下的不需要了
    while q2:
        pri,idx=heapq.heappop(q2)
        if tag[idx]!=1:
            continue
        res-=pri*rm[idx]
    print(res)
if __name__=="__main__":
    solve()