基于多个可能匹配匹配人的算法

假设我有一组5人P = {1,2,3,4,5},我知道有以下可能性将它们匹配在一起:

{1,2}, {1,3}, {1,5}, {2,1}, {2,4}, {2,5}, {3,1}, {3,4}, {4,2}, {4,3}, {4,5}, {5,1}, {5,2}, {5,4}

For example they could symbolise who likes who (everyone is bisexual,
gender doesn’t matter).

可视化为图形:
《基于多个可能匹配匹配人的算法》

现在我想知道谁能相互匹配,以便每个人都能与某人相匹配.理想情况下,没有人被排除在外.

So based on the example: Who should get married with whom? Ideally no one should stay single.

一点点扭曲:最多3个人可以匹配在一起.

So based on the example: polyamorous marriage is allowed.

所以我可以手动完成并得到一个有效的结果.所以我知道因为{1,2},{1,5}和{2,5}我可以匹配{1,2,5}.

现在这意味着1,2和5人出局,只留下以下组合:

{3,4}, {4,3}

这导致{3,4}.

所以最终的结果可能是:{1,2,5}和{3,4}

So based on the example: Person 1, 2 and 5 get married and person 3
and 5 get married.

再次,可视化为图形:
《基于多个可能匹配匹配人的算法》

现在,这是一个玩具的例子.如果人数和可能的比赛增加,情况会变得复杂得多.

我正在寻找如何用计算机解决这样一个问题的正确方向.

最佳答案 你可以采取一些残酷的递归Python函数

# people is a frozenset
# conflicts is a set of frozenset pairs
def match(people, conflicts):
    if not people:  # people is empty
        return {}
    for group in next_groups(people, conflicts):
        solution = match(people - group, conflicts)
        if solution is not None:
            solution.add(group)
            return solution
    return None


def next_groups(people, conflicts):
    a = min(people)
    for b in people - {a}:
        if frozenset({a, b}) in conflicts:
            continue
        yield frozenset({a, b})
        for c in people - {a, b}:
            if frozenset({a, c}) in conflicts or frozenset({b, c}) in conflicts:
                continue
            yield frozenset({a, b, c})

并记住它(在字典中查找人员以查看上次输出的内容).

点赞