1. 程式人生 > >洛谷P4360 [CEOI2004]鋸木廠選址(dp 斜率優化)

洛谷P4360 [CEOI2004]鋸木廠選址(dp 斜率優化)

題意

題目連結

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;
}
/*

*/