To solve this problem, we need to determine the maximum total price of gifts Santa can pack for each possible number of children ( k ) from 1 to ( M ). The constraints are that each gift type can be either included entirely for all children or excluded, and the total size of the gifts must not exceed ( C ).
Approach
-
Dynamic Programming (Knapsack Problem):
- We first solve a standard 0-1 knapsack problem where the capacity is ( C ). For each gift, we decide whether to include it or not to maximize the total price.
-
Precompute Maximum Prices:
- Using dynamic programming, we compute an array
dp where dp[c] represents the maximum price achievable with a total size exactly c.
-
Calculate for Each ( k ):
- For each ( k ) from 1 to ( M ), the maximum size per child is ( \left\lfloor \frac{C}{k} \right\rfloor ). The maximum price for ( k ) children is then given by
dp[lfloor(C/k)] * k.
Solution Code
#include <bits/stdc++.h>
using namespace std;
int main() {
int C, N, M;
cin >> C >> N >> M;
vector<pair<int, int>> gifts;
for (int i = 0; i < N; ++i) {
int s, p;
cin >> s >> p;
if (s <= C) {
gifts.push_back({s, p});
}
}
vector<int> dp(C + 1, 0);
for (const auto& item : gifts) {
int s = item.first;
int p = item.second;
for (int c = C; c >= s; --c) {
if (dp[c - s] + p > dp[c]) {
dp[c] = dp[c - s] + p;
}
}
}
for (int k = 1; k <= M; ++k) {
int x = C / k;
cout << dp[x] * k << endl;
}
return 0;
}
Explanation
-
Reading Input and Filtering Gifts:
- We read the number of children, gifts, and maximum children, then filter out gifts that exceed the bag's capacity ( C ).
-
Dynamic Programming Setup:
- We initialize a dynamic programming array
dp where dp[c] will store the maximum price achievable with a size exactly c.
-
Knapsack Problem Solution:
- For each gift, we update the
dp array from the back to ensure each gift is considered exactly once. This helps in avoiding using the same gift multiple times.
-
Computing Results:
- For each ( k ) from 1 to ( M ), compute the maximum possible size per child ( \left\lfloor \frac{C}{k} \right\rfloor ) and use the precomputed
dp array to find the maximum price. Multiply this price by ( k ) to get the total price for ( k ) children.
This approach efficiently leverages dynamic programming to solve the knapsack problem once, allowing us to quickly answer each query in constant time after the initial computation. The overall complexity is ( O(N \cdot C) ), which is feasible given the problem constraints.