Given n bulbs and N rooms, each light bulb has a power, and each room has a minimum illuminating power. You can change K light bulb for the minimum Illuminating Power of all rooms.
Sort the power of the light bulb and the minimum power of the room, and scan each room from large to small.
For a room, first add all the bulbs in the room to the heap.
If the heap is empty, it will take a chance to change the light bulb to the minimum power of the room.
Otherwise, the light bulb with the minimum power will be taken to illuminate the room, and the difference between the light bulb power and the minimum power of the room will be added to another heap.
If you still have the opportunity to change the light bulb at the end, replace the maximum K difference values in the second heap.
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>#define M 500500using namespace std;struct Heap{int heap[M],top;void Insert(int x){heap[++top]=x;int t=top;while(t>1){if(heap[t]>heap[t>>1])swap(heap[t],heap[t>>1]),t>>=1;elsebreak;}}void Pop(){heap[1]=heap[top--];int t=2;while(t<=top){if( t<top && heap[t+1]>heap[t] )++t;if(heap[t]>heap[t>>1])swap(heap[t],heap[t>>1]),t<<=1;elsebreak;}}}heap1,heap2;int n,k,a[M],b[M];long long ans;int main(){int i,j;cin>>n>>k;for(i=1;i<=n;i++)scanf("%d",&a[i]);for(i=1;i<=n;i++)scanf("%d",&b[i]);sort(a+1,a+n+1);sort(b+1,b+n+1);for(i=n,j=n;i;i--){for(;j&&a[j]>=b[i];j--)heap1.Insert(-a[j]);if(!heap1.top){k--;ans+=b[i];if(k==-1)return puts("NIE"),0;}else{int x=-heap1.heap[1];heap1.Pop();ans+=x;heap2.Insert(x-b[i]);}}while(k--)ans-=heap2.heap[1],heap2.Pop();cout<<ans<<endl;return 0;}
Bzoj 3728 pa2014final zarowki heap + greedy