【CodeForces - 1197C】Array Splitting(水题)

题干:

You are given a sorted array a1,a2,…,ana1,a2,…,an (for each index i>1i>1 condition ai≥ai−1ai≥ai−1holds) 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

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].

题目大意:

给一个有序数组(n=3e5),分成K份,要求每份的最大值减最小值的差最小,求这个差值。

解题报告:

   化简个公式然后求相邻点的差的最小值就可以了。取前k-1个,拿个优先队列维护一下。

AC代码:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define F first
#define S second
#define ll long long
#define pb push_back
#define pm make_pair
using namespace std;
typedef pair PII;
const int MAX = 4e5 + 5;
int a[MAX],n,k;
priority_queue pq;
ll ans;
int main()
{
	cin>>n>>k;
	for(int i = 1; i<=n; i++) cin>>a[i];
	for(int i = 2; i<=n; i++) pq.push(a[i] - a[i-1]);
	for(int i = 1; i<=k-1; i++) ans -= pq.top(),pq.pop();
	ans += a[n]-a[1];
	cout << ans << endl;
	return 0 ;
}

 

你可能感兴趣的:(思维,Codeforce~)