HDU 5410 CRB and His Birthday(DP)

题目让求总共m钱最多能买多少物品。

令dp[i][j][0]表示前i种物品,共j钱,不买第i种物品所能买到的最大值。dp[i][j][1]表示前i种物品,共j钱,买第i种物品所能买到的最大值。

那么转移方程为:

dp[i][j][0]=max(dp[i-1][j][1],dp[i-1][j][0])

dp[i][j][1]=max(dp[i][j-w[i]][1]+a[i],dp[i][j-w[i]][0]+a[i]+b[i])(分别表示买i种超过一个了,和买i种一个)

然后答案就是max(dp[n][m][0],dp[n][m][1])

#pragma warning(disable:4996)
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1005;
int w[N], a[N], b[N];
int dp[N][2005][2];

int main(){
	//freopen("in.txt", "r", stdin);
	int t; scanf("%d", &t);
	while (t--){
		int m, n; scanf("%d %d", &m, &n);
		for (int i = 1; i <= n; i++){
			scanf("%d %d %d", w + i, a + i, b + i);
		}

		memset(dp, 0, sizeof dp);
		for (int i = 1; i <= n; i++){
			for (int j = 0; j < w[i]; j++){
				dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j][1]);
				//不知道自己怎么想的。。。。这都能写错。
				//dp[i][j][0] = dp[i - 1][j][0];
				dp[i][j][1] = 0;
			}
			for (int j = w[i]; j <= m; j++){
				dp[i][j][0] = max(dp[i - 1][j][0], dp[i - 1][j][1]);
				dp[i][j][1] = max(dp[i][j - w[i]][0] + a[i] + b[i], dp[i][j - w[i]][1] + a[i]);
			}
		}
		int ans = max(dp[n][m][0], dp[n][m][1]);
		printf("%d\n", ans);

	}
	return 0;
}


你可能感兴趣的:(HDU 5410 CRB and His Birthday(DP))