題意:已知股票每天的買入和賣出價格、買入上限和賣出上限以及最多能持有的股票數,問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;
}