【DP HDU 3401】Trade

来源:互联网 发布:学生选课系统java实现 编辑:程序博客网 时间:2024/06/05 17:03

Description

    Recently, lxhgww is addicted to stock, he finds some regular patterns after a few days’ study.
    He forecasts the next T days’ stock market. On the i’th day, you can buy one stock with the price APi or sell one stock to get BPi.
    There are some other limits, one can buy at most ASi stocks on the i’th day and at most sell BSi stocks.
    Two trading days should have a interval of more than W days. That is to say, suppose you traded (any buy or sell stocks is regarded as a trade)on the i’th day, the next trading day must be on the (i+W+1)th day or later.
    What’s more, one can own no more than MaxP stocks at any time.
    Before the first day, lxhgww already has infinitely money but no stocks, of course he wants to earn as much money as possible from the stock market. So the question comes, how much at most can he earn?

Input

    The first line is an integer t, the case number.
    The first line of each case are three integers T , MaxP , W .(0 <= W < T <= 2000, 1 <= MaxP <= 2000) .
    The next T lines each has four integers APiBPiASiBSi(1<=BPi<=APi<=1000,1<=ASi,BSi<=MaxP), which are mentioned above.

Output

    The most money lxhgww can earn.

Sample Input

15 2 02 1 1 12 1 1 13 2 1 14 3 1 15 4 1 1

Sample Output

3

I think

    单调队列优化DP,注意初始化f[0][0]=0,etc,为使用优化应尽量将f[][]下标框内变量固定,框外变量进行变动。

Code

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>using namespace std;const int sm = 2000+5;int T,t,maxp,w,ans;int ap[sm],bp[sm],as[sm],bs[sm],f[sm][sm];int cq[sm],cqv[sm];int main() {    scanf("%d",&T);    while(T--) {        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]);        memset(f,0xaf,sizeof(f));        for(int i=1;i<=w+1;++i)            for(int j=0;j<=min(maxp,as[i]);++j)                f[i][j]=-ap[i]*j;        f[0][0]=0;        for(int i=2;i<=t;++i) {            for(int j=0;j<=maxp;++j)                f[i][j]=max(f[i-1][j],f[i][j]);            if(i-w-1<=0)continue;            int ss=1,tt=1,now,pre=i-w-1;            for(int j=0;j<=maxp;++j) {                now=f[pre][j]+j*ap[i];                while(ss<tt&&cq[tt-1]<now)--tt;                cq[tt]=now; cqv[tt++]=j;                while(ss<tt&&cqv[ss]+as[i]<j)ss++;                f[i][j]=max(f[i][j],cq[ss]-j*ap[i]);            }            ss=1,tt=1;            for(int j=maxp;j>=0;--j) {                now=f[pre][j]+j*bp[i];                while(ss<tt&&cq[tt-1]<now)--tt;                cq[tt]=now; cqv[tt++]=j;                while(ss<tt&&cqv[ss]-bs[i]>j)ss++;                f[i][j]=max(f[i][j],cq[ss]-j*bp[i]);            }        }        ans=0;        for(int i=0;i<=maxp;++i)            ans=max(ans,f[t][i]);        printf("%d\n",ans);    }    return 0;}