参考文章:http://www.cnblogs.com/Canon-CSU/p/3425801.html
题意:一些数字,要用区间覆盖他们,,诶个区间的花费是c*(x-y),求最小总花费
分析:开始一直没有想DP,只是想从每一段区间的左右端点数值只差的平方要小于C,各种水然后各种WA。。看过题解后,发现思路也不难想。
对于某个数a[i]来说其最小花费就是f[i]=min(f[j]+(a[i]-a[j+1])^2)。并且可以推出①对于一个y>x若是y优于x则
2*a[i]*(a[y + 1] - a[x + 1]) >= f[y] - f[x] + 1ll * a[y + 1] * a[y + 1] - 1ll * a[x + 1] * a[x + 1]
并且②令左边为L,右边为R,有R/L越小则y越优于x,根据这样的结论,这题就可以用一个双端队列,通过对队首利用①,队尾利用②维护队列的单调性。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<vector>
#include<cstring>
#define N 1000005
#define inf 0xfffffff
using namespace std;
typedef __int64 ll;
int q[N], a[N];
ll f[N];
ll getL(int x, int y){
return (a[y + 1] - a[x + 1]);
}
ll getR(int x, int y){
return f[y] - f[x] + 1ll * a[y + 1] * a[y + 1] - 1ll * a[x + 1] * a[x + 1];
}
int main(){
int n, c;
while(scanf("%d%d", &n, &c) && (n || c)){
int head = 1, tail = 1;q[1] = 0;
for(int i = 1;i <= n;i ++){
scanf("%d", &a[i]);
}
for(int i = 1;i <= n;i ++){
while(head < tail){
if(2ll * a[i] * getL(q[head], q[head + 1]) >= getR(q[head], q[head + 1]))head ++;
else break;
}
f[i] = f[q[head]] + 1ll * (a[i] - a[q[head] + 1]) * (a[i] - a[q[head] + 1]) + c;
while(head < tail){
ll x = getL(q[tail], i) * getR(q[tail - 1], q[tail]);
ll y = getL(q[tail - 1], q[tail]) * getR(q[tail], i);
if(x >= y)tail --;
else break;
}
q[++ tail] = i;
}
printf("%I64d\n", f[n]);
}
return 0;
}<strong>
</strong>