【BZOJ】【P3437】【小P的牧场】【题解】【斜率优化】

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=3437

一图流


Code:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
typedef long long LL;
struct point{
	LL x,y;
	point(LL _x=0,LL _y=0){x=_x;y=_y;}
	LL operator*(point oth){return x*oth.y-y*oth.x;}
	LL operator^(point oth){return x*oth.x+y*oth.y;}
	point operator-(point oth){return point(x-oth.x,y-oth.y);}
};
LL f[maxn],bksum[maxn],sum[maxn];
int a[maxn],b[maxn],n;
struct CH{
	vector<point>ch;
	void push_back(point p){
		while(ch.size()>1&&(p-ch.back())*(ch.back()-ch[ch.size()-2])>=0)ch.pop_back();
		ch.push_back(p);
	}
	LL Qmin(point p){
		int l=0,r=ch.size()-1;
		LL ans=(1LL<<61);
		while(r-l>2){
			int mid1=l+(r-l)/3;
			int mid2=r-(r-l)/3;
			if((p^ch[mid1])<(p^ch[mid2]))
				r=mid2;
			else l=mid1;
		}for(int i=l;i<=r;i++)ans=min(ans,p^ch[i]);
		return ans;
	}
}C;
int getint(){
	int res=0;char c=getchar();
	while(!isdigit(c))c=getchar();
	while(isdigit(c))res=res*10+c-'0',c=getchar();
	return res;
}
int main(){
	n=getint();
	for(int i=1;i<=n;++i)a[i]=getint();
	for(int i=1;i<=n;++i)b[i]=getint();
	for(int i=1;i<=n;i++)sum[i]=sum[i-1]+b[i];
	for(int i=1;i<=n;i++)bksum[i]=bksum[i-1]+(LL)i*b[i];
	C.push_back(point(0,0));
	for(int i=1;i<=n;i++){
		f[i]=C.Qmin(point(-i,1))+a[i]+(LL)i*sum[i]-bksum[i];		
		C.push_back(point(sum[i],f[i]+bksum[i]));
	}cout<<f[n]<<endl;
	return 0;
}


你可能感兴趣的:(bzoj)