HDOJ2602(01背包模板题 一维AC+二维TL)

#include  
#include 
#include 
#include 
#include 
#include 
#include 
#include
#include 

using namespace std;
#define INF  0xfffff;//0x代表十六进制
#define M 1050

struct aaa
{
	int w;
	int v;
}a[M];

int dp[M];  //M质量时的最大值

int main()
{
	int t;
	cin >> t;
	for (int i = 1; i <= t; i++)
	{
		memset(dp, 0, sizeof(dp));
		int n, m;  //m背包载重
		cin >> n >> m;
		for (int i = 0; i < n; i++) cin >> a[i].v;
		for (int i = 0; i < n; i++) cin >> a[i].w;
		for (int i = 0; i < n; i++)
			for (int j = m; j >= a[i].w; j--) dp[j] = max(dp[j - a[i].w] + a[i].v, dp[j]);  //j是背包剩余质量
		cout << dp[m] << endl;
	}
}


二维

#include  
#include 
#include 
#include 
#include 
#include 
#include 
#include
#include 


using namespace std;
#define INF  0xfffff;//0x代表十六进制
#define M 150


struct aaa
{
	int w;
	int v;
}a[M];

int dp[M][M]; //dp[i][j] 放入i个 重量达到j时的最大价值

int main()
{
	int t;
	cin >> t;
	for (int i = 0; i < t; i++)
	{
		int n, m;
		cin >> n >> m;
		for (int i = 0; i < n; i++) cin >> a[i].w;
		for (int i = 0; i < n; i++) cin >> a[i].v;
		for(int i=0;i			for (int j = m; j>=a[i].w; j--)
				dp[i][j] = max(dp[i-1][j], dp[i - 1][j - a[i].w] + a[i].v);  //前者不放入 后者放入
		cout << dp[n - 1][m] << endl;
	}
}


你可能感兴趣的:(动态规划)