题目链接:https://codeforces.com/contest/1457/problem/E
题解都有点看不懂…
这里是题解,论述了为什么分组做是可行的:https://codeforces.com/blog/entry/85118
从出现负数开始,这个负数和剩余的数,根据大小进行排序,进而根据顺序进行分组。每组最小的那个肯定不会加进来,次小的加一次,以此类推。因为是根据大小顺序分的组,所以肯定是大的负数贡献次数多,小的负数贡献次数小。均分k+1组即可。比如(-1,-6,-8,-9,-9)按k=2分为(-1,-9),(-6,-9),(-8),按k=1分为(-1,-8,-9)(-6,-9),即每次后面第k+1位取一个数。
这样保证两点:①组之间长度差不大于1;②如题解的图所示,组内位置在下的块,其值比任何一个其他组的位置在上的块值都要小,题解已经说明了下图的-5和-3互换是更优的。-5*4-3*2<-5*2-3*4
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
typedef long long ll;
ll c[maxn],cur,ans;
int main(void){
//freopen("in.txt","r",stdin);
int n,k;
scanf("%d %d",&n,&k);
for(int i=1;i<=n;i++)scanf("%lld",&c[i]);
sort(c+1,c+1+n);
int pos=n;
while(pos>0&&cur>=0){
ans+=cur;
cur+=c[pos--];
}
if(!pos){printf("%lld\n",ans);return 0;}
c[++pos]=cur;
sort(c+1,c+1+pos);
for(int i=1;i<=pos;i++){
int num=(i-1)/(k+1);
ans+=num*c[i];
}
printf("%lld\n",ans);
return 0;
}