AcWing 1019. Celebration [Multiple Knapsack Problem + DP] Solution

Hello, everyone, welcome to visit Lin Shenshi's blog of No See Deer, the algorithm Xiaobai, records the daily life of learning, and is committed to easy-to-understand problem solving. Meeting is the signing. If there are shortcomings, please give us more advice.

table of Contents

AcWing 1019. Celebration

In order to celebrate the class's first place in the school sports meeting, the head teacher decided to hold a celebration party and allocated funds to purchase prizes to reward the athletes.

It is hoped that the funding amount can purchase the most valuable prizes, which can supplement their energy and physical strength.

Input format
Two numbers n, m in the first line, where n represents the number of prizes you want to buy, and m represents the amount of grant.

In the next n rows, 3 numbers in each row, v, w, and s, respectively represent the price, value (price and value are different concepts) and the maximum quantity that can be purchased (buy 0 to s). can).

Output format
One line: a number, indicating the maximum value that can be obtained for this purchase (note! not the price).

Data range
n≤500,m≤6000,
v≤100,w≤1000,s≤10
Input example:
5 1000
80 20 4
40 50 9
30 50 7
40 30 6
20 20 1
Output example:
1040

Ideas

  • Multiple backpack problem: each item can be used s times
  • The total volume of the backpack V: Appropriation amount m
  • Number of items N: Number of prizes n
  • The value of each item w: the value of the prize
  • The volume of each item v: the price of the prize.
    Status f[i][j]:: Only select from the first i items, and the total volume does not exceed the maximum value of all selection sets of j.
    State calculation: f[i][j]=max(f[i][j],f[i-1][j-k*v]+k*w)
    each item can be installed if it can be installed Choose 0 times, 1 time, 2 times,,,, k times.
    Because the data range is small, there is no need to perform binary or monotonic queue optimization. The
    time complexity O(nms) is about 3e7.
    Here, two dimensions are optimized to one dimension.

Code

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

Guess you like

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