[ACWing] 4. Multiple knapsack problem I

Subject address:

https://www.acwing.com/problem/content/4/

Has NNN items and one capacity areVVV 's backpack. The firstiii items have at mostsi s_isiPieces, the volume of each piece is vi v_ivi, The value is wi w_iwi. Solve which items are loaded into the backpack, so that the total volume of the items does not exceed the capacity of the backpack, and the total value is the largest. Output the maximum value.

Data range:
0 <N, V ≤ 100 0< N, V\le 1000<N,V100
0 < v i , w i , s i ≤ 100 0<v_i,w_i,s_i\le 100 0<vi,wi,si100

The idea is dynamic programming. Let f [i] [j] f[i][j]f [ i ] [ j ] is if only the frontiii items, and the total weight does not exceedjjThe maximum value that can be achieved in the case of j . Then all schemes can follow theiiHow many i items to take to classify. Obviously you can take at least0 00 , max can bemin ⁡ {si, j / vi} \min\{s_i,j/v_i\}min { si,j/vi}个,所以有 f [ i ] [ j ] = max ⁡ k = 0 , 1 , . . . , min ⁡ { s i , j / v i } { f [ i − 1 ] [ j − k v i ] + k w i } f[i][j]=\max_{k=0,1,...,\min\{s_i,j/v_i\}}\{f[i-1][j-kv_i]+kw_i\} f[i][j]=k = 0 , 1 , . . . , min { si,j/vi}max{ f[i1][jkvi]+kwi} Finally returnf [N] [V] f[N][V]f [ N ] [ V ] is fine (there is a binary optimization for this question, refer tohttps://blog.csdn.net/qq_46105170/article/details/113840962). code show as below:

#include <iostream>
using namespace std;

const int N = 110;

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

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

    for (int i = 1; i <= n; i++) 
        for (int j = 0; j <= m; j++)
        	// 枚举第i件物品取多少个 
            for (int k = 0; k <= s[i] && k * v[i] <= j; k++)
                f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i]);
    

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

    return 0;
}

Time and space complexity O (NV 2) O (NV^2)O ( N V2 ), spaceO (NV) O(NV)O ( N V )

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/113840951