bzoj 1597: [Usaco2008 Mar]土地购买【斜率优化】

按xy降序排序,把能被完全包含的去掉
然后就得到了x升序y降序的一个数组
然后方程就显然了:f[i]=min(f[j]+y[j+1]x[i])
斜率优化转移
说起来我还不会斜率优化呢是不是该学一下了

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=50005;
int n,q[N],tot;
long long f[N];
struct qwe
{
	int x,y;
}a[N],b[N];
bool cmp(const qwe &a,const qwe &b)
{
	return a.x<b.x||(a.x==b.x&&a.y<b.y);
}
int read()
{
	int r=0,f=1;
	char p=getchar();
	while(p>'9'||p<'0')
	{
		if(p=='-')
			f=-1;
		p=getchar();
	}
	while(p>='0'&&p<='9')
	{
		r=r*10+p-48;
		p=getchar();
	}
	return r*f;
}
double clc(int k,int j)
{
	return (double)(f[j]-f[k])/(b[k+1].y-b[j+1].y);
}
int main()
{
	n=read();
	for(int i=1;i<=n;i++)
		a[i].x=read(),a[i].y=read();
	sort(a+1,a+1+n,cmp);
	for(int i=1;i<=n;i++)
	{
		while(tot&&b[tot].y<=a[i].y)
			tot--;
		b[++tot]=a[i];
	}
	int l=0,r=0;
	for(int i=1;i<=tot;i++)
	{
		while(l<r&&clc(q[l],q[l+1])<b[i].x)
			l++;
		f[i]=f[q[l]]+1ll*b[i].x*b[q[l]+1].y;
		while(l<r&&clc(q[r-1],q[r])>clc(q[r],i))
			r--;
		q[++r]=i;
	}
	printf("%lld\n",f[tot]);
	return 0;
}
posted @ 2018-04-24 20:44  lokiii  阅读(99)  评论(0编辑  收藏  举报