hdu4258 斜率优化dp

来源:互联网 发布:淘宝经营地怎么改 编辑:程序博客网 时间:2024/06/05 05:18
参考下面文章http://blog.csdn.net/balloons2012/article/details/7912296感觉最重要的是  和当前位置有关的斜率,随下表递增单调。。这样凸包才可以求得最优解
</pre><pre name="code" class="cpp">#include <iostream>#include <cmath>#include <cstdio>#define N 1000010#define LL long longusing namespace std;struct point{    LL x, y;    point(LL a=0, LL b = 0): x(a), y(b) {    }    void set(LL a, LL b) {        x = a;        y = b;    }};point que[N];LL a[N];LL dp[N];bool mul(const point &a, const point &b, const point &c) {    return (b.x-a.x) * (c.y-a.y) <= (b.y-a.y)*(c.x-a.x); }int main(int argc, char* argv[]) {    LL n, c;    while(scanf("%lld%lld", &n, &c) && (n && c)) {        for(LL i=0; i<n; ++i) {            scanf("%lld", &a[i]);        }        int head = 0, tail = 0;        que[tail++].set(a[0], a[0]*a[0]);        dp[0] = c;        for(LL i=1; i<n; ++i) {            point pp(a[i], dp[i-1]+a[i]*a[i]);            while(head+1 < tail && mul(que[tail-2], que[tail-1], pp)) --tail;            que[tail++] = pp;            while(head+1 < tail && que[head].y-2*a[i]*que[head].x >= que[head+1].y-2*a[i]*que[head+1].x) ++head;            dp[i] = que[head].y - 2*a[i]*que[head].x + a[i]*a[i] + c;        }        printf("%lld\n", dp[n-1]);    }    return 0;}

0 0