CodeForces - 1175D Array Splitting (+ suffix array division and greedy +)

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 


that Italy:
Given an array of length n, which is divided into k parts. Q. How is divided so that each part [i (i-th) * sum (i parts and internal)] and the maximum sum.

Ideas:
the use of suffixes and thinking, a differential (left minus right) and expressed in the form of continuous interval.
(Splitting summed) to derive the results according to the formula, k is a suffix and addition.
Ruoshi answer the most, just need to find the biggest and the k suffix, greed can be.
Note: S (p1) and the suffix must first, as to ensure coverage of all array elements, the k-1 remaining from the maximum to find the start.




#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;
}

Guess you like

Origin www.cnblogs.com/yzm10/p/11110180.html