BZOJ 4518: [Sdoi2016]征途 [斜率优化DP]
4518: [Sdoi2016]征途
题意:\(n\le 3000\)个数分成m组,一组的和为一个数,求最小方差\(*m^2\)
DP方程随便写\(f[i][j]=min\{f[k][j-1]+(s[i]-s[k])^2 \}\)
发现可以斜率优化,很久没写忘记了60分暴力走人
拆开平方,\(f[i][p]=-2s_i s_k + f[k][p-1] + s_k^2 - s_i^2\)
对于两个转移\(j,k\),j比k优时$$
slope(j,k)=\frac{f[j]+s_j2-f[k]-s_k2}{s_j-s_k} \ge 2s_i
\[纵坐标$A(i)=f[i]+s_i^2$,横坐标$s_i$,发现横坐标和斜率都递增,维护下凸壳就行了
</br>
MD这破玩意我还写错
```cpp
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long ll;
#define fir first
#define sec second
const int N=3005, INF=1e9;
inline int read() {
char c=getchar(); int x=0, f=1;
while(c<'0' || c>'9') {if(c=='-')f=-1; c=getchar();}
while(c>='0' && c<='9') {x=x*10+c-'0'; c=getchar();}
return x*f;
}
int n, m, a[N];
ll f[N][N], s[N];
inline double A(int i, int p) {return (double)f[i][p] + s[i]*s[i];}
inline double slope(int j, int k, int p) {
return (double)(A(j, p) - A(k, p))/(double)(s[j]-s[k]);
}
int q[N], head, tail;
void dp() {
f[0][0]=0; for(int i=1; i<=n; i++) f[i][1]=s[i]*s[i];
for(int p=2; p<=m; p++) {
head=1; tail=0;
for(int i=1; i<=n; i++) {
while(head<tail && slope(q[head], q[head+1], p-1) < 2*s[i]) head++;
int j=q[head];
f[i][p] = f[j][p-1] + (s[j]-s[i])*(s[j]-s[i]);
while(head<tail && slope(q[tail], q[tail-1], p-1) > slope(q[tail], i, p-1)) tail--;
q[++tail]=i;
}
}
ll ans = m*f[n][m] - s[n]*s[n];
printf("%lld\n",ans);
}
int main() {
//freopen("in","r",stdin);
freopen("menci_journey.in","r",stdin);
freopen("menci_journey.out","w",stdout);
n=read(); m=read();
for(int i=1; i<=n; i++) a[i]=read(), s[i]=s[i-1]+a[i];// printf("i %d\n",i);;
dp();
}
```\]
Copyright:http://www.cnblogs.com/candy99/