Submission #1184006

#TimeUsernameProblemLanguageResultExecution timeMemory
1184006ayushtiwari110Knapsack (NOI18_knapsack)C++20
37 / 100
1 ms328 KiB
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { // Read the maximum capacity S and number of item types N int S, N; cin >> S >> N; // Create a DP table where dp[w] represents the maximum value achievable with weight capacity w vector<long long> dp(S + 1, 0); // For each item type for (int i = 0; i < N; i++) { int value, weight, count; cin >> value >> weight >> count; // Skip if the item is too heavy for the basket if (weight > S) continue; // Use the binary optimization technique // Break down count K into powers of 2: 1, 2, 4, 8, ... and a remainder // This reduces processing from O(K) to O(log K) // Create "binary" bundles of items vector<pair<long long, int>> bundles; for (int c = 1; count > 0; c *= 2) { int bundle_size = min(c, count); bundles.push_back({(long long)value * bundle_size, weight * bundle_size}); count -= bundle_size; } // Apply 0/1 knapsack for each bundle for (auto& bundle : bundles) { long long bundle_value = bundle.first; int bundle_weight = bundle.second; // Skip if the bundle is too heavy if (bundle_weight > S) continue; // Update the DP table from right to left to avoid counting the same bundle multiple times for (int w = S; w >= bundle_weight; w--) { dp[w] = max(dp[w], dp[w - bundle_weight] + bundle_value); } } } // Output the maximum value cout << dp[S] << endl; 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...