Bzoj 1957 land purchase

Source: Internet
Author: User

This is my first question of slope optimization, which is a souvenir.

First, perform filtering, and then the dynamic planning expression will soon write out f (I) = min (f (I) + B [J + 1] * A [I]).

Then we need to optimize the slope. Obviously, everything here is monotonous, so we only need to maintain the monotonous queue.

The cal function calculates the slope. For details, refer to the Code (refer to others). You need to exercise more in the future.

 1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 using namespace std; 5 long long f[500005]; 6 int a[500005]; 7 int n; 8 long long u[50005],v[50005]; 9 struct node10 {11     long long x,y;12 }p[50005];13 int q[50005];14 int head,tail;15 bool cmp(int x,int y)16 {17     if(u[x]!=u[y])return u[x]<u[y];18     else return v[x]<v[y];19 }20 int m;21 double cal(int x,int y)22 {23     return (double)(f[y]-f[x])/(p[x+1].y-p[y+1].y);24 }25 int main()26 {27     scanf("%d",&n);28     for(int i=1;i<=n;i++)29     {30         a[i]=i;31         scanf("%lld%lld",&u[i],&v[i]);32     }33     sort(a+1,a+n+1,cmp);34     for(int i=1;i<=n;i++)35     {36         while(m && p[m].y<=v[a[i]])m--;37         m++;38         p[m].x=u[a[i]];39         p[m].y=v[a[i]];40     }41     n=m;42     for(int i=1;i<=n;i++)43     {44         while(head<tail && cal(q[head],q[head+1])<p[i].x)head++;45         int t=q[head];46         f[i]=f[t]+p[t+1].y*p[i].x;47         while(head<tail && cal(q[tail-1],q[tail])>cal(q[tail],i))tail--;48         q[++tail]=i;49     }50     printf("%lld\n",f[n]);51     return 0;52 }53     
View code

 

Bzoj 1957 land purchase

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.