cf-C. Array Splitting

C. Array Splitting

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given a sorted array a1,a2,…,ana1,a2,…,an (for each index i>1i>1 condition ai≥ai−1ai≥ai−1 holds) and an integer kk.

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

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

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

Input

The first line contains two integers nn and kk (1≤k≤n≤3⋅1051≤k≤n≤3⋅105).

The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109, ai≥ai−1ai≥ai−1).

Output

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

Examples

input

Copy

6 3
4 8 15 16 23 42

output

Copy

12

input

Copy

4 4
1 3 3 7

output

Copy

0

input

Copy

8 1
1 1 2 3 5 8 13 21

output

Copy

20

Note

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

题意:这个题的意思就是给你一个数n和一个数字k,然后输入从小到大排列好的n个数字,让你把这n个数字分成k组,分成的每一组的成本就是这个组里面数字的最大减最小,求分成k组成本最小。

题解:刚开始这个题我也没有什么思路,后来慢慢的画画才有了感觉,

现在假如给定的序列为    a1,a2,a3,a4,a5,a6;

然后我们得到相邻两个数字的差值,x1=a2-a1,x2=a3-a2.....

得到一个 x1,x2,x3,x4,x5;

然后我们再想不管你怎么分这个数组,是不是代价最终一定是x这个序列的几个数字相加。

假如我们把所给序列分成三组,得打 {a1,a2,a3}      {a4}     {a5,a6};

那么这么分的代价是多少呢?就是x1+x2+x5。

对吧,不管你怎么分,一定是x数组里面相加,那么既然要让代价最小,不就成了贪心了,我们只要不加最大的那几个xi,得到的是不是一定是最小的呢。

当然如果n个数字分成n组,那结果就是0 了,上面的就不成立了,这个单独讨论一下就行。

下面给出代码。

#include<bits/stdc++.h>
using namespace std;
const int maxn=3*1e5+7;
int a[maxn],b[maxn];
int main()
{
    int n,k;
    scanf("%d %d",&n,&k);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    int sum=0;
    a[0]=0;
    for(int i=1;i<=n;i++)
    {
        b[i]=a[i]-a[i-1];
        sum+=b[i];
    }
    sort(b+2,b+n+1,greater<int>());
    for(int i=1;i<=n;i++)
        printf("%d ",b[i]);
    printf("\n");
    for(int i=1;i<=k;i++)
        sum-=b[i];
    printf("%d\n",sum);
    return 0;
}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值