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 <bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
ios_base::sync_with_stdio(false); cin.tie(NULL);
//freopen("Knapsack.in", "r", stdin);
// freopen("Knapsack.out", "w", stdout);
int limit, type_num;
cin >> limit >> type_num;
map<int, vector<pair<int, int>>> by_weight;
//vector<vector<int>> items(type_num, vector<int>(3));
for (int t = 0; t < type_num; t++) {
int value, weight, amt;
cin >> value >> weight >> amt;
if (weight <= limit && amt > 0) {
by_weight[weight].push_back({value, amt});
}
}
vector<int> dp(limit+1, -1);
dp[0]= 0;
for (auto& [w, items] : by_weight) {
// sort items in reverse order by value
sort(items.begin(), items.end(), greater<pair<int, int>>());
for(int i = limit; i>=0; i--) {
if(dp[i]<0) continue;
int curr = i;
bool withinLimit = true;
for (auto& item:items){
for (int k=1; k<=item.second; k++) {
if (curr+k*w>limit) {
withinLimit = false;
break;
}
dp[curr+k*w] = max(dp[curr+k*w], dp[curr] + k*item.first);
}
if(!withinLimit) break;
curr += w*item.second;
}
}
}
cout << *max_element(dp.begin(), dp.end()) << endl;
}
Compilation message (stderr)
knapsack.cpp: In function 'int main()':
knapsack.cpp:28:13: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
28 | for (auto& [w, items] : by_weight) {
| ^
# | 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... |