# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1090167 | ULTRABIG7 | Knapsack (NOI18_knapsack) | C++14 | 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<bits/stdc++.h>
using namespace std;
using ll = long long;
using db = long double;
#define ff first
#define ss second
#define pb push_back
#define all(x) begin(x),end(x)
#define FOR(i,a,b) for(int i = (a);i<(b);i++)
#define F0R(i,a) FOR(i,0,a)
#define rep(a) F0R(_,a)
#define each(a,x) for(auto& a:x)
#define sz(x) (int)size(x)
#define vi vector<int>
const int MOD = 1e9+7;
const db PI = acos((db)-1);
int main(){
cin.tie(0)->sync_with_stdio(0);
int S, N; cin>>S>>N;
vector<vector<pair<int,int>>> por_peso(S+1);
FOR(i,1,N+1){
int v,w,k; cin>>v>>w>>k;
por_peso[w].pb({v,k});
}
vector<pair<int,int>> considerar;
FOR(i,1,S+1){
sort(por_peso[i].begin(),por_peso[i].end(),[&](pair<int,int>& a, pair<int,int>& b){return (a.ff == b.ff? a.ss<b.ss:(a.ff<b.ff));});
int cnt = 0;
for(int j = 0;j<sz(por_peso[i]) && cnt<S/i;j++){
int k = por_peso[i][j].ss;
int v = por_peso[i][j].ff;
while(k-- && cnt<S/i){
considerar.pb({i,v});
cnt++;
}
}
}
int nn = (int)considerar.size();
vector<vector<int>> dp(nn+1,vector<int>(S+1,-1));
dp[0][0] = 0;
for(int i = 0;i<nn;i++){
for(int peso = 0;peso<=S;peso++){
// Faz nada:
dp[i+1][peso] = max(dp[i][peso],dp[i+1][peso]);
// Bota:
int nw = peso + considerar[i].ff;
if(nw>S || dp[i][peso] == -1) continue;
dp[i+1][nw] = max(dp[i+1][nw],dp[i][peso] + considerar[i].ss);
}
}
int ans = 0;
FOR(i,0,nn+1){
FOR(j,0,S+1){
ans = max(ans,dp[i][j]);
}
}
cout<<ans<<"\n";
return 0;
}