BZOJ1911: [Apio2010]特别行动队(dp 斜率优化)

题意

题目链接

Sol

裸的斜率优化,注意推导过程中的符号问题。

#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, INF = 6e18 + 10;
const double eps = 1e-9;
template <typename Y> inline void chmin(Y &a, Y b){a = (a < b ? a : b);}
template <typename Y> inline void chmax(Y &a, Y b){a = (a > b ? a : b);}
template <typename Y> inline void debug(Y a){cout << a << '\n';}
template <typename Y> inline LL sqr(Y x){return 1ll * x * x;}
int add(int x, int y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
void add2(int &x, int y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
int mul(int x, int y) {return 1ll * x * y % mod;}
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, S[MAXN], A, B, C, f[MAXN], q[MAXN];
int F(int x) {
    return A * sqr(x) + B * x + C;
}
double Y(int x) {
    return A * sqr(S[x]) - B * S[x] + f[x];
}
double X(int x) {
    return S[x];
}
double slope(int a, int b) {
//  debug((Y(b) - Y(a)) / (X(b) - X(a)));
    return double(Y(b) - Y(a)) / (X(b) - X(a));
}
signed main() {
    N = read(); A = read(); B = read(); C = read();
    for(int i = 1; i <= N; i++) S[i] = S[i - 1] + read();
    q[1] = 0;
    for(int i = 1, h = 1, t = 1; i <= N; i++) {
        while(h < t && slope(q[h], q[h + 1]) > 2 * A * S[i]) h++;
        f[i] = f[q[h]] + F(S[i] - S[q[h]]);
        //printf("%d\n", q[h]);
        while(h < t && slope(q[t - 1], q[t]) < slope(q[t], i)) t--;
        q[++t] = i;
    }
    cout << f[N];
    return 0;
}
/*
7
-1 160 -2000
14 82 61 85 41 10 34
*/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
posted @ 2018-12-30 20:16  自为风月马前卒  阅读(167)  评论(0编辑  收藏  举报

Contact with me