【问题标题】:When given groups of numbers, how can I find the minimal set of groups to represent all the numbers?当给定一组数字时,如何找到代表所有数字的最小组?
【发布时间】:2013-09-26 11:01:21
【问题描述】:

当给定一组数字时,我如何找到覆盖所有数字的最小组?约束是所选组不应重叠。

例如,给定三组数字(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))

我知道我的算法在性能方面有很多漏洞,我认为这可能是一个众所周知的问题。这个问题有什么提示吗?

【问题讨论】:

  • 这是一个经典的 NP 完全问题:en.wikipedia.org/wiki/Set_cover_problem
  • 这实际上是一个非常困难的NP完全问题。在最坏的情况下,您将无法比测试组之间所有可能组合的指数时间蛮力算法做得更好。
  • 注意:“使用 (1,2,3)、(1,2,4) 和 (3,4),没有冗余。” - (1,2,3) 和 (3,4) 覆盖它....
  • @Karoly Horvath:限制是所选组 (1,2,3) 和 (3,4) 不应重叠。我更新了帖子以使其清楚。
  • 用(1,2,3),(1,2,4),(3,4),有冗余,但无解。

标签: algorithm


【解决方案1】:

我从这个网站找到了一个 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 2021-09-24
    • 2013-09-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 2012-12-29
    相关资源
    最近更新 更多