【文文殿下】[CEOI2004]锯木厂选址 题解

题解

我们枚举建厂的位置,发现有个\(n^2\)的DP。随手搞个斜率优化到\(O(n)\)

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
const int maxn = 21000 ;
const ll inf = 100000000000000LL;
int n;
ll f[maxn];
ll w[maxn],s[maxn],m[maxn],h[maxn],cnt[maxn];
ll d[maxn],wet[maxn];
int q[maxn],l,r;
ll calc(int j,int i) {
	//return s[j-1]+s[i-1]-s[j]-(h[i-1]-h[j])*d[j]+s[n]-s[i]-(h[n]-h[i])*d[i];
	return s[n]-(h[i-1]-h[j-1])*d[j]-(h[n]-h[i-1])*d[i];
}
double slope(int a,int b) {
	double tmp1 = h[b-1]*d[b]-h[a-1]*d[a],tmp2=d[b]-d[a];
	return tmp1/tmp2;
}
int main() {
	//freopen("test.in","r",stdin);
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin>>n;
	for(int i = n;i;--i) cin>>wet[i]>>d[i];
	for(int i = 1;i<=n;++i) {
		d[i]+=d[i-1];
		h[i]=h[i-1]+wet[i];
		s[i]=s[i-1]+wet[i]*d[i];
	}
	ll ans = inf;
	l=r=0;
	for(int i = 1;i<=n;++i) {
		while(l<r&&slope(q[l],q[l+1])<=h[i-1]) ++l;
		int j = q[l];
		f[i]=calc(j,i);
		ans=min(ans,f[i]);
		while(l<r&&slope(q[r-1],q[r])>=slope(q[r],i)) --r;
		q[++r]=i;
	}
	cout<<ans<<endl;
	return 0;
}

posted @ 2019-01-17 02:01  文文殿下  阅读(359)  评论(0编辑  收藏  举报