Submission #1291872

#TimeUsernameProblemLanguageResultExecution timeMemory
1291872atharva0300Knapsack (NOI18_knapsack)C++17
73 / 100
1095 ms580 KiB
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int S, N;
    cin >> S >> N;
    
    vector<long long> dp(S + 1, 0);
    
    for (int i = 0; i < N; i++) {
        long long V;
        int W, K;
        cin >> V >> W >> K;
        
        // Skip if single item is too heavy
        if (W > S) continue;
        
        // Limit K to maximum useful copies
        K = min(K, S / W);
        
        // Binary representation optimization
        for (int cnt = 1; K > 0; cnt *= 2) {
            int take = min(cnt, K);
            int weight = W * take;
            long long value = V * take;
            
            // Process this batch in 0/1 knapsack fashion
            for (int w = S; w >= weight; w--) {
                dp[w] = max(dp[w], dp[w - weight] + value);
            }
            
            K -= take;
        }
    }
    
    cout << dp[S] << '\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...