Submission #961782

#TimeUsernameProblemLanguageResultExecution timeMemory
961782RohakKnapsack (NOI18_knapsack)C++14
100 / 100
52 ms3676 KiB
#include <bits/stdc++.h>

using namespace std;
using i64 = long long;

#define UNSYNC ios::sync_with_stdio(false); cin.tie(nullptr);
#define all(x) x.begin(), x.end()
#define rep(i, ini, x) for (int i = ini; i < x; ++i)
#define per(i, fin, x) for (int i = fin; i >= x; --i)

int main() {
    UNSYNC
    int S, N; cin >> S >> N;
    vector<vector<pair<int, int>>> data(S + 1);  // To store items by weight

    // Read each item's value V, weight W, and quantity K
    rep(i, 0, N) {
        int V, W, K; cin >> V >> W >> K;
        data[W].push_back({V, K});
    }

    // Dynamic programming array to store maximum values up to weight S
    vector<int> dp(S + 1, 0);

    // Iterate over each possible weight
    rep(i, 0, S + 1) {
        if (!data[i].empty()) {
            // Sort items at weight i by their values in descending order
            sort(all(data[i]), [](const pair<int, int>& a, const pair<int, int>& b) {
                return a.first > b.first;
            });

            // Try to use each item at this weight
            int id = 0;  // Index of the current item in data[i]
            for (int j = 0; j * i <= S; ++j) {
                if (id >= data[i].size()) break;  // No more items to consider at this weight
                // Update dp values for using current item up to its quantity
                per(k, S, i) {
                    dp[k] = max(dp[k], dp[k - i] + data[i][id].first);
                }
                --data[i][id].second;  // Use one unit of the current item
                if (data[i][id].second == 0) ++id;  // Move to next item if all units used
            }
        }
    }

    // Output the maximum value that can be put in a knapsack of capacity S
    cout << dp[S] << '\n';
    return 0;
}

Compilation message (stderr)

knapsack.cpp: In function 'int main()':
knapsack.cpp:36:24: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
   36 |                 if (id >= data[i].size()) break;  // No more items to consider at this weight
      |                     ~~~^~~~~~~~~~~~~~~~~
#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...