Array Splitting CodeForces - 1197C

本文介绍了一种算法,用于将已排序的数组等分为k个连续的非空子数组,并计算这种划分方式下最小的成本。成本定义为每个子数组的最大值与最小值之差的总和。文章提供了一个示例性的C++实现。

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

You are given a sorted array a_1, a_2, \dots, a_na1​,a2​,…,an​ (for each index i > 1i>1 condition a_i \ge a_{i-1}ai​≥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 \sum\limits_{i=1}^{k} (max(i) - min(i))i=1∑k​(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 \le k \le n \le 3 \cdot 10^51≤k≤n≤3⋅105).

The second line contains nn integers a_1, a_2, \dots, a_na1​,a2​,…,an​ (1 \le a_i \le 10^91≤ai​≤109, a_i \ge a_{i-1}ai​≥ai−1​).

Output

Print the minimum cost you can obtain by dividing the array aa into kk 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 aa in the following way: [4, 8, 15, 16], [23], [42][4,8,15,16],[23],[42].

#include<iostream>
using namespace std;
#include<string>
#include<algorithm>
#pragma warning (disable:4996)
#include <climits>
#include <vector>
int a[1000000];
int d[1000000];
bool cmp(int a, int b);
int main() {
	int n, k;
	cin >> n >> k;
	int sum = 0;
	for (int cnt = 0; cnt < n; cnt++) {
		scanf("%d" , &a[cnt]);
	}
	d[0] = 0;
	for (int cnt = 1; cnt < n; cnt++) {
		d[cnt] = a[cnt] - a[cnt - 1];
		sum += d[cnt];
	}
	sort(d, d + n, cmp);
	for (int cnt = 0; cnt < k - 1; cnt++) {
		sum -= d[cnt];
	}
	cout << sum;
	return 0;
}
bool cmp(int a, int b) {
	return a > b;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cjz-lxg

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值