C++01 knapsack problem (dynamic programming)

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 pack 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 number 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, indicating
the volume and value of the i-th 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

AC code:

#include<stdio.h>
#include<algorithm>

using namespace std;

int n,V;
int w[1010];//价值
int v[1010];//体积
int f[1010][1010];//从前i个物品中选出总重不超过j的最大价值

int main()
{
    
    
    scanf("%d%d",&n,&V);
    for(int i=1;i<=n;++i)
        scanf("%d%d",&v[i],&w[i]);
    for(int i=1;i<=n;++i)
    {
    
    
        for(int j=0;j<=V;++j)
        {
    
    
            //必然存在的情况,从前i-1个物品中选出总重不超过j的最大价值
            f[i][j]=f[i-1][j];
            //不一定存在的情况,
            //从前i个物品中选择总重不超过j的最大价值,且必须选i
            //因为j不一定不小于i的体积
            if(j>=v[i]) f[i][j]=max(f[i][j],f[i-1][j-v[i]]+w[i]);
            //求解这个情况,等价于先从前i-1件物品中选择总重不超过j-v[i]
            //的最大价值,再加上i的价值
        }
    }
    printf("%d",f[n][V]);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108824551