跳到正文

题解

题解:B4104 [CSP-X2024 山东] 购物

songge888约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年12月26日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 2 分钟
获赞
1
题目
B4104

版本

  1. v1当前

题意

有一个序列 aa,表示第 11 到 nn 件商品的价格,mm 为一张优惠券能买的最大商品数,ww 为一张优惠券的价格。我们需要最小化购买所有商品的总费用。

思路

考虑贪心。

题目没有购买顺序的要求,可以先把价格全存下来,为了让优惠卷的价值最大,考虑把 aa 序列从大到小排序,每次先选价值最大的 mm 个商品,如果这 mm 个的价值和 sumsum 大于优惠卷的价格 ww,就可以用优惠卷来买。

注意最后不足 mm 个时也可以用优惠卷。

时间复杂度 O(nlog⁡n)O(n \log n)。

详见代码。

Code

C++
#include<bits/stdc++.h>
#define bug cout<<"songge888"<<'\n';
#define int long long
using namespace std;
int n,m,w; 
int a[200010];
int sum,ans;
int tot;
bool cmp(int x,int y){
	return x>y;
} 
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n>>m>>w;
    for(int i=1;i<=n;i++){
    	cin>>a[i];
	}
	sort(a+1,a+1+n,cmp);
	for(int i=1;i<=n;i++){
		sum+=a[i];
		tot++;
		if(tot==m){
			if(sum>w){
				ans+=w;
			}
			else{
				ans+=sum;
			}
			tot=0;
			sum=0;
		}
		
		
	}
	if(sum>w){
		ans+=w;
	}
	else{
		ans+=sum;
	}
	cout<<ans;
	return 0;
}

原文
存档评论1 条抓取于