当前位置:编程学习 > C/C++ >>

HDU 3401 Trade[单调队列+dp]

题意:已知股票每天的买入和卖出价格、买入上限和卖出上限以及最多能持有的股票数,问n天后的最大收益是多少。
[cpp]
#include <iostream> 
#include <cstring> 
#include <cstdio> 
#include <algorithm> 
#include <cmath> 
 
using namespace std; 
 
const int oo = 1 << 30; 
const int maxn = 2010; 
int tcase; 
int t, maxp, w; 
int ap[maxn], bp[maxn]; 
int as[maxn], bs[maxn]; 
int dp[maxn][maxn]; 
int head, tail; 
int q[maxn][2]; 
 
void DP() 

    for (int i = 0; i < maxn; ++i) { 
        for (int j = 0; j < maxn; ++j) { 
            dp[i][j] = -oo; 
        } 
    } 
    // 前w+1天只能买入  
    for (int i = 1; i <= w + 1; ++i) { 
        for (int j = 0; j <= min(maxp, as[i]); ++j) { 
            dp[i][j] = -ap[i] * j; 
        } 
    } 
    for (int i = 2; i <= t; ++i) { 
        /*for (int j = 0; j <= maxp; ++j) {
            dp[i][j] = max(dp[i][j], dp[i-1][j]);
        }
        if (i <= w + 1) continue;
        */ 
        head = tail = 0; 
        for (int j = 0; j <= maxp; ++j) { 
            dp[i][j] = max(dp[i][j], dp[i-1][j]); 
            if (i <= w + 1) continue; 
            while (head < tail && q[tail-1][1] <= dp[i-w-1][j] + ap[i] * j) { 
                tail--; 
            } 
            q[tail][0] = j; 
            q[tail++][1] = dp[i-w-1][j] + ap[i] * j; 
            while (head < tail && j - q[head][0] > as[i]) { 
                head++; 
            } 
            dp[i][j] = max(dp[i][j], q[head][1] - ap[i] * j); 
        } 
        head = tail = 0; 
        for (int j = maxp; j >= 0; --j) { 
            if (i <= w + 1) continue; 
            while (head < tail && q[tail-1][1] <= dp[i-w-1][j] + bp[i] * j) { 
                tail--; 
            } 
            q[tail][0] = j; 
            q[tail++][1] = dp[i-w-1][j] + bp[i] * j; 
            while (head < tail && q[head][0] - j > bs[i]) { 
                head++; 
            } 
            dp[i][j] = max(dp[i][j], q[head][1] - bp[i] * j); 
        } 
    } 
    int ans = -oo; 
    for (int i = 0; i <= maxp; ++i) { 
        ans = max(ans, dp[t][i]); 
    } 
    printf("%d\n", ans); 

 
int main() 

    scanf("%d", &tcase); 
    while (tcase--) { 
        scanf("%d%d%d", &t, &maxp, &w); 
        for (int i = 1; i <= t; ++i) { 
            scanf("%d%d%d%d", &ap[i], &bp[i], &as[i], &bs[i]); 
        } 
        DP(); 
    } 
    return 0; 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,