Question: I know the daily purchase and sale prices, the maximum Purchase and Sale limits, and the maximum number of votes that can be held for a stock. What is the maximum benefit after n days.
[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;
}
}
// The first w + 1 days can only be bought
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", & t, & maxp, & w );
For (int I = 1; I <= t; ++ I ){
Scanf ("% d", & ap [I], & bp [I], & as [I], & bs [I]);
}
DP ();
}
Return 0;
}