# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
500798 | pancankes | Knapsack (NOI18_knapsack) | C++17 | 0 ms | 0 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 <set>
#include <map>
using namespace std;
#define ll long long
const int MAXN=1e5+2;
const int MOD=1e9+7;
int main()
{
ll s,n;
cin >> s >> n;
// since s<=2000, and n<=1000000
// there will inevitably be repeated weights, so we can group them together
map<int, vector<pair<int,int> > >weights;
for (int i=0; i<n; i++)
{
int p,w,n;
cin >> p >> w >> n;
weights[w].push_back({p,n});
}
vector<vector<int>> dp(weights.size()+1,vector<int>(s+1,0));
dp[0][0]=0;
int at=1;
for (auto& [w, items] : weights)
{
sort(items.rbegin(),items.rend());
for (int i=0; i<=s; i++)
{
dp[at][i]=dp[at-1][i];
int copies=0, j=0, cur=0;
ll profit=0;
// while there are items and while it is within the usable weight
// we can use copies since all groups of items are of the same weight
while ((copies+1) * w <= i && j<items.size())
{
copies++;
profit+=items[j].first;
dp[at][i]=max((ll)dp[at][i],dp[at-1][i-copies*w]+profit);
cur++;
if (cur==items[j].second)
{
cur=0;
j++;
}
}
}
at++;
}
// max_element gives a ptr to the value of the max element in a vector
cout << *max_element(dp.back().begin(),dp.back().end()) << endl;
}