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<tuple<int, int, int>>> by_weight; //{weight, {value, amount}}, 根据weight从小到大排序
vector<vector<int>> items(type_num, vector<int>(3));
for (int i = 0; i < type_num; i++) {
int weight, num, val;
cin >> val >> weight >> num;
if (weight>limit) continue;
items[i][0] = weight; items[i][1] = num; items[i][2] = val;
}
vector<int> dp(limit+1, -1);
dp[0]= 0;
for (int t=0; t<items.size(); t++) {
int weight, num, val;
weight = items[t][0]; num = items[t][1]; val = items[t][2];
for (int j=0; j < num; j++) {
for (int i=limit - weight; i>=0; i--) {
if (dp[i]>=0) dp[i+weight] = max(dp[i+weight], dp[i] + val);
}
}
}
cout << *max_element(dp.begin(), dp.end()) << endl;
}
// /*
// * best[i][j] contains the most value we can
// * get using j weight and the first i weight types
// */
// vector<vector<ll>> best(by_weight.size() + 1, vector<ll>(limit + 1, INT32_MIN));
// best[0][0] = 0;
// int at = 1;
// for (auto& [w, items] : by_weight) {
// // sort items in reverse order by value
// sort(items.begin(), items.end(), std::greater<pair<int, int>>());
// for (int i = 0; i <= limit; i++) {
// best[at][i] = best[at - 1][i];
// int copies = 0;
// int type_at = 0;
// int curr_used = 0;
// ll profit = 0;
// // go through as many items until we run out of items or usable weight
// while ((copies + 1) * w <= i && type_at < items.size()) {
// copies++;
// profit += items[type_at].first;
// if (best[at - 1][i - copies * w] != INT32_MIN) {
// best[at][i] = max( best[at][i], best[at - 1][i - copies * w] + profit);
// }
// curr_used++;
// if (curr_used == items[type_at].second) {
// curr_used = 0;
// type_at++;
// }
// }
// }
// at++;
// }
// cout << *std::max_element(best.back().begin(), best.back().end()) << endl;
// }
Compilation message (stderr)
knapsack.cpp: In function 'int main()':
knapsack.cpp:27:20: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::vector<int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
27 | for (int t=0; t<items.size(); t++) {
| ~^~~~~~~~~~~~~
# | 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... |