您的位置:首页 > 其它

hdu4258 斜率优化dp

2015-10-23 08:53 246 查看
参考下面文章 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 long
using 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
;
LL a
;
LL dp
;

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: