cf 940E Cashback

探讨如何通过动态规划解决数组最优划分问题,目标是最小化特定条件下的子数组总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 原题

E. Cashback
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Since you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.

You are given an array a of length n and an integer c.

The value of some array b of length k is the sum of its elements except for the  smallest. For example, the value of the array [3, 1, 6, 5, 2] with c = 2 is 3 + 6 + 5 = 14.

Among all possible partitions of a into contiguous subarrays output the smallest possible sum of the values of these subarrays.

Input

The first line contains integers n and c (1 ≤ n, c ≤ 100 000).

The second line contains n integers ai (1 ≤ ai ≤ 109) — elements of a.

Output

Output a single integer  — the smallest possible sum of values of these subarrays of some partition of a.

Examples
input
Copy
3 5
1 2 3
output
6
input
Copy
12 10
1 1 10 10 10 10 10 10 9 10 10 10
output
92
input
Copy
7 2
2 3 6 4 5 7 1
output
17
input
Copy
8 4
1 3 4 5 5 3 4 1
output
23
Note

In the first example any partition yields 6 as the sum.

In the second example one of the optimal partitions is [1, 1], [10, 10, 10, 10, 10, 10, 9, 10, 10, 10] with the values 2 and 90 respectively.

In the third example one of the optimal partitions is [2, 3], [6, 4, 5, 7], [1] with the values 3, 13 and 1 respectively.

In the fourth example one of the optimal partitions is [1], [3, 4, 5, 5, 3, 4], [1] with the values 1, 21 and 1 respectively.


二 分析

题意:给一个长度为n的数组,你可以把数组切成若干份。对于每一份,如果长度为k,删除其中最小的k/c下取整个数(c给定),把剩下的数求和。最后把若干份的和再加在一起,问结果最小是多少。

分析:满足最优子结构和无后效性,很容易想到DP。琢磨一下,发现一个可行的策略是每份子数组长度只取1或c。这样我们状态转移的代价可以降到O(n),但事先需要储存一下所有长度为c的子数组的最小值以及和,用multiset处理的话代价是O(nlgn)。


三 代码

/*
AUTHOR: maxkibble
PROB: cf 940E
LANG: c++ 17
*/

#include <cstdio>
#include <set>

typedef long long LL;

const int maxn = 1e5 + 5;

int n, c, a[maxn], mina[maxn];
LL sum[maxn], dp[maxn];
std::multiset<int> seg;

int main() {
    scanf("%d%d", &n, &c);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &a[i]);
        seg.insert(a[i]);
        sum[i] = sum[i - 1] + a[i];
        if (seg.size() > c) {
            seg.erase(seg.lower_bound(a[i - c]));
            sum[i] -= a[i - c];
        }
        mina[i] = *seg.begin();
    }

    for (int i = 1; i <= n; i++) {
        if (i < c) { dp[i] = dp[i - 1] + a[i]; continue; }
        dp[i] = std::min(dp[i - 1] + a[i], dp[i - c] + sum[i] - mina[i]);
    }
    printf("%lld\n", dp[n]);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值