[Dynamic programming] Complete backpack: piggy bank (just full)

The backpack is exactly full problem:

There are n items whose weights (or occupied space) are w1, W.,...Wn. The values ​​are V1, 2....n. ←
Given a knapsack with a total capacity of W, each Items can only be placed in the backpack as a whole or not.
Q: How to choose the items put into the backpack so that the total weight of the items in the backpack is exactly W , and the total value is the largest/smallest?

The problem of just filling the backpack is the same as that of the ordinary 01 backpack, but the initialization is different + finally judge whether it can be filled

dp[i][j]: the maximum value of the first i items that are just filled with j

Initialization problem:

Just fill up to find the minimum value: dp->inf,dp[0]=0

Just fill up to find the maximum value: dp->-inf, dp[0]=0

understand:

(1) Initialization refers to the legal state in which no items are put into the backpack.

① A backpack with a capacity of 0 can be filled with nothing, and the value is 0, so dp[0]=0

② A backpack whose capacity is not 0 cannot be filled without loading anything, and it is in an undefined state, so it should be assigned infinite

(2) The current legal solution must be derived from the previous legal state. If dp[m] is still inf after the end of the loop, it means that there is no legal state that can be derived to m, which means that several of the n numbers cannot be filled. m

Code:

void input()
{
	cin>>e>>f;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>p[i]>>w[i];
	}
}
int main()
{
	input();
	memset(dp,inf,sizeof(dp));
	dp[0]=0;
	int v=f-e;
	for(int i=1;i<=n;i++)
	{
		for(int j=w[i];j<=v;j++)
		{
			dp[j]=min(dp[j],dp[j-w[i]]+p[i]);
		}
	}
	if(dp[v]==inf)
	{
		cout<<"impossible"<<endl;
	}
	else
	{
		cout<<dp[v]<<endl;
	}
  
}

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/124001135