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(aif(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 112131+4252+6373=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 (1kn31051≤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个从最大开始找。




#include<bits/stdc++.h> 
using namespace std;
typedef long long ll;

ll a[300005],suf[300005];

int main()
{
    int t,n,k,i,j;
    scanf("%d%d",&n,&k);
    for(i=1;i<=n;i++){
        scanf("%I64d",&a[i]);
    }
    for(i=n;i>=1;i--){
        suf[i]=suf[i+1]+a[i];
    }
    sort(suf+2,suf+n+1);
    ll ans=suf[1];
    for(i=n;i>n-(k-1);i--){
        ans+=suf[i];
    }
    printf("%I64d\n",ans);
    return 0;
}
posted @ 2019-06-30 16:03  yzm10  阅读(430)  评论(0编辑  收藏  举报