华为OD机考 HJ_16 购物单
n, m = map(int, input().strip().split()) # Read the total budget (N) and the number of items (m)
data = []
# Step 1: Collect input data
for a in range(m):
values = list(map(int, input().strip().split())) # v: price, p: importance, q: type
data.append(values) # Append the item to data
# Initialize the DP array
dp = [0] * (n + 1) # dp[j] stores the maximum satisfaction for budget j
# Step 2: Process each item
for i in range(len(data)):
v, p, q = data[i][0], data[i][1], data[i][2] # Unpack item properties
# Calculate satisfaction for the current item
satisfaction = v * p
# If the item is a main item (q == 0)
if q == 0:
# First, consider this main item
for budget in range(n, v - 1, -1):
dp[budget] = max(dp[budget], dp[budget - v] + satisfaction)
# Set to track added accessories
added_accessories = set()
# Now check for accessories linked to this main item
for j in range(len(data)):
if data[j][2] == i + 1 and j not in added_accessories: # Check for unique accessories
acc_v, acc_p = data[j][0], data[j][1]
acc_satisfaction = acc_v * acc_p
# Update DP considering both main item and its accessory
for budget in range(n, v + acc_v - 1, -1):
if budget >= v + acc_v:
dp[budget] = max(dp[budget], dp[budget - v - acc_v] + satisfaction + acc_satisfaction)
added_accessories.add(j) # Mark this accessory as added
# Output the maximum satisfaction achievable within the budget
print(dp[n])
写完之后发现
示例1:
1000 5
800 2 0
400 5 1
300 5 1
400 3 0
500 2 0
是可以跑出正确的数字,但是示例2卡在120。正确结果是130
示例2:
50 5
20 3 5
20 3 5
10 3 0
10 2 0
10 1 0
想问下大家能帮忙看下这段哪里出问题了吗。AI问了无数遍也没查出来