题目:有n个数,要分成若干组,每组至少L个数,每组的价值定义为每个数减去该组数的最小值的和,求各组数的价值和的最小值
思路:
先对序列arr按从小到大排序,求出前缀和
设dp[i]表示前i个数的合法分组的最小值
dp[i]=min{dp[j]+sum[i]-sum[j]-arr[j+1]*(i-j)},j<=i-L
然后就是斜率优化了
代码:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<algorithm>
#include<ctime>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<numeric>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template<class T> T f_abs(T a){ return a > 0 ? a : -a; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f
//0x3f3f3f3f
const int maxn=4e5+50;
int q[maxn];
LL dp[maxn];
LL arr[maxn];
LL sum[maxn];
int head,tail,n,L;
LL getdp(int i,int j){
return dp[j]+(sum[i]-sum[j])-arr[j+1]*(i-j);
}
LL gety(int k,int j){//yj-yk
return dp[j]-sum[j]+arr[j+1]*j-(dp[k]-sum[k]+arr[k+1]*k);
}
LL getx(int k,int j){//xj-xk
return arr[j+1]-arr[k+1];
}
int main(){
// freopen("D:\\input.txt","r",stdin);
// freopen("D:\\output.txt","w",stdout);
while(~scanf("%d%d",&n,&L)){
for(int i=1;i<=n;i++)
scanf("%I64d",&arr[i]);
sort(arr+1,arr+n+1);
sum[0]=dp[0]=0;
for(int i=1;i<=n;i++)
sum[i]=sum[i-1]+arr[i];
head=0;
tail=-1;
q[++tail]=0;
for(int i=1;i<=n;i++){
while(head<tail&&gety(q[head],q[head+1])<=(LL)i*getx(q[head],q[head+1]))
head++;
dp[i]=getdp(i,q[head]);
int j=i-L+1;
if(i-L+1<L) continue;//注意这里
while(head<tail&&gety(q[tail-1],q[tail])*getx(q[tail],j)>=gety(q[tail],j)*getx(q[tail-1],q[tail]))
tail--;
q[++tail]=j;
}
printf("%I64d\n",dp[n]);
}
return 0;
}