# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
643400 | VISHNUCODE | Knapsack (NOI18_knapsack) | C++14 | 155 ms | 35248 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <climits>
using namespace std;
int main(){
int limit; int N; cin >> limit >> N;
// group by weights
map<int,vector<pair<int,int> > > weight_groups; //value,amount
for(int i = 0;i < N;i++){
int value; int weight; int amt; cin >> value >> weight >> amt;
if(amt > 0 && limit >= weight){
weight_groups[weight].push_back(make_pair(value,amt));
}
}
vector<vector<long long > > best(weight_groups.size()+1,vector<long long> (limit+1,INT_MIN));
//best [i][j] = max value you can get choosing the first i weight groups and spending at most j money
best[0][0] = 0;
int i = 1;
for(auto&[w,items] : weight_groups){
//sort weight groups in reverse order cuz you want the best value if you have the same weight lol
sort(items.begin(),items.end(),greater<pair<int,int> >());
for(int j = 0;j <= limit;j++){
best[i][j] = best[i-1][j];
int kthcopy = 0;
int typecounter = 0;
int curr_used = 0;
long long profit = 0;
//keep picking till you run out of options or run out of weight
while((kthcopy + 1)* w <= j && typecounter < items.size()){
kthcopy++;
profit += items[typecounter].first;
if(best[i-1][j-(kthcopy*w)] != INT_MIN){
best[i][j] = max(best[i][j],best[i-1][j-(kthcopy*w)] + profit);
}
curr_used++;
if(curr_used == items[typecounter].second){
curr_used = 0;
typecounter++;
}
}
}
i++;
}
cout << *std::max_element(best.back().begin(), best.back().end()) << endl;
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |