Educational Codeforces Round 69 (Rated for Div. 2) C. Array Splitting 水题

C. Array Splitting

You are given a sorted array ?1,?2,…,?? (for each index ?>1 condition ??≥??−1 holds) and an integer ?.

You are asked to divide this array into ? non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray.

Let ???(?) be equal to the maximum in the ?-th subarray, and ???(?) be equal to the minimum in the ?-th subarray. The cost of division is equal to ∑?=1?(???(?)−???(?)). For example, if ?=[2,4,5,5,8,11,19] and we divide it into 3 subarrays in the following way: [2,4],[5,5],[8,11,19], then the cost of division is equal to (4−2)+(5−5)+(19−8)=13.

Calculate the minimum cost you can obtain by dividing the array ? into ? non-empty consecutive subarrays.

Input

The first line contains two integers ? and ? (1≤?≤?≤3⋅105).

The second line contains ? integers ?1,?2,…,?? (1≤??≤109, ??≥??−1).

Output

Print the minimum cost you can obtain by dividing the array ? into ? nonempty consecutive subarrays.

Examples

input
6 3
4 8 15 16 23 42
output
12
input
4 4
1 3 3 7
output
0
input
8 1
1 1 2 3 5 8 13 21
output
20

Note

In the first test we can divide array ? in the following way: [4,8,15,16],[23],[42].

题目大意

给你长度为n的从小到大排列的数组,你需要切为k个连续的子序列数组,每个数组的切分代价是max(a[i])-min(a[j]),现在问你总代价最小是多少

题解

每个子序列的代价其实就是最大值减去最小值,就是最后面的数减去最前面的数,再拆分细致一点,就是差值的和。

我们令b[i]=a[i+1]-a[i]之后,他需要切成k个连续的子序列,实际上就是去掉k-1个最大的差值。

举个简单例子 4 8 15 16 23 42 这个序列需要切分成三份。

他们的差值分别为: 4, 7, 1, 7, 19。如果不需要切分的话,答案就是42-4,或者所有差值的和。

如果切分成三份,实际上就是去掉了最大的3-1个差值罢了。

代码

#include<bits/stdc++.h>
using namespace std;

const int maxn = 300000 + 5;
int n, k;
int a[maxn],b[maxn];
int main() {
    scanf("%d%d",&n,&k);
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=0;i<n-1;i++){
        b[i]=a[i+1]-a[i];
    }
    int sum=0;
    sort(b,b+n-1);
    for(int i=0;i<n-k;i++){
        sum=sum+b[i];
    }
    printf("%d\n",sum);
    return 0;
}

转载于:https://www.cnblogs.com/qscqesze/p/11255043.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值