Classic 01 knapsack problem (one-dimensional array optimization method)

01 backpack problem

There are N items and a backpack with a capacity of V. Each item can only be used once.

The volume of the i-th item is vi and the value is wi.

Find out which items to load into the backpack so that the total volume of these items does not exceed the backpack capacity and the total value is the largest.
Output the maximum value.

Input format The
two integers in the first line, N and V, are separated by spaces, indicating the quantity of items and the volume of the backpack respectively.

Next, there are N rows, each with two integers vi and wi, separated by a space, which represent the volume and value of the ith item.

Output format
Output an integer that represents the maximum value.

Data range
0<N,V≤1000
0<vi,wi≤1000
Input example
4 5
1 2
2 4
3 4
4 5
Output example:
8

#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
int main()
{
    
    
    int n,v,a[1010],b[1010],i,j,k,s,d[1010];
    scanf("%d%d",&n,&v);
    for(i=1;i<=n;i++)
    scanf("%d%d",&a[i],&b[i]);
	for(i=0;i<=v;i++)//初始化数组
	d[i]=0;
	for(i=1;i<=n;i++)
	for(j=v;j>=a[i];j--)
	{
    
    
		d[j]=max(d[j],d[j-a[i]]+b[i]);//不选当前物品和选当前物品的最大值
	}
	printf("%d\n",d[v]);
}

Insert picture description here
Sample data
When i=1, the first i can be installed from the maximum j=5 to j=1, and all the value is 2.
When i=2, j=5 starts, because when you want the second This item will make room for him, so d[j]=max(d[j],d[ja[i]]+b[i]); this time d[5]=d[5-a[ 2]]+b[2]=6, when j=2, we find that choosing the second item is more valuable than the first item, so we will choose the second item, when j=1, choose the first item Kind.
When i=3, j=5 starts. At this time, if you want the third item to make room for the third item, it is also 5-3=2. This 2 means that you only have 2 space to choose the first two items. For items, we found that when the space is 2, the maximum value is 4, so at this time d[5]=8, the same can be calculated for 4, 3, 2, 1.
It has been calculated so that i is selected or not.
When we want this item, we need to make room for this item, that is, ja[i] plus its value b[i] and it does not choose this The d[j] of each item is compared to select the maximum value.

The two-dimensional array method will be updated later, and the one-dimensional array is more convenient! ! ! , Two-dimensional array is easy to explode! ! ! So a one-dimensional array is best, but a two-dimensional array is easier to understand.

Guess you like

Origin blog.csdn.net/m0_46381590/article/details/111479320