【题解】LuoGu2120:[ZJOI2007]仓库建设

原题传送门
初学斜率优化好题
先写出 O ( n 2 ) O(n^2) O(n2)DP
预处理 s i = ∑ j = 1 i x j p j , s p i = ∑ j = 1 i p j s_i=\sum_{j=1}^{i}x_jp_j,sp_i=\sum_{j=1}^{i}p_j si=j=1ixjpj,spi=j=1ipj
转移方程: d p [ i ] = m i n ( d p j − s i + s j + x i ( s p i − s p j ) ) + c i dp[i]=min(dp_j-s_i+s_j+x_i(sp_i-sp_j))+c_i dp[i]=min(dpjsi+sj+xi(spispj))+ci

考虑两个决策 x , y x,y x,y,满足 x > y x>y x>y
如果x这个决策比y靠后并且比y更优
那么应该满足 d p x − s i + s x + x i ( s p i − s p x ) < d p y − s i + s y + x i ( s p i − s p y ) dp_x-s_i+s_x+x_i(sp_i-sp_x)<dp_y-s_i+s_y+x_i(sp_i-sp_y) dpxsi+sx+xi(spispx)<dpysi+sy+xi(spispy)
化简得 ( d p x + s x ) − ( d p y + s y ) s p x − s p y < x i \frac{(dp_x+s_x)-(dp_y+s_y)}{sp_x-sp_y}<x_i spxspy(dpx+sx)(dpy+sy)<xi
s l o p e ( x , y ) = ( d p x + s x ) − ( d p y + s y ) s p x − s p y slope(x,y)=\frac{(dp_x+s_x)-(dp_y+s_y)}{sp_x-sp_y} slope(x,y)=spxspy(dpx+sx)(dpy+sy)
那么维护单调队列,保证这个相邻两个决策的“斜率”递增
每次取队首更新自己就行了

Code:

#include 
#define maxn 1000010
#define LL long long
using namespace std;
LL n, s[maxn], sp[maxn], c[maxn], dp[maxn], q[maxn], x[maxn];

inline LL read(){
	LL s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

double slope(int x, int y){ return 1.0 * (dp[x] + s[x] - dp[y] - s[y]) / (sp[x] - sp[y]); }

int main(){
	n = read();
	for (int i = 1; i <= n; ++i){
		x[i] = read(), sp[i] = read(), c[i] = read();
		s[i] = s[i - 1] + x[i] * sp[i], sp[i] += sp[i - 1];
	}
	int h = 0, t = 0;
	for (int i = 1; i <= n; ++i){
		while (h < t && slope(q[h + 1], q[h]) < x[i]) ++h;
		dp[i] = dp[q[h]] - s[i] + s[q[h]] + x[i] * (sp[i] - sp[q[h]]) + c[i];
		while (h < t && slope(q[t], q[t - 1]) > slope(i, q[t])) --t;
		q[++t] = i;
	}
	printf("%lld\n", dp[n]);
	return 0;
}

你可能感兴趣的:(题解,LuoGu,DP,斜率优化)