【发布时间】:2011-10-18 14:59:47
【问题描述】:
假设我们有一个这样的数字表(我们可以假设它是一个方表):
20 2 1 3 4
5 1 14 8 9
15 12 17 17 11
16 1 1 15 18
20 13 15 5 11
您的工作是计算 n 个数字的最大总和,其中 n 是表中的行数或列数。关键是每个数字必须来自唯一的行和列。
例如,选择 (0,0)、(1,1)、(2,2)、(3,3) 和 (4,4) 处的数字是可以接受的,但 (0,0)、 (0,1)、(2,2)、(3,3) 和 (4,4) 并不是因为前两个数字是从同一行中拉出来的。
我对这个问题的(可笑的)解决方案是遍历行和列的所有可能排列。这适用于小网格,但当然,随着 n 变大,它会非常慢。如果我没记错的话,它的时间复杂度为 O(n!)(示例 Python 代码如下)。
我真的认为这可以在更好的时间解决,但我没有想出足够聪明的东西。
所以我的问题是,应该使用什么算法来解决这个问题?
如果有帮助,这个问题似乎类似于 knapsack problem.
import itertools
import re
grid = """20 2 1 3 4
5 1 14 8 9
15 12 17 17 11
16 1 1 15 18
20 13 15 5 11"""
grid = [[int(x) for x in re.split("\s+", line)] for line in grid.split("\n")]
possible_column_indexes = itertools.permutations(range(len(grid)))
max_sum = 0
max_positions = []
for column_indexes in possible_column_indexes:
current_sum = 0
current_positions = []
for row, col in enumerate(column_indexes):
current_sum += grid[row][col]
current_positions.append("(%d, %d)" % (row, col))
if current_sum > max_sum:
max_sum = current_sum
max_positions = current_positions
print "Max sum is", max_sum
for position in max_positions:
print position
【问题讨论】:
-
出于好奇,您是从哪里遇到这个问题的?
-
它在 codeeval.com 上遇到了挑战。不过我不会说是哪个!