码迷,mamicode.com
首页 > 其他好文 > 详细

BZOJ1855 [Scoi2010]股票交易 【单调队列优化dp】

时间:2018-05-10 15:47:53      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:printf   lin   tail   枚举   inf   flag   c++   getchar   单调队列   

题目链接

BZOJ1855

题解

\(f[i][j]\)表示第\(i\)天结束时拥有\(j\)张股票时的最大收益
\(i \le W\),显然在这之前不可能有交易
\[f[i][j] = max\{f[i - 1][j],-ap[i] * j\} \quad [j \le as[i]]\]
否则,就有三种选择:
①购买
\[f[i][j] = max\{f[i - W - 1][k] - ap[i] * (j - k)\} \quad[k \le j][j - k \le as[i]]\]
②卖出
\[f[i][j] = max\{f[i - W - 1][k] + bp[i] * (k - j)\} \quad[k \ge j][k - j \le bs[i]]\]
③什么也不做
\[f[i][j] = max\{f[i][j],f[i - 1][j]\}\]

其中③总共是\(O(n^2)\)
①和②如果逐个枚举是\(O(n^3)\)的,无法承受
拆开式子可发现可以用单调队列优化成\(O(n^2)\)

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define LL long long int
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define cls(s) memset(s,-0x3f3f3f3f,sizeof(s))
using namespace std;
const int maxn = 2005,maxm = 100005,INF = 1000000000;
inline int read(){
    int out = 0,flag = 1; char c = getchar();
    while (c < 48 || c > 57){if (c == ‘-‘) flag = -1; c = getchar();}
    while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
    return out * flag;
}
int f[maxn][maxn],T,P,W,ap[maxn],bp[maxn],as[maxn],bs[maxn];
struct node{
    int k,v;
}q[maxn];
int head,tail;
int main(){
    T = read(); P = read(); W = read();
    REP(i,T) ap[i] = read(),bp[i] = read(),as[i] = read(),bs[i] = read();
    cls(f); f[0][0] = 0; int ans = 0;
    for (int i = 1; i <= T; i++){
        for (int j = 0; j <= P; j++) f[i][j] = f[i - 1][j];
        if (i <= W){
            for (int j = 0; j <= as[i]; j++)
                f[i][j] = max(f[i][j],-ap[i] * j);
        }
        else {
            head = 0; tail = -1;
            for (int j = 0; j <= P; j++){
                while (head <= tail && (j - q[head].k) > as[i]) head++;
                while (head <= tail && q[tail].v < f[i - W - 1][j] + ap[i] * j) tail--;
                q[++tail] = (node){j,f[i - W - 1][j] + ap[i] * j};
                f[i][j] = max(f[i][j],q[head].v - ap[i] * j);
            }
            head = 0; tail = -1;
            for (int j = P; j >= 0; j--){
                while (head <= tail && (q[head].k - j) > bs[i]) head++;
                while (head <= tail && q[tail].v < f[i - W - 1][j] + bp[i] * j) tail--;
                q[++tail] = (node){j,f[i - W - 1][j] + bp[i] * j};
                f[i][j] = max(f[i][j],q[head].v - bp[i] * j);
            }
        }
        ans = max(ans,f[i][0]);
    }
    printf("%d\n",ans);
    return 0;
}

BZOJ1855 [Scoi2010]股票交易 【单调队列优化dp】

标签:printf   lin   tail   枚举   inf   flag   c++   getchar   单调队列   

原文地址:https://www.cnblogs.com/Mychael/p/9019607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!