You are given an array k.
You are asked to divide this array into k.
Let the cost of division be equal to 1⋅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 k non-empty consecutive subarrays.
Input
The first line contains two integers 1≤k≤n≤3⋅105).
The second line contains |ai|≤106).
Output
Print the maximum cost you can obtain by dividing the array k 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; }