题目大意:给出一个序列,可以连续出一段序列[l,r],费用为sum[j][i] ^2+M,求输出整个序列的最小费用。
思路:裸DP方程:f[i] = f[j] + (sum[i] - sum[j - 1]) ^ 2 + M,然后整理一下斜率优化
=> f[j] + sum[j]^2 = 2 * sum[i] * sum[j] - M - f[i]
y = f[j] + sum[j] ^ 2
k = 2 * sum[i]
x = sum[j]
CODE:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAX 500010 #define INF 1e15 using namespace std; struct Point{ long long x,y; Point(long long _ = 0,long long __ = 0):x(_),y(__) {} }q[MAX]; int cnt,M; long long src[MAX],sum[MAX],f[MAX]; int front,tail; inline double GetSlope(Point p1,Point p2) { if(p1.x == p2.x) return INF; return (double)(p2.y - p1.y) / (p2.x - p1.x); } inline void Insert(long long x,long long y) { Point temp(x,y); while(tail - front >= 2) if(GetSlope(q[tail],temp) < GetSlope(q[tail - 1],q[tail])) --tail; else break; q[++tail] = temp; } inline Point GetAns(double slope) { while(tail - front >= 2) if(GetSlope(q[front + 1],q[front + 2]) < slope) ++front; else break; return q[front + 1]; } int main() { while(scanf("%d%d",&cnt,&M) != EOF) { for(int i = 1; i <= cnt; ++i) { scanf("%I64d",&src[i]); sum[i] = sum[i - 1] + src[i]; } front = tail = 0; for(int i = 1; i <= cnt; ++i) { Insert(sum[i - 1],f[i - 1] + sum[i - 1] * sum[i - 1]); Point p = GetAns(sum[i] << 1); f[i] = p.y + sum[i] * sum[i] - (p.x * sum[i] << 1) + M; } printf("%I64d\n",f[cnt]); } return 0; }