To solve this problem, we need to determine the maximum total price of gifts Santa can pack for each possible number of children (from 1 to M) while ensuring the total size does not exceed the bag's capacity C. Each child must receive the exact same set of gifts, meaning each gift must be included for all children or none.
Approach
-
Problem Analysis:
- We need to maximize the total price for each possible number of children k (from 1 to M).
- Each gift can either be included for all k children or excluded, so the problem reduces to selecting subsets of gifts such that the total size multiplied by k does not exceed C.
-
Key Insight:
- For a given k, the maximum total size of the gifts must be ≤ C/k.
- We can use a dynamic programming (DP) approach to solve the knapsack problem for subsets of gifts and then adjust for each k.
-
Dynamic Programming Setup:
- Use a DP array
dp[s] where dp[s] represents the maximum price for a subset of gifts with an exact total size s.
- Compute another array
max_dp where max_dp[s] is the maximum price for any subset of gifts with size up to s.
-
Optimization:
- The
max_dp array helps quickly determine the best possible price for any required size threshold derived from k's value.
Solution Code
import sys
def main():
C, N, M = map(int, sys.stdin.readline().split())
gifts = []
for _ in range(N):
s, p = map(int, sys.stdin.readline().split())
if s <= C:
gifts.append((s, p))
max_size = C
# Initialize dp array for exact sizes
dp = [-float('inf')] * (max_size + 1)
dp[0] = 0
for s_i, p_i in gifts:
for s in range(max_size, s_i - 1, -1):
candidate = dp[s - s_i] + p_i
if candidate > dp[s]:
dp[s] = candidate
# Compute max_dp where max_dp[s] is the max price up to size s
max_dp = [0] * (max_size + 1)
current_max = dp[0]
for s in range(max_size + 1):
if s == 0:
max_dp[s] = current_max
else:
current_max = max(current_max, dp[s])
max_dp[s] = current_max
# Calculate the answers for each k from 1 to M
for k in range(1, M + 1):
a = C // k
ans = max_dp[a] * k
print(ans)
if __name__ == "__main__":
main()
Explanation
- Reading Input: The gifts are read and filtered to exclude those whose size exceeds the bag's capacity C.
- Dynamic Programming Array Initialization:
dp is initialized to track the maximum price for each possible subset size.
- Processing Gifts: For each gift, the DP array is updated to reflect the best subset prices considering the current gift.
- Max DP Array: This array efficiently tracks the best price up to every possible size, allowing quick lookups for each k.
- Generating Results: For each k from 1 to M, the maximum allowable subset size is calculated, and the corresponding maximum price is retrieved from
max_dp.
This approach efficiently computes the solution using dynamic programming and pre-processing to handle all queries in O(N*C + M) time, which is feasible given the problem constraints.