题目大意:山坡上有一些仓库,下雨了,要把所有仓库中的东西转移出来,每转移一单位的东西走一个单位长度需要花费1,在i处建立一个仓库需要花费cost[i],求最小的花费。
思路:和小P的牧场好像啊。。。
记录两个前缀和,sum[i] = Σsrc[i]
_sum[i] = Σsrc[i] * pos[i],
然后DP方程:f[i] = f[j] + (sum[i] - sum[j]) * pos[i] - _sum[i] + _sum[j] + cost[i]
注意转换long long 数据有可能乘爆
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; int pos[MAX],num[MAX],cost[MAX]; long long sum[MAX],_sum[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 >= 2) 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 >= 2) 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%d%d",&pos[i],&num[i],&cost[i]); sum[i] = sum[i - 1] + num[i]; _sum[i] = _sum[i - 1] + (long long)pos[i] * num[i]; } memset(f,0x3f,sizeof(f)); f[0] = 0; for(int i = 1; i <= cnt; ++i) { Insert(sum[i - 1],f[i - 1] + _sum[i - 1]); Point ans = GetAns(pos[i]); f[i] = ans.y + sum[i] * pos[i] - ans.x * pos[i] - _sum[i] + cost[i]; } cout << f[cnt] << endl; return 0; }
时间: 2024-11-07 00:11:37