思路:设dp[i]为考虑前i个cows的最小值。s[i] 为从第1个到第i个的moos和。
那么方程为dp[i] = min(dp[i],dp[j] + s[i] - s[j] - (i - j)*a[j+1])。
然后斜率优化将复杂度降为O(n)。
这个题!!!一定要注意初值!!!一定要注意状态从什么地方开始转移!!!以后的所有DP题也是!!!
我的代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long LL;
const int maxn = 400005;
LL n,t,k,a[maxn],dp[maxn],s[maxn];
LL q[maxn],hd,tl;
void init(){
s[0] = a[0] = 0;
}
LL getDP(LL j,LL k){
return dp[k] + s[j] - s[k] - (j - k)*a[k+1];
}
LL getUp(LL j,LL k){
return (dp[k] - s[k] + k*a[k+1]) - (dp[j] - s[j] + j*a[j+1]);
}
LL getDown(LL j,LL k){
return a[k+1] - a[j+1];
}
void solve(){
LL i,j;
hd = tl = 0;
q[tl++] = t;
for(j=t;j<2*t;j++) dp[j] = s[j] - j*a[1];
for(j=2*t;j<=n;j++){
while(hd+1<tl && (getUp(q[hd],q[hd+1])
<= j*getDown(q[hd],q[hd+1]))) hd++;
dp[j] = getDP(j,q[hd]);
//cout<<getUp(q[tl-1],j-t+1)<<" "<<getUp(q[tl-2],q[tl-1])<<endl;
while(hd+1<tl && getUp(q[tl-1],j-t+1)*getDown(q[tl-2],q[tl-1])
<= getUp(q[tl-2],q[tl-1])*getDown(q[tl-1],j-t+1)) tl--;
q[tl++] = j-t+1;
//cout<<j<<" "<<q[hd]<<" "<<q[tl-1]<<" "<<dp[j]<<endl;
}
printf("%I64d\n",dp[n]);
}
int main(){
while(~scanf("%I64d%I64d",&n,&t)){
k = n / t;
init();
LL i;
for(i=1;i<=n;i++) scanf("%I64d",&a[i]);
sort(a+1,a+n+1);
for(i=1;i<=n;i++) s[i] = s[i-1] + a[i];
solve();
}
return 0;
}