跳到正文

题解

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

firefly_szy约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年9月30日
收录
2026年10月24日
更新
2026年11月16日
篇幅
约 3 分钟
题目
P8769

版本

  1. v1当前

思路

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

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

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

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

代码

C++
// 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;
}
原文