AcWing 8. Two-dimensional cost knapsack problem [two-dimensional cost knapsack] solution

table of Contents


1. Title

There are N items and a backpack with a capacity of V. The maximum weight that the backpack can bear is M.

Each item can only be used once. The volume is vi, the weight is mi, and the value is wi.

Solve which items are loaded into the backpack so that the total volume of the items does not exceed the capacity of the backpack, the total weight does not exceed the maximum weight that the backpack can bear, and the total value is the largest.
Output the maximum value.

Input format
Two integers in the first line, N, V, M, separated by spaces, respectively indicate the number of items, the volume of the backpack and the maximum weight that the backpack can bear.

Next, there are N rows, each with three integers vi, mi, wi, separated by spaces, representing the volume, weight, and value of the ith item.

Output format
Output an integer that represents the maximum value.

Data range
0<N≤1000
0<V,M≤100
0<vi,mi≤100
0<wi≤1000
Input example

4 5 6
1 2 3
2 4 4
3 4 5
4 5 6

Sample output:

8

2. Thinking


The knapsack problem of the two-dimensional cost
State means:
f[i][j][k]select only from the first i items, the total volume does not exceed j, and the total value does not exceed the maximum value of all selection methods.
State calculation:
f[i][j][k]=max(f[i-1][j][k],f[i-1][j-v1][k-v2]+w)
State transition equation calculation:

for(int j=V;j>=v;j--)
  for(int k=M;k>=m;k--)
    f[j][k]=max(f[j][k],f[j-v][k-m]+w);

Icon
Insert picture description here

3.AC code

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=110;
int f[N][N];
int main()
{
    
    
    int n,V,M;
    cin>>n>>V>>M;
    for(int i=0;i<n;i++)
    {
    
    
        int v,m,w;
        cin>>v>>m>>w;
        for(int j=V;j>=v;j--)
         for(int k=M;k>=m;k--)
          f[j][k]=max(f[j][k],f[j-v][k-m]+w);
    }
    cout<<f[V][M]<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45629285/article/details/109210963