01背包问题

#include <stdio.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
const int maxn = 100;
const int maxm = 100;
int main()
{
	int n, m,i,j;
	int need[maxn], value[maxm];//need为物品所需空间,value为物品对应价值
	//int dp[maxn][maxn] = { 0 };
	int dp[maxn] = { 0 };
	scanf("%d %d", &n, &m);
	//输入need数组和value数组
	for (int i = 1; i <= n; i++)
		scanf("%d", &need[i]);
	for (int j = 1; j <= n; j++)
		scanf("%d", &value[j]);
	//递推边界初始化
	/*for (int j = 1; j <= m; j++)
		dp[0][j] = 0;*/
	//动态规划(二维数组)
	/*for(int i=1;i<=n;i++)
		for (int j = 1; j <= m;j++)
		{
			if (need[i] > j)
				dp[i][j] = dp[i - 1][j];
			else
				dp[i][j] = max(dp[i-1][j],dp[i-1][j-need[i]]+value[i]);
		}*/
	//动态规划(优化为一维滚动数组)
	for (i = 1; i <= n; i++)
		for (j = m; j >= need[i]; j--)
			dp[j] = max( dp[j],dp[j - need[i]] + value[i] );
	//printf("%d\n", dp[k]);
	return 0;
}

上一篇:LOJ2527 HAOI2018 染色 容斥、生成函数、多项式求逆


下一篇:HCIA-Kunpeng练习题第一篇