当给定数字组时,如何找到涵盖所有数字的最小组?约束条件是所选组不应重叠。
例如,给定三组数字(1,2),(2,3)和(3,4),我们可以选择(1,2)和(3,4)为(2,3)是多余的。
对于(1,2),(2,3),(3,4),(1,4),我们有两种溶液(1,2),(3,4)或(1,4), (2,3)。
对于(1,2,3),(1,2,4)和(3,4),存在冗余,但没有解决方案。
我想出的算法(对于G =(1,2),(2,3),(3,4),(1,4)例子)是
collect all the numbers from the groups x = (1,2,3,4)
for g in G:
x = remove g in x # x = (3,4)
find G' = (a set of (g' in (G - g))) that makes (G' + g = x) # G' = ((3,4))
if find (G' + g) return (G',g) # return ((1,2)(3,4))
我知道我的算法在性能方面有很多漏洞,我认为这可能是一个众所周知的问题。这个问题有什么提示吗?
答案 0 :(得分:0)
我在这个网站的python中找到了一个工作代码:http://www.cs.mcgill.ca/~aassaf9/python/algorithm_x.html
X = {1, 2, 3, 4, 5, 6, 7}
Y = {
'A': [1, 4, 7],
'B': [1, 4],
'C': [4, 5, 7],
'D': [3, 5, 6],
'E': [2, 3, 6, 7],
'F': [2, 7]}
def solve(X, Y, solution=[]):
if not X:
yield list(solution)
else:
c = min(X, key=lambda c: len(X[c]))
for r in list(X[c]):
solution.append(r)
cols = select(X, Y, r)
for s in solve(X, Y, solution):
yield s
deselect(X, Y, r, cols)
solution.pop()
def select(X, Y, r):
cols = []
for j in Y[r]:
for i in X[j]:
for k in Y[i]:
if k != j:
X[k].remove(i)
cols.append(X.pop(j))
return cols
def deselect(X, Y, r, cols):
for j in reversed(Y[r]):
X[j] = cols.pop()
for i in X[j]:
for k in Y[i]:
if k != j:
X[k].add(i)
X = {j: set(filter(lambda i: j in Y[i], Y)) for j in X}
a = solve(X, Y)
for i in a: print i