[BZOJ1597]土地购买 斜率优化
dp方程较难想
#include<cstdio> #include<algorithm> using namespace std; int top=0,x[50010],y[50010]; long long dp[50010]; int q[50010],n; struct S{ long long int x,y; }s[50010]; bool cmp(S a,S b) { if(a.x==b.x) return a.y<b.y; else return a.x<b.x; } double slope(int j,int k) { return double((dp[j]-dp[k])/(y[k+1]-y[j+1])); } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%lld %lld",&s[i].x,&s[i].y); sort(s+1,s+1+n,cmp); for(int i=1;i<=n;i++) { while(top && s[i].y>=y[top]) top--; x[++top]=s[i].x; y[top]=s[i].y; } int head=0,tail=0; for(int i=1;i<=top;i++) { while(head<tail && slope(q[head+1],q[head])<x[i]) head++; dp[i]=dp[q[head]]+x[i]*y[q[head]+1]; while(head<tail && slope(q[tail],q[tail-1])>slope(i,q[tail])) tail--; q[++tail]=i; // printf("%d,",dp[i]); } printf("%lld",dp[top]); return 0; }
int相乘如果结果超出int,会出错。