美团2019秋招笔试:考试策略

题目描述:

题目地址:https://www.nowcoder.com/questionTerminal/a1792d443f914f2b928d2a157cd7900d

美团2019秋招笔试:考试策略_第1张图片

美团2019秋招笔试:考试策略_第2张图片

美团2019秋招笔试:考试策略_第3张图片

我的代码实现:

n = int(input())
k = 120
w, v = [], []
for _ in range(n):
    w1, v1, w2, v2 = [int(i) for i in input().split()]
    w.append([w1, w2])
    v.append([v1, v2])

dp = [[0 for i in range(k + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
    for j in range(1, k + 1):
        dp[i][j] = dp[i-1][j]
        if j >= w[i-1][0] or j >= w[i-1][1]:
            if j >= w[i-1][0] and j >= w[i-1][1]:
                dp[i][j] = max(dp[i][j], dp[i-1][j-w[i-1][0]] + v[i-1][0], dp[i-1][j-w[i-1][1]] + v[i-1][1])
            elif j >= w[i-1][0]:
                dp[i][j] = max(dp[i][j], dp[i-1][j-w[i-1][0]] + v[i-1][0])
            else:
                dp[i][j] = max(dp[i][j], dp[i-1][j-w[i-1][1]] + v[i-1][1])
print(dp[-1][-1])

别人的代码实现(减少了空间复杂度):

n = int(input())
weight = []
value = []
for i in range(n):
    w1, v1, w2, v2 = map(int, input().split())
    weight.append([w1, w2])
    value.append([v1, v2])
 
dp = [0]*121
for i in range(n):
    for j in range(120,0, -1):
        if j >= weight[i][0] or j >= weight[i][1]:
            if j >= weight[i][0] and j >= weight[i][1]:
                dp[j] = max(dp[j-weight[i][0]]+value[i][0], dp[j-weight[i][1]]+value[i][1], dp[j])
            elif j >= weight[i][0]:
                dp[j] = max(dp[j-weight[i][0]]+value[i][0], dp[j])
            else:
                dp[j] = max(dp[j-weight[i][1]]+value[i][1], dp[j])
print(dp[120])

 

你可能感兴趣的:(笔试记录)