From 23c3e35865e8a690884b1d0532de31fd9bc2f767 Mon Sep 17 00:00:00 2001 From: Joris van Rantwijk Date: Mon, 6 Feb 2023 12:35:35 +0100 Subject: [PATCH] Eliminate edges with negative weight The base algorithm transparently ignores edges, but only if the graph contains at least 1 edge with positive weight. If ALL edges have negative weight, dual variables may be initialized to negative values which leads to failure. --- python/max_weight_matching.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/python/max_weight_matching.py b/python/max_weight_matching.py index a6deb08..0259767 100644 --- a/python/max_weight_matching.py +++ b/python/max_weight_matching.py @@ -28,9 +28,7 @@ def maximum_weight_matching( Isolated vertices (not incident to any edge) are allowed, but not recommended since such vertices consume time and memory but have no effect on the maximum-weight matching. - - Negative edge weights are allowed, but not recommended since such edges - consume time and memory but have no effect on the maximum-weight matching. + Edges with negative weight are ignored. This function takes time O(n**3), where "n" is the number of vertices. This function uses O(n + m) memory, where "m" is the number of edges. @@ -53,6 +51,12 @@ def maximum_weight_matching( _check_input_types(edges) _check_input_graph(edges) + # Eliminate edges with negative weight. + # This does not change the solution but prevents complications + # in the algorithm. + if any(e[2] < 0 for e in edges): + edges = [e for e in edges if e[2] >= 0] + # Special case for empty graphs. if not edges: return []