Codeforces 940E - Cashback(dp+区间最小值)


E. Cashback
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard 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.


看了别人题解中讲如何推导出本体的思路,顿觉自己水平略差。。。
(我一开始还在想怎么处理区间前k小呢。。。)
从长度为k的区间中删去int(k/c)个最小的数字,可以推导得出尽量选择长度为c的连续自区间是最优的选择:(1.区间长度小于c则一个都不能删,不划算;2.长度为不为c的倍数则删除数量j不变且多出来的几个数字不能使区间前j小变大而只会变小,不划算;3,对于j*c长度的区间,分开成为j个区间分别取最小值会比合在一起取前j小大,所以合在一起不划算)

所以dp[i]表示长度为i的前缀的最优解
dp[i]=min( dp[i-1] , dp[i-c] + sum[i] - sum[i-c] - MIN(i-c+1,i) )
区间最小值用单调队列维护又简便复杂度还低。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=100005;
const int maxe=200005;
const int mod=1e9+7;
int n,c;
int a[maxn];
ll dp[maxn];
int sta[maxn];
ll sum[maxn];
int lef,rig;

int main(){
    scanf("%d%d",&n,&c);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=n;i++)sum[i]=sum[i-1]+a[i];
    if(c==0){printf("0\n");return 0;}
    for(int i=1;i<=n;i++){
        while(rig>lef&&a[sta[rig-1]]>=a[i])rig--;
        sta[rig++]=i;
        while(sta[lef]<=i-c)lef++;
        dp[i]=dp[i-1]+a[i];
        if(i-c>=0)dp[i]=min(dp[i],dp[i-c]+sum[i]-sum[i-c]-a[sta[lef]]);
    }
    printf("%lld",dp[n]);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值