python - 如何让每个人都按喜好入座?

标签 python algorithm recursion

这个问题来自CodeEval problem 118

Your team is moving to a new office. In order to make them feel comfortable in a new place you decided to let them pick the seats they want. Each team member has given you a list of seats that he/she would find acceptable. Your goal is to determine whether it is possible to satisfy everyone using these lists.

The seats in the new office are numbered from 1 to N. And the list of seating preferences each team member has given you is unsorted.

Example input and output:

1:[1, 3, 2], 2:[1], 3:[4, 3], 4:[4, 3] --> Yes # possible
1:[1, 3, 2], 2:[1], 3:[1] --> No # not possible

如何解决?


我尝试了什么?我相信解决方案将是递归的,这就是我到目前为止提出的解决方案,但我认为我没有将问题正确分解为更小的子问题。

def seat_team(num_seats, preferences, assigned):
    if len(preferences) == 1:
        for seat in range(len(preferences)):
            print preferences
            seat_wanted = preferences[0][1][seat]
            if not assigned[seat_wanted-1]:
                assigned[seat_wanted-1] = True
                return True, assigned
        return False, assigned
    else:
        for i in range(len(preferences)):
            current = preferences[i]
            for seat in current[1]:
                    found, assigned = seat_team(num_seats, [preferences[i]], assigned)
                    if not found:
                        return False
                    found, assigned = seat_team(num_seats, preferences[i+1:], assigned)
                    if not found:
                        return False
        return True

num_seats = 4
preferences = [(1,[1,3,2]), (2,[1]), (3,[4,3]), (4,[4,3])]
assigned = [False] * num_seats

print seat_team(4, preferences, assigned)

有什么想法吗?我确信这类问题有一个通用名称,以及解决它的算法,但我无法在网上找到类似的问题(或解决方案)。如果您知道任何示例,请分享示例,我将不胜感激。

最佳答案

这是一个标准最大值 Bipartite Matching问题。

集合 S 代表 M 个顶点,每个顶点属于一个成员,集合 T 代表 N 个顶点,每个顶点代表一个座位。如果 ith 成员想要 jth 席位,则存在从 Si 到 Tj 的边。这是必需的二分图。如果maximum matching结果是M,那么我们有解决方案,否则没有。

关于python - 如何让每个人都按喜好入座?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20832994/

相关文章:

php - 将多个 csv 文件组合在一起,并在连接期间添加一列

python - 为什么扁平化列表中的项目为空白

haskell - 以递归方式正确编写存在函数

python - 在 2x2 网格中绘制形状图

python - 如何使用 lxml 和 iterlinks 替换链接

sql - 如何填充表格中缺失的日期

c# - 如何根据 DateTime 值的接近度将两个列表中的所有对象匹配成两个对

javascript - 我是否正确使用了递归?

Python:找到3个相邻的列表项并确定其中第一个的列表索引

c++ - 使 c++11 Dijkstra 实现返回最短路径