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;
typedef long long ll;
int main()
{
int s,n;
cin>>s>>n;
vector<int> w(n);
vector<ll> v(n),k(n);
//w_i <= 2000
//n <= 1e5
map<int,vector<pair<int,int> > > mp;
for(int i=0; i<n; i++)
{
cin>>v[i]>>w[i]>>k[i];
if(w[i]<=s && k[i]>0) mp[w[i]].push_back(make_pair(v[i],k[i]));
}
vector<vector<ll> > dp(mp.size()+1, vector<ll>(s+1, INT_MIN));
dp[0][0]=0;
int at=1;
/*
* dp[i][w]= answer after processing first i items, weight=w
* dp[i][w]=max(dp[i-1][w], dp[i-1][w-w[i]]+v[i])
* Sort each copy of an item by value, only take the greatest S/w_i copies
*/
for(auto &[w,items] : mp)
{
sort(items.begin(), items.end(), greater<pair<int,int>>());
for(int i=0; i<=s; i++)
{
dp[at][i]=dp[at-1][i];
int copies=0;
int type_at=0;
int curr_used=0;
ll profit=0;
while((copies+1)*w <= i && type_at < items.size())
{
copies++;
profit+=items[type_at].first;
if(dp[at-1][i-copies*w]!=INT_MIN)
{
dp[at][i]=max(dp[at][i], dp[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(dp.back().begin(), dp.back().end()) << endl;
return 0;
}
Compilation message (stderr)
knapsack.cpp: In function 'int main()':
knapsack.cpp:39:40: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
39 | while((copies+1)*w <= i && type_at < 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... |