BZOJ3156: 防御准备 【斜率优化dp】
3156: 防御准备
Time Limit: 10 Sec Memory Limit: 512 MBSubmit: 2207 Solved: 933
[Submit][Status][Discuss]
Description
Input
第一行为一个整数N表示战线的总长度。
第二行N个整数,第i个整数表示在位置i放置守卫塔的花费Ai。
Output
共一个整数,表示最小的战线花费值。
Sample Input
10
2 3 1 5 4 5 6 3 1 2
Sample Output
18
HINT
1<=N<=10^6,1<=Ai<=10^9
练了几题,这类题目的模式还是很固定好写的
就不推了
设f[i]表示i位置放防御塔的最小代价
显然有f[i] = min{f[j] + (i - j) * (i - j - 1) / 2} + A[i] 【中间那一段就是中间木偶的代价】
去掉常数化简有2 * i * j + 2 * f[i] = (2 * f[j] + j^2 + j)
令y = 2 * f[j] + j^2 + j,x = j
就是y = 2i * x + 2 * f[i]
化为求截距最小,由于所有值都是单调递增,维护下凸包
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define eps 1e-9 #define LL long long int #define REP(i,n) for (int i = 1; i <= (n); i++) #define fo(i,x,y) for (int i = (x); i <= (y); i++) #define Redge(u) for (int k = head[u]; k != -1; k = edge[k].next) using namespace std; const int maxn = 1000005,maxm = 100005,INF = 1000000000; inline LL read(){ LL out = 0,flag = 1;char c = getchar(); while (c < 48 || c > 57) {if (c == '-') flag = -1; c = getchar();} while (c >= 48 && c <= 57) {out = out * 10 + c - 48; c = getchar();} return out * flag; } LL n,q[maxn],head,tail; LL A[maxn],f[maxn]; inline double slope(LL u,LL v){ double y1 = 2 * f[u] + u * u + u,y2 = 2 * f[v] + v * v + v; return (y1 - y2) / (u - v); } inline LL getf(LL i,LL j){ return f[j] + (i - j) * (i - j - 1) / 2 + A[i]; } int main() { n = read(); REP(i,n) A[i] = read(); head = tail = 0; for (LL i = 1; i <= n; i++){ while (head < tail && slope(q[head],q[head + 1]) + eps < 2 * i) head++; f[i] = getf(i,q[head]); while (head < tail && slope(q[tail],q[tail - 1]) + eps > slope(i,q[tail])) tail--; q[++tail] = i; } cout<<f[n]<<endl; return 0; }