HDU 3401 Trade [monotonous queue + dp]

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.