nyoj289 apple--01 backpack

The state transition equation is: dp[i][j] represents the maximum value of i items put into a knapsack with capacity j

dp[i][j] = max(dp[i-1][j], dp[i-1][j-size[i]]+value[i]);

Analysis: There are two options for whether the item i is put into the backpack: if it is not put into the backpack, the value of dp[i][j] is equal to the maximum value of the i-1 item in the backpack with capacity j, which is

dp[i][j] = dp[i-1][j],

If it is put into a backpack, the value of dp[i][j] is equal to the maximum value of i-1 items put into a backpack with a capacity of j-size[i], that is

dp[i][j] = dp[i-1][j-size[i]]+value[i] ;



#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1010;
typedef struct Apple
{
	int size,value;
}Apple;
Apple apple[maxn];
int res[maxn][maxn];
intmain()
{
	int n,v;
	while(scanf("%d%d",&n,&v)==2 && (n&&v))
	{
		memset(res,0,sizeof(res));
		int sum = 0;
		for(int i=1;i<=n;++i)
		{
			scanf("%d%d",&apple[i].size,&apple[i].value);
		}
		
		for(int i=1;i<=n;++i)
			for(int j=1;j<=v;++j)
				if(apple[i].size<=j)//When the space of the backpack is greater than the size of the i-th apple
					res[i][j] = max(res[i-1][j],res[i-1][j-apple[i].size]+apple[i].value);
				else
					res[i][j] = res[i-1][j];//Otherwise, the backpack space cannot hold this apple, and the value of the loaded apple at this time is equal to the value of the apple in the backpack that does not put this apple
		printf("%d\n",res[n][v]);
	}
	return 0;
}

It can be seen from the calculation of res[i][j] above that only res[i-1][0...j] is used in the calculation of res[i][j], and
no other sub-problems are used, so the sub-problems are stored in the When the solution of , only the solution of the res[i-1] subproblem is stored.

This reduces res to a one-dimensional array! !


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1010;
typedef struct Apple
{
	int size,value;
}Apple;
Apple apple[maxn];
int res[maxn];
intmain()
{
	int n,v;
	while(scanf("%d%d",&n,&v)==2 && (n&&v))
	{
		memset(res,0,sizeof(res));
		int sum = 0;
		for(int i=1;i<=n;++i)
			scanf("%d%d",&apple[i].size,&apple[i].value);
		
		for(int i=1;i<=n;++i)
			for(int j=v;j>=apple[i].size;--j)
					res[j] = max(res[j],res[j-apple[i].size]+apple[i].value);
		printf("%d\n",res[v]);
	}
	return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324850455&siteId=291194637