1. 程式人生 > >HDU 3401 Trade(DP + 單調佇列優化)

HDU 3401 Trade(DP + 單調佇列優化)

任重而道遠

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

AC程式碼:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int N = 2e3 + 5, oo = 1e9 + 7;
struct Node {int id, val;} q[N];
int dp[N][N], ap[N], bp[N], as[N], bs[N];
int t, T, MaxP, W, head, tail;

void init () {
	for (int i = 0; i < N; i++)
		for (int j = 0; j < N; j++)
		dp[i][j] = -oo;
	for (int i = 1; i <= W + 1; i++)
		for (int j = 0; j <= min (as[i], MaxP); j++)
		dp[i][j] = -j * ap[i];
}

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]);
		init ();
		for (int i = 1; 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;
			int pre = i - W - 1;
			head = 1, tail = 0;
			for (int j = 0; j <= MaxP; j++) {
				int sww = dp[pre][j] + j * ap[i];
				while (head <= tail && q[tail].val < sww) tail--;
				q[++tail] = (Node) {j, sww};
				while (head <= tail && j - q[head].id > as[i]) head++;
				dp[i][j] = max (dp[i][j], q[head].val - j * ap[i]);
			}
			head = 1, tail = 0;
			for (int j = MaxP; j >= 0; j--) {
				int sww = dp[pre][j] + j * bp[i];
				while (head <= tail && q[tail].val < sww) tail--;
				q[++tail] = (Node) {j, sww};
				while (head <= tail && q[head].id - j > bs[i]) head++;
				dp[i][j] = max (dp[i][j], q[head].val - j * bp[i]);
			}
		}
		int sww = -oo;
		for (int j = 0; j <= MaxP; j++) sww = max (sww, dp[T][j]);
		printf ("%d\n", sww);
	}
}