题目链接
题解
设(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
",ans);
return 0;
}