ハンガリー語アルゴリズムのPython実装

 このアルゴリズムは、主に2つの互いに素な2つのセットの最大ペアリング数の問題を解決します。2つの独立したセット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 10,000以上のビュー

おすすめ

転載: blog.csdn.net/wangyhwyh753/article/details/105538700