Trade
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6208 Accepted Submission(s): 2154
Problem 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 APi,BPi,ASi,BSi( 1<=BPi<=APi<=1000,1<=ASi,BSi<=MaxP), which are mentioned above.
Output
The most money lxhgww can earn
Sample Input
1
5 2 0
2 1 1 1
2 1 1 1
3 2 1 1
4 3 1 1
5 4 1 1
Sample Output
3
买入:
dp[i][j]=max(dp[i-w-1][k]-(j-k)*a[i]);(0<j-k<=buy[i])
卖出:
dp[i][j]=max(dp[i-w-1][k]+(k-j)*b[i]);(0<k-j<=sell[i])
不作为:
dp[i][j]=max(dp[i][j],dp[i-1][j]);
dp[i][j]=max(dp[i-w-1][k]+k*a[i])-j*a[i];
dp[i][j]=max(dp[i-w-1][k]+k*b[i])-j*a[i];
买
令f(k)=dp[i][k]+k*AP[i]
f(j)=max(f(k)) (j-AS[i]<=k<=j)
所以dp[i][j]=f(j)-j*AP[i]
卖
令ff(k)=dp[i][k]+k*AP[i]
ff(j)=max(ff(k)) (j<=k<=j+BS[i])
所以dp[i][j]=ff(j)-j*BP[i]
#include <bits/stdc++.h>
using namespace std;
const int maxn=2005;
int q[maxn],a[maxn],b[maxn],buy[maxn],sell[maxn],f[maxn][maxn];
int n,maxp,w;
void input()
{
scanf("%d%d%d",&n,&maxp,&w);
for(int i=1;i<=n;i++)
scanf("%d%d%d%d",&a[i],&b[i],&buy[i],&sell[i]);
for(int i=0;i<=n;i++)
for(int j=0;j<=maxp;j++)
f[i][j]=-1e9;
}
void work()
{
f[0][0]=0;
for(int i=1;i<=w+1;i++)
for(int j=0;j<=buy[i];j++)
f[i][j]=-a[i]*j;
for(int i=1;i<=n;i++)
{
for(int j=0;j<=maxp;j++)
f[i][j]=max(f[i][j],f[i-1][j]); //不作为
if(i<=w+1) continue;
//买
int pre=i-w-1;
int head=1,tail=0;
for(int j=0;j<=maxp;j++)
{
while(head<=tail&&q[head]<j-buy[i]) head++;
int tmp=f[pre][j];
while(head<=tail&&f[pre][q[tail]]-(j-q[tail])*a[i]<tmp) tail--;
q[++tail]=j;
if(head<=tail) f[i][j]=max(f[i][j],f[pre][q[head]]-(j-q[head])*a[i]);
}
//卖
head=1,tail=0;
for(int j=maxp;j>=0;j--)
{
while(head<=tail&&q[head]>j+sell[i]) head++;
int tmp=f[pre][j];
while(head<=tail&&f[pre][q[tail]]+(q[tail]-j)*b[i]<tmp) tail--;
q[++tail]=j;
if(head<=tail) f[i][j]=max(f[i][j],f[pre][q[head]]+(q[head]-j)*b[i]);
}
}
int ans=0;
for(int i=0;i<=maxp;i++)
ans=max(ans,f[n][i]);
printf("%d\n",ans);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
input();
work();
}
return 0;
}