[蓝桥杯 2021 国 C] 巧克力 solution

· · 题解

思路

选巧克力的操作具有后效性,要优先保证天数靠后的巧克力,所以按保质期从第 x 天倒推到第 1 天。

对于第 i 天,把所有保质期 b \ge i 的巧克力加入小根堆,然后取出价格最小的一块吃掉。这样能保证每一天都用到当前可选的最便宜巧克力。

由于每种巧克力数量可能很大,不能一块一块存,需要记录剩余数量。

无解判断也是简单的。如果某一天堆为空,说明无法满足,输出 -1。

代码

// code by Umbrella.
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,l,r) for(int i=(l);i<=(r);i++)
#define per(i,r,l) for(int i=(r);i>=(l);i--)
#define pii pair<int,int>
#define fir first
#define sec second
#define pb push_back
namespace Umbrella{
    struct Node{
        int a,b,c;
        bool operator<(const Node& other)const {
            if(a==other.a){
                return b>other.b;
            }
            return a>other.a;
        }
    }g[100005];
    int x,n;
    priority_queue<Node> pq;
    void solve(){
        cin>>x>>n;
        rep(i,1,n){
            cin>>g[i].a>>g[i].b>>g[i].c;
        }
        sort(g+1,g+n+1,[](Node u,Node v){
            return u.b<v.b;
        });
        int now=n,ans=0;
        per(i,x,1){
            while(g[now].b>=i){
                pq.push(g[now]);
                now--;
            }
            ans+=pq.top().a;
            auto k=pq.top();
            pq.pop();
            pq.push(Node{k.a,k.b,k.c-1});
            if(pq.top().c==0){
                pq.pop();
            }
        }
        cout<<ans;
    }
}
signed main(){
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int _T=1;
//  cin>>_T;
    while(_T--){
        Umbrella::solve();
    }
    return 0;
}