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>
#include<iostream>
#include<stdlib.h>
#include<cmath>
#include <algorithm>
#include<numeric>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pair<int, int> > vpii;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
typedef vector<ll> vll;
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define trav(a,x) for (auto& a: x)
#define fr(i, a, b, s) for (int i=(a); (s)>0?i<(b):i>=(b); i+=(s))
#define mp make_pair
#define pb push_back
#define sz(x) int(x.size())
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define in insert
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define out(x) cout<<x<<'\n'
int dx[4] = { -1, 0, 1, 0 };
int dy[4] = { 0, 1, 0, -1 };
int dx8[8]={0,0,-1,1,-1,1,-1,1};
int dy8[8]={-1,1,0,0,-1,1,1,-1};
void solve(){
int limit,type_num; cin >> limit >> type_num;
unordered_map<int, vector<pair<int, int>>> by_weight;
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});
}
}
/*
* best[i][j] contains the most value we can
* get using j weight and the first i weight types
*/
vector<vector<long long>> best(by_weight.size() + 1, vector<long long>(limit + 1, INT32_MIN));
best[0][0] = 0;
int at = 1;
for (auto &[w, items] : by_weight) {
sort(all(items),greater<pii>());
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;
long long profit = 0;
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;
}
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int tt=1;// cin>>tt;
while(tt--){
solve();
}
}
Compilation message (stderr)
knapsack.cpp: In function 'void solve()':
knapsack.cpp:58:44: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
58 | 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... |