CodeForces - 1175D Array Splitting(数组划分+后缀和+贪心)

时间:2023-03-10 04:28:52
CodeForces - 1175D Array Splitting(数组划分+后缀和+贪心)

You are given an array a1,a2,…,ana1,a2,…,an 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 f(i)f(i) be the index of subarray the ii-th element belongs to. Subarrays are numbered from left to right and from 11 to kk.

Let the cost of division be equal to ∑i=1n(ai⋅f(i))∑i=1n(ai⋅f(i)). For example, if a=[1,−2,−3,4,−5,6,−7]a=[1,−2,−3,4,−5,6,−7] and we divide it into 33 subbarays in the following way: [1,−2,−3],[4,−5],[6,−7][1,−2,−3],[4,−5],[6,−7], then the cost of division is equal to 1⋅1−2⋅1−3⋅1+4⋅2−5⋅2+6⋅3−7⋅3=−91⋅1−2⋅1−3⋅1+4⋅2−5⋅2+6⋅3−7⋅3=−9.

Calculate the maximum 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 (|ai|≤106|ai|≤106).

Output

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

Examples

Input
5 2
-1 -2 5 -4 8
Output
15
Input
7 6
-3 0 -1 -2 -2 -4 -1
Output
-45
Input
4 1
3 -1 6 0
Output
8

题意:
给定一个长度为n的数组,将其划分为k份。问怎样划分使得各份【i(第i份)*sum(i份内部和)】相加的和最大。 思路:
利用后缀和思想,用差(左减右)的形式表示连续的区间和。
根据以下公式(裂项求和)推导出结果,为k个后缀和相加。
若使答案最大,只需找出最大的k个后缀和,贪心即可。
注意:S(p1)必须为第一项的后缀和,因为要保证覆盖所有的数组元素,剩余k-1个从最大开始找。 CodeForces - 1175D Array Splitting(数组划分+后缀和+贪心)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll; ll a[],suf[]; int main()
{
int t,n,k,i,j;
scanf("%d%d",&n,&k);
for(i=;i<=n;i++){
scanf("%I64d",&a[i]);
}
for(i=n;i>=;i--){
suf[i]=suf[i+]+a[i];
}
sort(suf+,suf+n+);
ll ans=suf[];
for(i=n;i>n-(k-);i--){
ans+=suf[i];
}
printf("%I64d\n",ans);
return ;
}