Solution of P10987 [蓝桥杯 2023 国 Python A] 火车运输

· · 题解

你可以浏览这个题解的中文版本。

Template Problem.

Consider the plain dp state f_{i,x,y} denoting the maximum value that can be obtained from the first i items two vehicles filled with items of volume x and y, respectively. There are transfers:

f_{i,x,y}=\max(f_{i-1,x,y},f_{i-1,x-w_i,y}+w_i,f_{i-1,x,y-w_i}+w_i)

Note that the last two expressions are required to ensure that x or y is not less than w_i.

The answer is then f_{n,x,y}.

Finding that space blows up doing this, consider using a rolling array to squash the first dimension.

Time complexity \mathcal{O}(nV^2), space complexity \mathcal{O}(V^2).

line = list(map(int, input().split()))
# print(line)
n = line[0]
a = line[1]
b = line[2]
w = [0] + list(map(int, input().split()))
# print(w)
f = [[[0 for _ in range(b + 1)] for _ in range(a + 1)] for _ in range(2)]
# print(f)
for i in range(1, n + 1):
    p = i % 2
    q = not p
    for x in range(0, a + 1):
        for y in range(0, b + 1):
            # print(i, x, y)
            f[p][x][y] = f[q][x][y]
            if(x >= w[i]):
                f[p][x][y] = max(f[p][x][y], f[q][x - w[i]][y] + w[i])
            if(y >= w[i]):
                f[p][x][y] = max(f[p][x][y], f[q][x][y - w[i]] + w[i])
print(f[n % 2][a][b])