跳到正文

题解

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

tder约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年8月25日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟
题目
P10987

版本

  1. v1当前

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

Template Problem.

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

fi,x,y=max⁡(fi−1,x,y,fi−1,x−wi,y+wi,fi−1,x,y−wi+wi)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 xx or yy is not less than wiw_i.

The answer is then fn,x,yf_{n,x,y}.

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

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


Python
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])
原文