Submission #543158

#TimeUsernameProblemLanguageResultExecution timeMemory
543158shubham20_03Knapsack (NOI18_knapsack)C++17
100 / 100
123 ms19456 KiB
#include <bits/stdc++.h>
using namespace std;
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);
#define deb(x) cout<<#x<<'='<<x<<'\n';
#define deb2(x,y) cout<<#x<<'='<<x<<", "<<#y<<'='<<y<<'\n';
#define all(x) (x).begin(), (x).end()
#define pii pair<int, int>
#define pb push_back
#define f first
#define s second
#define sz(x) (int)(x).size()
const long double PI = acos(-1);
const int mod = 1e9 + 7;

signed main() {
    fastio

    int S, N; cin >> S >> N;
    map<int, vector<pii>> bywt;
    for (int i = 0; i < N; i++) {
        int v, w, k; cin >> v >> w >> k;
        bywt[w].pb({v, k});
    }

    int dp[sz(bywt) + 1][S + 1];
    memset(dp, -1, sizeof(dp));

    dp[0][0] = 0;
    int at = 1;
    for (auto& pp : bywt) {
        int w = pp.f;
        vector<pii>& itms = pp.s;
        sort(all(itms));
        reverse(all(itms));

        for (int j = 0; j <= S; j++) {
            dp[at][j] = dp[at - 1][j];
          // update from prev wt also
            if (j > 0) dp[at][j] = max(dp[at][j], dp[at][j - 1]);

            int copies = 0;
            int type_at = 0;
            int cur_val = 0;
            int cur_used = 0;

            while ((copies + 1)*w <= j and type_at < sz(itms)) {
                copies++;
                cur_val += itms[type_at].f;

                if (dp[at - 1][j - w * copies] != -1)
                    dp[at][j] = max(dp[at][j], dp[at - 1][j - w * copies] + cur_val);

                cur_used++;
                if (cur_used == itms[type_at].s) {
                    cur_used = 0;
                    type_at++;
                }
            }
        }

        at++;
    }

    int ans = dp[at - 1][S];
    cout << ans << '\n';

    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...