题目大意:给出一排东西,现在要建造防御塔,在i处建造防御塔的花费是cost[i],所有东西的花费是他它距离右侧最近的防御塔的距离。求最小花费。
思路:很简单的斜率优化。DP方程:f[i] = f[j] + (i - j - 1) * (i - j) / 2 + cost[i]
然后简单整理一下会发现f[j] + (j + 1) * j / 2 = f[i] - i ^ 2 + i * j + i / 2 + cost[i]
之后移项,得到y = f[j] + j * (j + 1) / 2;
k = i,x = j;
然后斜率优化一下。。。
CODE:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAX 1000010 using namespace std; struct Point{ long long x,y; Point(long long _ = 0,long long __ = 0):x(_),y(__) {} }q[MAX]; int cnt,cost[MAX]; long long f[MAX]; int front,tail; inline double GetSlope(const Point &a,const Point &b) { if(a.x == b.x) return 1e15; return (double)(a.y - b.y) / (a.x - b.x); } inline void Insert(long long x,long long y) { Point now(x,y); while(tail - front > 1) if(GetSlope(q[tail],now) < GetSlope(q[tail - 1],q[tail])) --tail; else break; q[++tail] = now; } inline Point GetAns(double slope) { while(tail - front > 1) if(GetSlope(q[front + 1],q[front + 2]) < slope) ++front; else break; return q[front + 1]; } int main() { cin >> cnt; for(int i = 1; i <= cnt; ++i) scanf("%d",&cost[i]); for(int i = 1; i <= cnt; ++i) { Insert(i - 1,f[i - 1] + (long long)i * (i - 1) / 2); Point ans = GetAns(i); f[i] = ans.y + (long long)i * (i - 1) / 2 - (long long)i * ans.x + cost[i]; } cout << f[cnt] << endl; return 0; }
原文地址:http://blog.csdn.net/jiangyuze831/article/details/41679615