欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

洛谷P4360 [CEOI2004]锯木厂选址(dp 斜率优化)

程序员文章站 2022-10-19 07:58:54
题意 "题目链接" Sol 枚举第二个球放的位置,用前缀和推一波之后发现可以斜率优化 cpp // luogu judger enable o2 include define Pair pair define MP(x, y) make_pair(x, y) define fi first defi ......

题意

题目链接

sol

枚举第二个球放的位置,用前缀和推一波之后发现可以斜率优化

// luogu-judger-enable-o2
#include<bits/stdc++.h> 
#define pair pair<int, int>
#define mp(x, y) make_pair(x, y)
#define fi first
#define se second
#define int long long 
#define ll long long 
#define fin(x) {freopen(#x".in","r",stdin);}
#define fout(x) {freopen(#x".out","w",stdout);}
using namespace std;
const int maxn = 1e6 + 10, mod = 1e9 + 7;
ll inf = 2e18 + 10;
const double eps = 1e-9;
template <typename a, typename b> inline bool chmin(a &a, b b){if(a > b) {a = b; return 1;} return 0;}
template <typename a, typename b> inline bool chmax(a &a, b b){if(a < b) {a = b; return 1;} return 0;}
template <typename a, typename b> inline ll add(a x, b y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
template <typename a, typename b> inline void add2(a &x, b y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
template <typename a, typename b> inline ll mul(a x, b y) {return 1ll * x * y % mod;}
template <typename a, typename b> inline void mul2(a &x, b y) {x = (1ll * x * y % mod + mod) % mod;}
template <typename a> inline void debug(a a){cout << a << '\n';}
template <typename a> inline ll sqr(a x){return 1ll * x * x;}
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int n, w[maxn], d[maxn], s[maxn], sw[maxn], g[maxn], f[maxn], q[maxn];
int calc(int l, int r) {
    if(l > r) return 0; 
    return s[r] - s[l - 1] - d[l - 1] * (sw[r] - sw[l - 1]);
}
double y(int x) {
    return g[x];
}
double x(int x) {
    return d[x];
}
double slope(int a, int b) {
    return double(y(b) - y(a)) / (x(b) - x(a));
}
signed main() {
    n = read();
    for(int i = 1; i <= n; i++) w[i] = read(), d[i] = read();
    reverse(w + 1, w + n + 1); reverse(d + 1, d + n + 1);
    for(int i = 1; i <= n; i++) d[i] += d[i - 1], s[i] = s[i - 1] + w[i] * d[i], sw[i] = w[i] + sw[i - 1];
    ll ans = inf;
    for(int i = 1; i <= n; i++) g[i] = calc(1, i - 1)- s[i] + d[i] * sw[i];
    q[1] = 0; 
    for(int i = 1, h = 1, t = 1; i <= n; i++) {
        f[i] = inf; 
        while(h < t && slope(q[h], q[h + 1]) < sw[i - 1]) h++;
        f[i] = g[q[h]] - d[q[h]] * sw[i - 1];
        while(h < t && slope(q[t - 1], q[t]) > slope(q[t], i)) t--;
        q[++t] = i;
        //for(int j = i - 1; j >= 1; j--) chmin(f[i], g[j] - d[j] * sw[i - 1]);
        
        f[i] += s[i - 1];
    }
    for(int i = 1; i <= n; i++) 
        f[i] += calc(i + 1, n), chmin(ans, f[i]);
    cout << ans;
    return 0;
}
/*

*/