//#include <bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
#pragma comment(linxer, "/STACK:102400000,102400000")
#define LL long long
#define pii pair<int, int>
#define MP make_pair
#define ls i << 1
#define rs ls | 1
#define md (ll + rr >> 1)
#define lson ll, md, ls
#define rson md + 1, rr, rs
#define mod 1000000007
#define inf 0x3f3f3f3f
#define N 1010
#define M 200020
int a[N], s[N], tot[N], q[N], dp[N][N];
int x[N], y[N];
LL cross(int ax, int ay, int bx, int by){
return 1LL * ax * by - 1LL * bx * ay;
}
bool check(int i, int j, int k){
return y[j] - y[i] <= (x[j] - x[i]) * k;
}
int main(){
int n, m;
while(scanf("%d%d", &n, &m) != EOF){
if(n == 0 && m == 0) break;
for(int i = 1; i <= n; ++i){
scanf("%d", &a[i]);
s[i] = s[i-1] + a[i];
tot[i] = tot[i-1] + s[i-1] * a[i];
dp[i][1] = tot[i];
}
for(int j = 2; j <= m + 1; ++j){
int head = 0, tail = 0;
q[tail++] = 0;
for(int i = 1; i <= n; ++i){
while(head + 1 < tail){
if(check(q[head], q[head+1], s[i])) head++;
else break;
}
int k = q[head];
dp[i][j] = -x[k] * s[i] + y[k] + tot[i];
x[i] = s[i];
y[i] = s[i] * s[i] - tot[i] + dp[i][j-1];
while(head + 1 < tail){
if(cross(x[q[tail-1]] - x[q[tail-2]], y[q[tail-1]] - y[q[tail-2]], x[i] - x[q[tail-2]], y[i] - y[q[tail-2]]) <= 0) tail--;
else break;
}
q[tail++] = i;
}
}
printf("%d\n", dp[n][m+1]);
}
return 0;
}
hdu 2829 Lawrence(斜率dp)
最新推荐文章于 2021-01-25 20:07:59 发布