To solve this problem, we need to determine the maximum total price of gifts that Santa can pack for a family with ( k ) children for each ( 1 \leq k \leq M ). The solution involves a combination of dynamic programming (0-1 knapsack problem) and preprocessing to efficiently compute the results for all required values of ( k ).
Approach
-
Dynamic Programming (Knapsack):
- We first use a 0-1 knapsack approach to compute the maximum price achievable for each possible total size of gifts. The array
dp will store the maximum price obtainable for each possible weight (total size of gifts).
-
Precompute Maximum Prices Up to Each Weight:
- Create an array
pre_max where each entry at index i holds the maximum price achievable with a total weight up to i. This is derived directly from the dp array.
-
Compute Results for Each ( k ):
- For each ( k ) from 1 to ( M ), compute the maximum weight capacity ( T = \lfloor \frac{C}{k} \rfloor ). Use the precomputed
pre_max array to get the maximum price for this capacity and then scale it by ( k ).
Solution Code
import numpy as np
def main():
import sys
C, N, M = map(int, sys.stdin.readline().split())
gifts = []
for _ in range(N):
s, p = map(int, sys.stdin.readline().split())
gifts.append((s, p))
INF = -float('inf')
dp = np.full((C + 1,), INF, dtype=np.float64)
dp[0] = 0.0 # Base case: 0 weight, 0 price
for s, p in gifts:
if s > C:
continue
max_possible = C - s
prev_dp_part = dp[0: max_possible + 1]
delta = prev_dp_part + p
dp[s: C+1] = np.maximum(dp[s: C+1], delta)
# Precompute pre_max array
pre_max = np.copy(dp)
for i in range(1, C + 1):
pre_max[i] = max(pre_max[i - 1], dp[i])
# Compute answers for each k from 1 to M
ans = [0] * (M + 1)
for k in range(1, M + 1):
T = C // k
if T < 0:
curr_max_p = 0
else:
curr_max_p = pre_max[T]
ans_k = curr_max_p * k
ans[k] = int(ans_k) # Convert back to integer
for k in range(1, M + 1):
print(ans[k])
if __name__ == "__main__":
main()
Explanation
-
Dynamic Programming Initialization:
- The
dp array is initialized to store negative infinity (indicating impossible states) except for the first element (weight 0, price 0).
-
Updating DP Array:
- For each gift, we calculate the possible weights up to the maximum weight caused by excluding this gift. The delta array represents the potential new prices if the gift is included.
-
Precomputing Maximum Prices:
- The
pre_max array is built to efficiently query the maximum price achievable for any given weight capacity.
-
Querying Results:
- For each ( k ), compute the maximum weight capacity
T = C // k, then retrieve the maximum price for this capacity from pre_max and scale it by ( k ) to get the total price.
This approach efficiently handles the constraints using dynamic programming and preprocessing, ensuring we can answer queries for all ( k ) up to ( M ) in linear time relative to ( M ). The use of NumPy helps expedite the array operations, making this solution feasible within the problem’s constraints.