algorithm acwing 01 backpack

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

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

Find out which items can be packed into the backpack so that the total volume of these items does not exceed the capacity of the backpack and the total value is maximum.
Output the maximum value.

Input format:
The first line contains two integers, N and V, separated by spaces, representing the number of items and the capacity of the backpack respectively.

Next there are N lines, each line contains two integers vi and wi, separated by spaces, representing the volume and value of the i-th item respectively.

Output format
Output an integer representing the maximum value.

data range

0<N,V≤1000 0<vi,wi≤1000

Input sample

4 5 1 2 2 4 3 4 4 5

Output sample:

8

answer

#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 1010;

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

int main() {
    
    
    //题目输入  物品数量n, 背包容积m
    cin >> n >> m;
    for (int i = 1; i <= n; i++)cin >> v[i] >> w[i];

    for (int i = 1; i <= n; i++) 
        for (int j = 1; j <= m; j++) {
    
    
            //f[i][j] = f[i - 1][j];
            if (v[i] <= j)
                f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i]);
        }

    int res = 0;
    for (int j = 0; j <= m; j++)res = max(res, f[n][j]);

    cout << res;
    return 0;
}

Code optimization

#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 1010;

int n, m;
int f[N];
int v[N], w[N];
//二维表示前i个物品,所占总体积为j 时的最大价值
//一维表示f[i]表示体积是i的情况下最大价值是多少
int main() {
    
    
    //题目输入  物品数量n, 背包容积m
    cin >> n >> m;
    for (int i = 1; i <= n; i++)cin >> v[i] >> w[i];

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

    cout << f[m];
    return 0;
}

This is my first time contacting the 01 backpack issue, so I am still a little unfamiliar with it. Please correct me if there is anything wrong.

Guess you like

Origin blog.csdn.net/smile66688/article/details/116085284