C++: A detailed introduction to the c++ knapsack problem

        The knapsack problem is a classic dynamic programming problem. The basic idea is to select some items to maximize their value given a given capacity. Here we introduce the specific method of implementing the knapsack problem in C++.

        First declare a two-dimensional array dp[i][j] to represent the maximum value that can be obtained by using the first i items to fill a backpack with capacity j. Among them, dp[0][j]=0 means that the maximum value that can be obtained by filling a backpack of any capacity with 0 items is 0, and dp[i][0]=0 means that without filling in any items , the backpack value is also 0.

        Then, we can solve it according to the state transition equation. The state transition equation can be expressed as:

        当j>=w[i]时,dp[i][j]=max(dp[i-1][j],dp[i-1][j-w[i]]+v[i]);

        当j<w[i]时,dp[i][j]=dp[i-1][j];

        Among them, w[i] represents the weight of the i-th item, and v[i] represents the value of the i-th item.

​#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1010;

int n, m;
int w[N], v[N];
int dp[N][N];

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i ++ ) cin >> w[i] >> v[i];

    for (int i = 1; i <= n; i ++ )
        for (int j = 1; j <= m; j ++ )
            if (j >= w[i]) dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w[i]] + v[i]);
            else dp[i][j] = dp[i - 1][j];

    cout << dp[n][m] << endl;

    return 0;
}

Guess you like

Origin blog.csdn.net/SYC20110120/article/details/132916423