[Template] slope optimization dp

Topic links: https://codeforces.com/problemset/problem/1083/E

I wanted to write a few dollars, and found that the slope is to optimize dp, just did how did the slope dp, tidy up the board.

Feeling on the slope dp optimization convex hull and almost maintenance on a sub-sub (lower) the convex hull.

 1 // f[j] = yi * xj + wi - xi * yi + fi;
 2 //维护上凸包,斜率递减
 3 #include<bits/stdc++.h>
 4 using namespace std;
 5 typedef long long ll;
 6 const int N = 1e6 + 9;
 7 struct Point{
 8     ll x,y,w;
 9     bool operator < (const Point& b)const{
10         return x < b.x;
11     }
12 }a[N];
13 ll q[N],f[N];
14 double cal(int i,int j){
15     return 1.0 * (f[j] - f[i]) / (a[j].x - a[i].x);
16 }
17 int main(){
18     int n; scanf("%d",&n);
19     for(int i =1;i<=n;++i) scanf("%lld %lld %lld",&a[i].x,&a[i].y,&a[i].w);
20     sort(a+1,a+1+n);
21     int l = 1, r = 1;
22     ll ans = -1000000000000000;
23     for(int i = 1;i<=n;++i){
24         while( l < r && cal(q[l],q[l+1]) >= a[i].y ) ++l;
25         int j = q[l];
26         f[i] = f[j] - a[i].y * a[j].x - a[i].w + a[i].x * a[i].y;
27         ans = max(ans,f[i]);
28         while( l < r && cal(q[r-1],q[r]) <= cal(q[r],i) ) --r;
29         q[++r] = i;
30     }
31     printf("%lld",ans);
32 }
View Code

 

Guess you like

Origin www.cnblogs.com/xiaobuxie/p/12239333.html