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 <algorithm>
#include <vector>
#include <map>
using namespace std;
int limit, n;
const int inf = 2000000000;
map<int, vector<pair<int, int>>> by_weight;
void fastIO()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}
int main()
{
fastIO();
cin >> limit >> n;
for (int i = 1; i <= n; ++i)
{
int w, val, copies;
cin >> val >> w >> copies;
if (w <= limit)
{
by_weight[w].push_back(make_pair(val, copies));
}
}
vector<vector<long long>> dp(by_weight.size() + 1, vector<long long>(limit + 1, -inf));
dp[0][0] = 0;
int pos = 1;
for (auto& [w, items] : by_weight)
{
sort(items.begin(), items.end(), greater<pair<int, int>>());
for (int i = 0; i <= limit; ++i)
{
dp[pos][i] = dp[pos - 1][i];
int copies = 0;
int type_pos = 0;
int used = 0;
long long profit = 0;
while ((copies + 1) * w <= i && type_pos < items.size())
{
++copies;
profit += items[type_pos].first;
if (dp[pos - 1][i - copies * w] != -inf)
{
dp[pos][i] = max(dp[pos][i], profit + dp[pos - 1][i - copies * w]);
}
++used;
if (used == items[type_pos].second)
{
used = 0;
++type_pos;
}
}
}
++pos;
}
long long ans = -inf;
for (int i = 0; i <= limit; ++i)
{
ans = max(ans, dp[by_weight.size()][i]);
}
cout << ans << endl;
return 0;
}
Compilation message (stderr)
knapsack.cpp: In function 'int main()':
knapsack.cpp:59:54: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
59 | while ((copies + 1) * w <= i && type_pos < items.size())
| ~~~~~~~~~^~~~~~~~~~~~~~
# | 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... |