Submission #853659

#TimeUsernameProblemLanguageResultExecution timeMemory
853659Dawae12321Knapsack (NOI18_knapsack)C++14
29 / 100
4 ms1884 KiB
#include <bits/stdc++.h>
using namespace std;

struct item{
    int value, weight, quantity;
};



int main(){
    int S, N;
    cin >> S >> N; //S is maximum weight, N is total # of items
    item items[N];
    for(int i = 0; i < N; i++){
        cin >> items[i].value >> items[i].weight >> items[i].quantity;
    }

    pair<int,int> maxval[N][S+1]; //first is current value, second is current weight

    for(auto &element:maxval){
        for(auto &e : element){
            e = {0,0};
        }
    }

    for(int j = 0; j <= S; j++){
        maxval[0][j].first = min(items[0].quantity, int(j/items[0].weight)) * items[0].value;
        maxval[0][j].second = items[0].weight * min(items[0].quantity, int(j/items[0].weight));
    }

    for(int i = 1; i < N; i++){
        for(int j = 0; j <= S; j++){
            int add_new = min(items[i].quantity, (j-maxval[i-1][j].second)/items[i].weight); //with each you can either
            int reform = min(items[i].quantity, j/items[i].weight); //add to fill up or restart using that as the best
            int value1 = maxval[i-1][j].first + add_new*items[i].value;
            int value2 = reform * items[i].value + maxval[i-1][j-reform*items[i].weight].first;
            if(value1 > value2){
                maxval[i][j].first = value1;
                maxval[i][j].second = maxval[i-1][j].second + add_new*items[i].weight;
            }
            else if(value1 < value2){
                maxval[i][j].first = value2;
                maxval[i][j].second = items[i].weight * reform + maxval[i-1][j-reform*items[i].weight].second;
            }
            else{
                maxval[i][j].first = value1;
                maxval[i][j].second = min(maxval[i-1][j].second + add_new*items[i].weight, items[i].weight * reform + maxval[i-1][j-reform*items[i].weight].second);
            }
        }
    }

    cout << maxval[N-1][S].first;

    
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...