匈牙利算法的python实现

 该算法主要解决的是两个不相交的两个集合最大配对数的问题。假如有两个独立的集合A,B,在AB 中当满足一定条件时能进行匹配,但是每个元素的匹配可能不止一个,那么如何匹配使得AB两个之间匹配达到最大。

# 编写配置函数,其中used列表用来记录B是否被占用,这个在每次对A发现的时候需要清空
# match列表表示B与A中的匹配
# link表示A,B匹配的条件,满足返回真,失败返回FALSE
def find(index_item_A) -> bool:
    for index_item_B in range(len(B)):
        if not used[index_item_B] and link(A[index_item_A],B[index_item_B]):
           used[index_item_B] = True
           if match[index_item_B] == -1 or find(match[index_item_B]):
                match[index_item_B] = index_item_A
                return True
    return False

if __name__ == "__main__":
   count = 0
   #这里的count就是最大的那个匹配数目
   match = [-1 for i in range(len(B))]
   #这里初始化为-1,其含义是A中的与B匹配的下坐标之外,注意不能是0,最终的匹配在这里呈现
   for index in range(len(A)):
       used = [0 for i in range(len(B))]
       if find(index):
          count += 1
    print(count)
发布了42 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wangyhwyh753/article/details/105538700