hdu 2829 Lawrence(斜率dp)

//#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值