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 𝑘.c++

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

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

Input

The first line contains two integers 𝑛 and 𝑘 (1≤𝑘≤𝑛≤3⋅105).spa

The second line contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤109, 𝑎𝑖≥𝑎𝑖−1).code

Output

Print the minimum cost you can obtain by dividing the array 𝑎 into 𝑘 nonempty consecutive subarrays.element

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
20input

Note

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

題目大意

給你長度爲n的從小到大排列的數組,你須要切爲k個連續的子序列數組,每一個數組的切分代價是max(a[i])-min(a[j]),如今問你總代價最小是多少io

題解

每一個子序列的代價其實就是最大值減去最小值,就是最後面的數減去最前面的數,再拆分細緻一點,就是差值的和。

咱們令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;
}
相關文章
相關標籤/搜索