CodeForces 1253 C. Sweets Eating DP

本文探讨了一个有趣的算法问题,通过合理安排吃甜点的顺序来最小化总糖罚,涉及到排序、前缀和及动态规划等概念,最终提供了一种高效的解决方案。

一、内容

Tsumugi brought n delicious sweets to the Light Music Club. They are numbered from 1 to n, where the i-th sweet has a sugar concentration described by an integer aiYui loves sweets, but she can eat at most m
sweets each day for health reasons.Days are -indexed (numbered 1,2,3,…). Eating the sweet i at the d-th day will cause a sugar penalty of (d⋅ai), as sweets become more sugary with time. A sweet can be eaten at most once.The total sugar penalty will be the sum of the individual penalties of each sweet eaten.Suppose that Yui chooses exactly ksweets, and eats them in any order she wants. What is the minimum total sugar penalty she can get?Since Yui is an undecided girl, she wants you to answer this question for every value of kbetween 1 and n

.
Input

The first line contains two integers n
and m (1≤m≤n≤200 000).

The second line contains n
integers a1,a2,…,an (1≤ai≤200 000).

Output

You have to output n
integers x1,x2,…,xn on a single line, separed by spaces, where xk is the minimum total sugar penalty Yui can get if she eats exactly k sweets.

Input

9 2
6 19 3 4 4 2 6 7 8

Output

2 5 11 18 30 43 62 83 121

二、思路

  • 首先按照从小到大进行排序。
  • 然后根据前几个我们可以发现规律,每次我们只需要让最小的m个数乘以最大的天数,剩下的m个数依次递减,这样得到的答案就是最优的。找出规律,利用前缀和就可以求解出。
  • dp【i】:表示的是第i颗糖的最小花费
    dp【i】 = dp[max(i - m, 0)] + sum[i] 如果i - m < 0 就令为0.

三、代码

#include <cstdio>
#include <algorithm>
#define max(a, b) (a > b ? a : b)
using namespace std;
typedef long long ll;
const int N = 2e5 + 5;
int n, m, a[N];
ll sum[N], dp[N];
int main() {
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
	sort(a + 1, a + 1 + n);
	for (int i = 1; i <= n; i++) {
		sum[i] = a[i] + sum[i - 1];
	}
	for (int i = 1; i <= n; i++) {
		dp[i] = dp[max(0, i - m)] + sum[i];
		printf("%lld ", dp[i]); 
	} 
	return 0;
} 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值