题解:B4104 [CSP-X2024 山东] 购物
Wendy_Hello_qwq · · 题解
题目传送门。
原文食用效果更佳。
题意
给定
分析
一道贪心题。
贪心需要排序,先将物品价格从小到大排序,然后倒序贪心。
设定一个
注意记得开 long long,数据范围较大。
Code
#include <cstdio>
#include <algorithm>
using namespace std;
// 数据范围较大,要开 long long
long long num, cnt, ans;
long long n, m, w, a[200005];
int main() {
scanf ("%lld%lld%lld", &n, &m, &w);
for (int i = 1; i <= n; i++) scanf ("%lld", &a[i]);
// 贪心,排序
sort (a + 1, a + 1 + n);
// 倒序查找贪心
for (int i = n; i >= 1; i--) {
// 价格
num += a[i];
// 买了多少个商品
cnt++;
// 当足够 m 件商品时
if (cnt == m) {
// 答案取现在的价格总和与优惠券价格的最小值
ans = ans + (num < w ? num : w);
// 全部归零
num = cnt = 0;
}
}
// 最后再进行一次比较
ans = ans + (num < w ? num : w);
printf ("%lld", ans);
return 0;
}
AC 记录。
完结撒花。
作者写题解不易,点个赞再走呗。