maximum_weighted_matching.hpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  1. //=======================================================================
  2. // Copyright (c) 2018 Yi Ji
  3. // Copyright (c) 2025 Joris van Rantwijk
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. //=======================================================================
  10. #ifndef BOOST_GRAPH_MAXIMUM_WEIGHTED_MATCHING_HPP
  11. #define BOOST_GRAPH_MAXIMUM_WEIGHTED_MATCHING_HPP
  12. #include <boost/assert.hpp>
  13. #include <boost/optional.hpp>
  14. #include <boost/property_map/property_map.hpp>
  15. #include <boost/range/iterator_range_core.hpp>
  16. #include <boost/graph/exception.hpp>
  17. #include <boost/graph/graph_concepts.hpp>
  18. #include <boost/graph/max_cardinality_matching.hpp> // for empty_matching
  19. #include <algorithm>
  20. #include <deque>
  21. #include <limits>
  22. #include <list>
  23. #include <stack>
  24. #include <tuple> // for std::tie
  25. #include <utility> // for std::pair, std::swap
  26. #include <vector>
  27. namespace boost
  28. {
  29. template <typename Graph, typename MateMap, typename VertexIndexMap>
  30. typename property_traits<
  31. typename property_map<Graph, edge_weight_t>::type>::value_type
  32. matching_weight_sum(const Graph& g, MateMap mate, VertexIndexMap vm)
  33. {
  34. using vertex_iterator_t = typename graph_traits<Graph>::vertex_iterator;
  35. using vertex_descriptor_t = typename graph_traits<Graph>::vertex_descriptor;
  36. using edge_property_t = typename property_traits<
  37. typename property_map<Graph, edge_weight_t>::type>::value_type;
  38. edge_property_t weight_sum = 0;
  39. vertex_iterator_t vi, vi_end;
  40. for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi)
  41. {
  42. vertex_descriptor_t v = *vi;
  43. if (get(mate, v) != graph_traits<Graph>::null_vertex()
  44. && get(vm, v) < get(vm, get(mate, v)))
  45. weight_sum += get(edge_weight, g, edge(v, mate[v], g).first);
  46. }
  47. return weight_sum;
  48. }
  49. template <typename Graph, typename MateMap>
  50. inline typename property_traits<
  51. typename property_map<Graph, edge_weight_t>::type>::value_type
  52. matching_weight_sum(const Graph& g, MateMap mate)
  53. {
  54. return matching_weight_sum(g, mate, get(vertex_index, g));
  55. }
  56. // brute-force matcher searches all possible combinations of matched edges to
  57. // get the maximum weighted matching which can be used for testing on small
  58. // graphs (within dozens vertices)
  59. template <typename Graph, typename MateMap, typename VertexIndexMap>
  60. class brute_force_matching
  61. {
  62. public:
  63. using vertex_descriptor_t = typename graph_traits<Graph>::vertex_descriptor;
  64. using vertex_iterator_t = typename graph_traits<Graph>::vertex_iterator;
  65. using vertex_vec_iter_t =
  66. typename std::vector<vertex_descriptor_t>::iterator;
  67. using edge_iterator_t = typename graph_traits<Graph>::edge_iterator;
  68. using vertex_to_vertex_map_t =
  69. boost::iterator_property_map<vertex_vec_iter_t, VertexIndexMap>;
  70. brute_force_matching(
  71. const Graph& arg_g, MateMap arg_mate, VertexIndexMap arg_vm)
  72. : g(&arg_g)
  73. , vm(arg_vm)
  74. , mate_vector(num_vertices(*g))
  75. , best_mate_vector(num_vertices(*g))
  76. , mate(mate_vector.begin(), vm)
  77. , best_mate(best_mate_vector.begin(), vm)
  78. {
  79. vertex_iterator_t vi, vi_end;
  80. for (boost::tie(vi, vi_end) = vertices(*g); vi != vi_end; ++vi)
  81. best_mate[*vi] = mate[*vi] = get(arg_mate, *vi);
  82. }
  83. template <typename PropertyMap> void find_matching(PropertyMap pm)
  84. {
  85. edge_iterator_t ei;
  86. boost::tie(ei, ei_end) = edges(*g);
  87. select_edge(ei);
  88. vertex_iterator_t vi, vi_end;
  89. for (boost::tie(vi, vi_end) = vertices(*g); vi != vi_end; ++vi)
  90. put(pm, *vi, best_mate[*vi]);
  91. }
  92. private:
  93. const Graph* g;
  94. VertexIndexMap vm;
  95. std::vector<vertex_descriptor_t> mate_vector, best_mate_vector;
  96. vertex_to_vertex_map_t mate, best_mate;
  97. edge_iterator_t ei_end;
  98. void select_edge(edge_iterator_t ei)
  99. {
  100. if (ei == ei_end)
  101. {
  102. if (matching_weight_sum(*g, mate)
  103. > matching_weight_sum(*g, best_mate))
  104. {
  105. vertex_iterator_t vi, vi_end;
  106. for (boost::tie(vi, vi_end) = vertices(*g); vi != vi_end; ++vi)
  107. best_mate[*vi] = mate[*vi];
  108. }
  109. return;
  110. }
  111. vertex_descriptor_t v, w;
  112. v = source(*ei, *g);
  113. w = target(*ei, *g);
  114. select_edge(++ei);
  115. if (mate[v] == graph_traits<Graph>::null_vertex()
  116. && mate[w] == graph_traits<Graph>::null_vertex())
  117. {
  118. mate[v] = w;
  119. mate[w] = v;
  120. select_edge(ei);
  121. mate[v] = mate[w] = graph_traits<Graph>::null_vertex();
  122. }
  123. }
  124. };
  125. template <typename Graph, typename MateMap, typename VertexIndexMap>
  126. void brute_force_maximum_weighted_matching(
  127. const Graph& g, MateMap mate, VertexIndexMap vm)
  128. {
  129. empty_matching<Graph, MateMap>::find_matching(g, mate);
  130. brute_force_matching<Graph, MateMap, VertexIndexMap> brute_force_matcher(
  131. g, mate, vm);
  132. brute_force_matcher.find_matching(mate);
  133. }
  134. template <typename Graph, typename MateMap>
  135. inline void brute_force_maximum_weighted_matching(const Graph& g, MateMap mate)
  136. {
  137. brute_force_maximum_weighted_matching(g, mate, get(vertex_index, g));
  138. }
  139. namespace graph
  140. {
  141. namespace detail
  142. {
  143. /** Check that vertex indices are unique and in range [0, V). */
  144. template <typename Graph, typename VertexIndexMap>
  145. void check_vertex_index_range(const Graph& g, VertexIndexMap vm)
  146. {
  147. using index_t = typename property_traits<VertexIndexMap>::value_type;
  148. using unsigned_index_t = typename std::make_unsigned<index_t>::type;
  149. auto nv = num_vertices(g);
  150. std::vector<bool> got_vertex(nv);
  151. for (const auto& x : make_iterator_range(vertices(g)))
  152. {
  153. index_t i = get(vm, x);
  154. if ((i < 0) || (static_cast<unsigned_index_t>(i) >= nv))
  155. throw bad_graph("Invalid vertex index.");
  156. if (got_vertex[i])
  157. throw bad_graph("Duplicate vertex index.");
  158. got_vertex[i] = true;
  159. }
  160. }
  161. /** Check that edge weights are valid. */
  162. template <typename Graph, typename EdgeWeightMap>
  163. void check_maximum_weighted_matching_edge_weights(
  164. const Graph& g, EdgeWeightMap edge_weights)
  165. {
  166. for (const auto& e : make_iterator_range(edges(g)))
  167. {
  168. auto w = get(edge_weights, e);
  169. auto max_weight = (std::numeric_limits<decltype(w)>::max)() / 4;
  170. if (!(w <= max_weight)) // inverted logic to catch NaN
  171. throw bad_graph("Edge weight exceeds maximum supported value.");
  172. }
  173. }
  174. /** Implementation of the matching algorithm. */
  175. template <typename Graph, typename VertexIndexMap, typename EdgeWeightMap>
  176. struct maximum_weighted_matching_context
  177. {
  178. using vertex_t = typename graph_traits<Graph>::vertex_descriptor;
  179. using edge_t = typename graph_traits<Graph>::edge_descriptor;
  180. using vertices_size_t = typename graph_traits<Graph>::vertices_size_type;
  181. using edges_size_t = typename graph_traits<Graph>::edges_size_type;
  182. using weight_t = typename property_traits<EdgeWeightMap>::value_type;
  183. /** Ordered pair of vertices. */
  184. using vertex_pair_t = std::pair<vertex_t, vertex_t>;
  185. /**
  186. * List of edges forming an alternating path or alternating cycle.
  187. *
  188. * The path is defined over top-level blossoms; it skips parts of the path
  189. * that are internal to blossoms. Vertex pairs are oriented to match the
  190. * direction of the path.
  191. */
  192. using alternating_path_t = std::deque<vertex_pair_t>;
  193. /** Top-level blossoms may be labeled "S" or "T" or unlabeled. */
  194. enum blossom_label_t { LABEL_NONE = 0, LABEL_S = 1, LABEL_T = 2 };
  195. struct nontrivial_blossom_t; // forward declaration
  196. /**
  197. * A blossom is either a single vertex, or an odd-length alternating
  198. * cycle over sub-blossoms.
  199. */
  200. struct blossom_t
  201. {
  202. /** Parent of this blossom, or "nullptr" for top-level blossom. */
  203. nontrivial_blossom_t* parent;
  204. /**
  205. * Base vertex of this blossom.
  206. *
  207. * This is the unique vertex inside the blossom which is not matched
  208. * to another vertex in the same blossom.
  209. */
  210. vertex_t base_vertex;
  211. /** Label S or T or NONE, only valid for top-level blossoms. */
  212. blossom_label_t label;
  213. /** True if this is an instance of nontrivial_blossom. */
  214. bool is_nontrivial_blossom;
  215. /** Edge that attaches this blossom to the alternating tree. */
  216. vertex_pair_t tree_edge;
  217. /** Base vertex of the blossom at the root of the alternating tree. */
  218. vertex_t tree_root;
  219. /** Least-slack edge to a different S-blossom. */
  220. optional<edge_t> best_edge;
  221. /** Initialize a blossom instance. */
  222. blossom_t(vertex_t base_vertex = graph_traits<Graph>::null_vertex(),
  223. bool is_nontrivial_blossom = false)
  224. : parent(nullptr)
  225. , base_vertex(base_vertex)
  226. , label(LABEL_NONE)
  227. , is_nontrivial_blossom(is_nontrivial_blossom)
  228. { }
  229. /**
  230. * Cast this blossom_t instance to nontrivial_blossom_t if possible,
  231. * otherwise return "nullptr".
  232. */
  233. nontrivial_blossom_t* nontrivial()
  234. {
  235. // This is much faster than dynamic_cast.
  236. return (is_nontrivial_blossom ?
  237. static_cast<nontrivial_blossom_t*>(this) : nullptr);
  238. }
  239. const nontrivial_blossom_t* nontrivial() const
  240. {
  241. return (is_nontrivial_blossom ?
  242. static_cast<const nontrivial_blossom_t*>(this) : nullptr);
  243. }
  244. };
  245. /**
  246. * A non-trivial blossom is an odd-length alternating cycle over
  247. * 3 or more sub-blossoms.
  248. */
  249. struct nontrivial_blossom_t : public blossom_t
  250. {
  251. struct sub_blossom_t {
  252. /** Pointer to sub-blossom. */
  253. blossom_t* blossom;
  254. /** Vertex pair (x, y) where "x" is a vertex in "blossom" and
  255. "y" is a vertex in the next sub-blossom. */
  256. vertex_pair_t edge;
  257. };
  258. /** List of sub-blossoms, ordered along the alternating cycle. */
  259. std::list<sub_blossom_t> subblossoms;
  260. /** Dual LPP variable for this blossom. */
  261. weight_t dual_var;
  262. /** Least-slack edges to other S-blossoms. */
  263. std::list<edge_t> best_edge_set;
  264. /** Initialize a non-trivial blossom. */
  265. nontrivial_blossom_t(
  266. const std::vector<blossom_t*>& blossoms,
  267. const std::deque<vertex_pair_t>& edges)
  268. : blossom_t(blossoms.front()->base_vertex, true)
  269. , dual_var(0)
  270. {
  271. BOOST_ASSERT(blossoms.size() == edges.size());
  272. BOOST_ASSERT(blossoms.size() % 2 == 1);
  273. BOOST_ASSERT(blossoms.size() >= 3);
  274. auto blossom_it = blossoms.begin();
  275. auto blossom_end = blossoms.end();
  276. auto edge_it = edges.begin();
  277. while (blossom_it != blossom_end) {
  278. subblossoms.push_back({*blossom_it, *edge_it});
  279. ++blossom_it;
  280. ++edge_it;
  281. }
  282. }
  283. /** Find the position of the specified subblossom. */
  284. std::pair<vertices_size_t, typename std::list<sub_blossom_t>::iterator>
  285. find_subblossom(blossom_t* child)
  286. {
  287. vertices_size_t pos = 0;
  288. auto it = subblossoms.begin();
  289. while (it->blossom != child) {
  290. ++it;
  291. ++pos;
  292. BOOST_ASSERT(it != subblossoms.end());
  293. }
  294. return std::make_pair(pos, it);
  295. }
  296. };
  297. /** Specification of a delta step. */
  298. struct delta_step_t
  299. {
  300. /** Type of delta step: 1, 2, 3 or 4. */
  301. int kind;
  302. /** Delta value. */
  303. weight_t value;
  304. /** Edge on which the minimum delta occurs (for delta type 2 or 3). */
  305. edge_t edge;
  306. /** Blossom on which the minimum delta occurs (for delta type 4). */
  307. nontrivial_blossom_t* blossom;
  308. };
  309. /** Similar to vector_property_map, but uses a fixed-size vector. */
  310. template <typename T>
  311. struct vertex_map
  312. {
  313. using key_type = typename property_traits<VertexIndexMap>::key_type;
  314. std::vector<T> vec;
  315. VertexIndexMap vm;
  316. vertex_map(vertices_size_t arg_size, VertexIndexMap arg_vm)
  317. : vec(arg_size)
  318. , vm(arg_vm)
  319. { }
  320. const T& operator[](const key_type& v) const
  321. {
  322. return vec[get(vm, v)];
  323. }
  324. T& operator[](const key_type& v)
  325. {
  326. return vec[get(vm, v)];
  327. }
  328. };
  329. /** Keep track of the least-slack edge out of a bunch of edges. */
  330. struct least_slack_edge_t
  331. {
  332. optional<edge_t> edge;
  333. weight_t slack;
  334. least_slack_edge_t() : slack(0) {}
  335. void update(const edge_t& e, weight_t s)
  336. {
  337. if ((!edge.has_value()) || (s < slack))
  338. {
  339. edge = e;
  340. slack = s;
  341. }
  342. }
  343. };
  344. /** Scale integer edge weights to enable integer-only calculations. */
  345. static constexpr weight_t weight_factor =
  346. std::numeric_limits<weight_t>::is_integer ? 2 : 1;
  347. /** Input graph. */
  348. const Graph* g;
  349. VertexIndexMap vm;
  350. EdgeWeightMap edge_weights;
  351. /** Current mate of each vertex. */
  352. vertex_map<vertex_t> vertex_mate;
  353. /**
  354. * For each vertex, the trivial blossom that contains it.
  355. *
  356. * Pointers to blossoms must remain valid for the life time of
  357. * this data structure, therefore the underlying vector must
  358. * have a fixed size.
  359. */
  360. vertex_map<blossom_t> trivial_blossom;
  361. /**
  362. * List of non-trivial blossoms.
  363. *
  364. * This must be a linked list to ensure that elements can be added
  365. * and removed without invalidating pointers to other elements.
  366. */
  367. std::list<nontrivial_blossom_t> nontrivial_blossom;
  368. /** For each vertex, the unique top-level blossom that contains it. */
  369. vertex_map<blossom_t*> vertex_top_blossom;
  370. /** For each vertex, a variable in the dual LPP. */
  371. vertex_map<weight_t> vertex_dual;
  372. /** For T-vertex or unlabeled vertex, least-slack edge to any S-vertex. */
  373. vertex_map<optional<edge_t>> vertex_best_edge;
  374. /** Queue of S-vertices to be scanned. */
  375. std::deque<vertex_t> scan_queue;
  376. /** Initialize the matching algorithm. */
  377. explicit maximum_weighted_matching_context(
  378. const Graph& arg_g, VertexIndexMap arg_vm, EdgeWeightMap weights)
  379. : g(&arg_g)
  380. , vm(arg_vm)
  381. , edge_weights(weights)
  382. , vertex_mate(num_vertices(*g), arg_vm)
  383. , trivial_blossom(num_vertices(*g), arg_vm)
  384. , vertex_top_blossom(num_vertices(*g), arg_vm)
  385. , vertex_dual(num_vertices(*g), arg_vm)
  386. , vertex_best_edge(num_vertices(*g), arg_vm)
  387. {
  388. // Vertex duals are initialized to half the maximum edge weight.
  389. weight_t max_weight = 0;
  390. for (const edge_t& e : make_iterator_range(edges(*g)))
  391. max_weight = (std::max)(max_weight, get(weights, e));
  392. weight_t init_vertex_dual = max_weight * (weight_factor / 2);
  393. for (const vertex_t& x : make_iterator_range(vertices(*g)))
  394. {
  395. vertex_mate[x] = null_vertex();
  396. trivial_blossom[x].base_vertex = x;
  397. vertex_top_blossom[x] = &trivial_blossom[x];
  398. vertex_dual[x] = init_vertex_dual;
  399. }
  400. }
  401. /** Return the null vertex. */
  402. static vertex_t null_vertex()
  403. {
  404. return graph_traits<Graph>::null_vertex();
  405. }
  406. /** Call a function for every vertex inside the specified blossom. */
  407. template <typename Func>
  408. static void for_vertices_in_blossom(const blossom_t& blossom, Func func)
  409. {
  410. auto ntb = blossom.nontrivial();
  411. if (ntb) {
  412. // Visit all vertices in the non-trivial blossom.
  413. // Use an explicit stack to avoid deep call chains.
  414. std::vector<const nontrivial_blossom_t*> stack;
  415. stack.push_back(ntb);
  416. while (!stack.empty()) {
  417. auto cur = stack.back();
  418. stack.pop_back();
  419. for (const auto& sub : cur->subblossoms) {
  420. ntb = sub.blossom->nontrivial();
  421. if (ntb) {
  422. stack.push_back(ntb);
  423. } else {
  424. func(sub.blossom->base_vertex);
  425. }
  426. }
  427. }
  428. } else {
  429. // A trivial blossom contains just one vertex.
  430. func(blossom.base_vertex);
  431. }
  432. }
  433. /** Mark blossom as the top-level blossom of its vertices. */
  434. void update_top_level_blossom(blossom_t& blossom)
  435. {
  436. BOOST_ASSERT(!blossom.parent);
  437. for_vertices_in_blossom(blossom,
  438. [this,&blossom](vertex_t x)
  439. {
  440. vertex_top_blossom[x] = &blossom;
  441. });
  442. }
  443. /**
  444. * Calculate edge slack.
  445. * The two vertices must be in different top-level blossoms.
  446. */
  447. weight_t edge_slack(const edge_t& e) const
  448. {
  449. vertex_t x = source(e, *g);
  450. vertex_t y = target(e, *g);
  451. weight_t w = get(edge_weights, e);
  452. BOOST_ASSERT(vertex_top_blossom[x] != vertex_top_blossom[y]);
  453. return vertex_dual[x] + vertex_dual[y] - weight_factor * w;
  454. }
  455. /** Clear least-slack edge tracking. */
  456. void clear_best_edge()
  457. {
  458. for (vertex_t x : make_iterator_range(vertices(*g)))
  459. {
  460. vertex_best_edge[x].reset();
  461. trivial_blossom[x].best_edge.reset();
  462. }
  463. for (nontrivial_blossom_t& b : nontrivial_blossom)
  464. {
  465. b.best_edge.reset();
  466. b.best_edge_set.clear();
  467. }
  468. }
  469. /** Add edge from unlabeled verter or T-vertex "y" to an S-vertex. */
  470. void add_delta2_edge(vertex_t y, const edge_t& e, weight_t slack)
  471. {
  472. auto& best_edge = vertex_best_edge[y];
  473. if ((!best_edge.has_value()) || slack < edge_slack(*best_edge))
  474. best_edge = e;
  475. }
  476. /** Return least-slack edge between any unlabeled vertex and S-vertex. */
  477. least_slack_edge_t get_least_slack_delta2_edge()
  478. {
  479. least_slack_edge_t best_edge;
  480. for (vertex_t x : make_iterator_range(vertices(*g)))
  481. {
  482. if (vertex_top_blossom[x]->label == LABEL_NONE)
  483. {
  484. const auto& vertex_edge = vertex_best_edge[x];
  485. if (vertex_edge.has_value())
  486. best_edge.update(*vertex_edge, edge_slack(*vertex_edge));
  487. }
  488. }
  489. return best_edge;
  490. }
  491. /** Add edge between different S-blossoms. */
  492. void add_delta3_edge(blossom_t& b, const edge_t& e, weight_t slack)
  493. {
  494. auto& best_edge = b.best_edge;
  495. if ((!best_edge.has_value()) || slack < edge_slack(*best_edge))
  496. best_edge = e;
  497. auto ntb = b.nontrivial();
  498. if (ntb)
  499. ntb->best_edge_set.push_back(e);
  500. }
  501. /** Update least-slack edge tracking after merging blossoms. */
  502. void merge_delta3_blossoms(nontrivial_blossom_t& blossom)
  503. {
  504. // Build a temporary array holding the least-slack edges to
  505. // other S-blossoms. The array is indexed by base vertex.
  506. std::vector<least_slack_edge_t> tmp_best_edge(num_vertices(*g));
  507. // Collect edges from sub-blossoms that were S-blossoms.
  508. for (auto& sub : blossom.subblossoms)
  509. {
  510. blossom_t* b = sub.blossom;
  511. if (b->label == LABEL_S)
  512. {
  513. b->best_edge.reset();
  514. auto ntb = b->nontrivial();
  515. if (ntb)
  516. {
  517. // Use least-slack edges from subblossom.
  518. for (const edge_t& e : ntb->best_edge_set)
  519. {
  520. blossom_t* bx = vertex_top_blossom[source(e, *g)];
  521. blossom_t* by = vertex_top_blossom[target(e, *g)];
  522. BOOST_ASSERT(bx == &blossom);
  523. // Only use edges between top-level blossoms.
  524. if (bx != by)
  525. {
  526. BOOST_ASSERT(by->label == LABEL_S);
  527. tmp_best_edge[get(vm, by->base_vertex)].update(
  528. e, edge_slack(e));
  529. }
  530. }
  531. ntb->best_edge_set.clear();
  532. }
  533. else
  534. {
  535. // Trivial blossoms don't maintain a least-slack edge set.
  536. // Consider all incident edges.
  537. for (const edge_t& e :
  538. make_iterator_range(out_edges(b->base_vertex, *g)))
  539. {
  540. BOOST_ASSERT(source(e, *g) == b->base_vertex);
  541. vertex_t y = target(e, *g);
  542. blossom_t* by = vertex_top_blossom[y];
  543. // Only use edges to different S-blossoms.
  544. // Ignore edges with negative weight.
  545. if ((by != &blossom)
  546. && (by->label == LABEL_S)
  547. && (get(edge_weights, e) >= 0))
  548. {
  549. tmp_best_edge[get(vm, by->base_vertex)].update(
  550. e, edge_slack(e));
  551. }
  552. }
  553. }
  554. }
  555. }
  556. // Build a compact list of edges from the temporary array.
  557. // Also find the overall least-slack edge to any other S-blossom.
  558. BOOST_ASSERT(blossom.best_edge_set.empty());
  559. BOOST_ASSERT(!blossom.best_edge.has_value());
  560. least_slack_edge_t best_edge;
  561. for (const least_slack_edge_t& item : tmp_best_edge)
  562. {
  563. if (item.edge.has_value())
  564. {
  565. blossom.best_edge_set.push_back(*item.edge);
  566. best_edge.update(*item.edge, item.slack);
  567. }
  568. }
  569. blossom.best_edge = best_edge.edge;
  570. }
  571. /** Return least-slack edge between any pair of S-blossoms. */
  572. least_slack_edge_t get_least_slack_delta3_edge()
  573. {
  574. least_slack_edge_t best_edge;
  575. for (vertex_t x : make_iterator_range(vertices(*g)))
  576. {
  577. blossom_t* b = vertex_top_blossom[x];
  578. BOOST_ASSERT(!b->parent);
  579. if ((b->label == LABEL_S) && (b->best_edge.has_value()))
  580. best_edge.update(*b->best_edge, edge_slack(*b->best_edge));
  581. }
  582. return best_edge;
  583. }
  584. /** Add the vertices in a blossom to the scan queue. */
  585. void add_vertices_to_scan_queue(blossom_t& blossom)
  586. {
  587. for_vertices_in_blossom(blossom,
  588. [this](vertex_t x)
  589. {
  590. scan_queue.push_back(x);
  591. });
  592. }
  593. /** Trace back through the alternating trees from vertices "x" and "y". */
  594. alternating_path_t trace_alternating_paths(vertex_t x, vertex_t y)
  595. {
  596. // Initialize a path containing only the edge (x, y).
  597. alternating_path_t path;
  598. path.emplace_back(x, y);
  599. // Trace alternating path from "x" to the root of the tree.
  600. while (x != null_vertex())
  601. {
  602. blossom_t* bx = vertex_top_blossom[x];
  603. x = bx->tree_edge.first;
  604. if (x != null_vertex())
  605. path.push_front(bx->tree_edge);
  606. }
  607. // Trace alternating path from "y" to the root of the tree.
  608. while (y != null_vertex())
  609. {
  610. blossom_t* by = vertex_top_blossom[y];
  611. y = by->tree_edge.first;
  612. if (y != null_vertex())
  613. path.emplace_back(by->tree_edge.second, y);
  614. }
  615. // If we found a common ancestor, trim the paths so they end there.
  616. while (path.front().second == path.back().first)
  617. {
  618. BOOST_ASSERT(path.size() > 2);
  619. path.pop_front();
  620. path.pop_back();
  621. }
  622. // Any alternating path between S-blossoms must have odd length.
  623. BOOST_ASSERT(path.size() % 2 == 1);
  624. return path;
  625. }
  626. /** Create a new S-blossom from an alternating cycle. */
  627. void make_blossom(const alternating_path_t& path)
  628. {
  629. BOOST_ASSERT(path.size() % 2 == 1);
  630. BOOST_ASSERT(path.size() >= 3);
  631. // Collect pointers to sub-blossoms.
  632. std::vector<blossom_t*> subblossoms;
  633. subblossoms.reserve(path.size());
  634. for (const vertex_pair_t& edge : path)
  635. subblossoms.push_back(vertex_top_blossom[edge.first]);
  636. // Check that the path is cyclic.
  637. vertices_size_t pos = 0;
  638. for (const vertex_pair_t& edge : path)
  639. {
  640. pos = (pos + 1) % subblossoms.size();
  641. BOOST_ASSERT(vertex_top_blossom[edge.second] == subblossoms[pos]);
  642. }
  643. // Create the new blossom.
  644. nontrivial_blossom.emplace_back(subblossoms, path);
  645. nontrivial_blossom_t& blossom = nontrivial_blossom.back();
  646. // Link the subblossoms to the new parent.
  647. // Insert former T-vertices into the scan queue.
  648. for (blossom_t* b : subblossoms)
  649. {
  650. BOOST_ASSERT(!b->parent);
  651. b->parent = &blossom;
  652. if (b->label == LABEL_T)
  653. add_vertices_to_scan_queue(*b);
  654. }
  655. // Mark vertices as belonging to the new blossom.
  656. update_top_level_blossom(blossom);
  657. // Assign label S to the new blossom and link to the alternating tree.
  658. BOOST_ASSERT(subblossoms.front()->label == LABEL_S);
  659. blossom.label = LABEL_S;
  660. blossom.tree_edge = subblossoms.front()->tree_edge;
  661. blossom.tree_root = subblossoms.front()->tree_root;
  662. // Merge least-slack edges for the S-sub-blossoms.
  663. merge_delta3_blossoms(blossom);
  664. }
  665. /** Expand and delete a T-blossom. */
  666. void expand_t_blossom(nontrivial_blossom_t* blossom)
  667. {
  668. BOOST_ASSERT(!blossom->parent);
  669. BOOST_ASSERT(blossom->label == LABEL_T);
  670. // Convert sub-blossoms into top-level blossoms.
  671. for (const auto& sub : blossom->subblossoms)
  672. {
  673. blossom_t* b = sub.blossom;
  674. BOOST_ASSERT(b->parent == blossom);
  675. b->parent = nullptr;
  676. b->label = LABEL_NONE;
  677. update_top_level_blossom(*b);
  678. }
  679. // Reconstruct the alternating tree via the sub-blossoms.
  680. // Find the sub-blossom that attaches the expanding blossom to
  681. // the alternating tree.
  682. blossom_t* entry = vertex_top_blossom[blossom->tree_edge.second];
  683. auto subblossom_loc = blossom->find_subblossom(entry);
  684. auto entry_pos = subblossom_loc.first;
  685. auto entry_it = subblossom_loc.second;
  686. // Get the edge that attached this blossom to the alternating tree.
  687. vertex_t x, y;
  688. std::tie(x, y) = blossom->tree_edge;
  689. // Reconstruct the tree in an even number of steps from entry to base.
  690. auto sub_it = entry_it;
  691. if (entry_pos % 2 == 0)
  692. {
  693. // Walk backward around the blossom.
  694. auto sub_begin = blossom->subblossoms.begin();
  695. while (sub_it != sub_begin)
  696. {
  697. extend_tree_s_to_t(x, y);
  698. --sub_it;
  699. BOOST_ASSERT(sub_it != sub_begin);
  700. --sub_it;
  701. std::tie(y, x) = sub_it->edge;
  702. }
  703. }
  704. else
  705. {
  706. // Walk forward around the blossom.
  707. auto sub_end = blossom->subblossoms.end();
  708. while (sub_it != sub_end) {
  709. extend_tree_s_to_t(x, y);
  710. ++sub_it;
  711. BOOST_ASSERT(sub_it != sub_end);
  712. std::tie(x, y) = sub_it->edge;
  713. ++sub_it;
  714. }
  715. }
  716. // Assign label T to the base sub-blossom.
  717. blossom_t* base = blossom->subblossoms.front().blossom;
  718. base->label = LABEL_T;
  719. base->tree_edge = std::make_pair(x, y);
  720. base->tree_root = blossom->tree_root;
  721. // Delete the expanded blossom.
  722. auto blossom_it = std::find_if(
  723. nontrivial_blossom.begin(),
  724. nontrivial_blossom.end(),
  725. [blossom](const nontrivial_blossom_t& b)
  726. {
  727. return (&b == blossom);
  728. });
  729. BOOST_ASSERT(blossom_it != nontrivial_blossom.end());
  730. nontrivial_blossom.erase(blossom_it);
  731. }
  732. void augment_blossom_rec(
  733. nontrivial_blossom_t& blossom, blossom_t& entry,
  734. std::stack<std::pair<nontrivial_blossom_t*, blossom_t*>>& stack)
  735. {
  736. auto subblossom_loc = blossom.find_subblossom(&entry);
  737. auto entry_pos = subblossom_loc.first;
  738. auto entry_it = subblossom_loc.second;
  739. // Walk from entry to the base in an even number of steps.
  740. auto sub_begin = blossom.subblossoms.begin();
  741. auto sub_end = blossom.subblossoms.end();
  742. auto sub_it = entry_it;
  743. while ((sub_it != sub_begin) && (sub_it != sub_end)) {
  744. vertex_t x, y;
  745. blossom_t* bx;
  746. blossom_t* by;
  747. if (entry_pos % 2 == 0)
  748. {
  749. // Walk backward around the blossom.
  750. --sub_it;
  751. by = sub_it->blossom;
  752. BOOST_ASSERT(sub_it != sub_begin);
  753. --sub_it;
  754. bx = sub_it->blossom;
  755. std::tie(x, y) = sub_it->edge;
  756. }
  757. else
  758. {
  759. // Walk forward around the blossom.
  760. ++sub_it;
  761. BOOST_ASSERT(sub_it != sub_end);
  762. std::tie(x, y) = sub_it->edge;
  763. bx = sub_it->blossom;
  764. ++sub_it;
  765. by = (sub_it == sub_end) ?
  766. blossom.subblossoms.front().blossom :
  767. sub_it->blossom;
  768. }
  769. // Pull this edge into the matching.
  770. vertex_mate[x] = y;
  771. vertex_mate[y] = x;
  772. // Augment through any non-trivial subblossoms touching this edge.
  773. auto bx_ntb = bx->nontrivial();
  774. if (bx_ntb)
  775. stack.emplace(bx_ntb, &trivial_blossom[x]);
  776. auto by_ntb = by->nontrivial();
  777. if (by_ntb)
  778. stack.emplace(by_ntb, &trivial_blossom[y]);
  779. }
  780. // Re-orient the blossom.
  781. if (entry_it != sub_begin)
  782. blossom.subblossoms.splice(
  783. sub_begin, blossom.subblossoms, entry_it, sub_end);
  784. blossom.base_vertex = entry.base_vertex;
  785. }
  786. void augment_blossom(nontrivial_blossom_t& blossom, blossom_t& entry)
  787. {
  788. // Use an explicit stack to avoid deep call chains.
  789. std::stack<std::pair<nontrivial_blossom_t*, blossom_t*>> stack;
  790. stack.emplace(&blossom, &entry);
  791. while (!stack.empty()) {
  792. nontrivial_blossom_t* outer_blossom;
  793. blossom_t* inner_entry;
  794. std::tie(outer_blossom, inner_entry) = stack.top();
  795. nontrivial_blossom_t* inner_blossom = inner_entry->parent;
  796. BOOST_ASSERT(inner_blossom);
  797. if (inner_blossom != outer_blossom)
  798. stack.top() = std::make_pair(outer_blossom, inner_blossom);
  799. else
  800. stack.pop();
  801. augment_blossom_rec(*inner_blossom, *inner_entry, stack);
  802. }
  803. }
  804. /** Augment the matching through the specified augmenting path. */
  805. void augment_matching(const alternating_path_t& path)
  806. {
  807. BOOST_ASSERT(path.size() % 2 == 1);
  808. // Process the unmatched edges on the augmenting path.
  809. auto path_it = path.begin();
  810. auto path_end = path.end();
  811. while (path_it != path_end)
  812. {
  813. vertex_t x = path_it->first;
  814. vertex_t y = path_it->second;
  815. // Augment any non-trivial blossoms that touch this edge.
  816. blossom_t* bx = vertex_top_blossom[x];
  817. auto bx_ntb = bx->nontrivial();
  818. if (bx_ntb)
  819. augment_blossom(*bx_ntb, trivial_blossom[x]);
  820. blossom_t* by = vertex_top_blossom[y];
  821. auto by_ntb = by->nontrivial();
  822. if (by_ntb)
  823. augment_blossom(*by_ntb, trivial_blossom[y]);
  824. // Pull this edge into the matching.
  825. vertex_mate[x] = y;
  826. vertex_mate[y] = x;
  827. // Go to the next unmatched edge on the path.
  828. ++path_it;
  829. if (path_it == path_end)
  830. break;
  831. ++path_it;
  832. }
  833. }
  834. /**
  835. * Remove non-S-vertices from the scan queue.
  836. * This is necessary after removing labels from S-blossoms.
  837. */
  838. void refresh_scan_queue()
  839. {
  840. std::deque<vertex_t> new_scan_queue;
  841. for (const vertex_t& x : scan_queue)
  842. {
  843. if (vertex_top_blossom[x]->label == LABEL_S)
  844. new_scan_queue.push_back(x);
  845. }
  846. scan_queue = std::move(new_scan_queue);
  847. }
  848. /** Remove edges to non-S-vertices from delta3 edge tracking. */
  849. void refresh_delta3_blossom(blossom_t& b)
  850. {
  851. // Do nothing if this blossom was not tracking any delta3 edge.
  852. if (!b.best_edge.has_value())
  853. return;
  854. auto ntb = b.nontrivial();
  855. if (ntb)
  856. {
  857. // Remove bad edges from best_edge_set and refresh best_edge.
  858. least_slack_edge_t best_edge;
  859. auto it = ntb->best_edge_set.begin();
  860. auto it_end = ntb->best_edge_set.end();
  861. while (it != it_end)
  862. {
  863. vertex_t y = target(*it, *g);
  864. blossom_t* by = vertex_top_blossom[y];
  865. BOOST_ASSERT(by != &b);
  866. if (by->label == LABEL_S)
  867. {
  868. best_edge.update(*it, edge_slack(*it));
  869. ++it;
  870. }
  871. else
  872. {
  873. // Remove edge to non-S-blossom.
  874. it = ntb->best_edge_set.erase(it);
  875. }
  876. }
  877. b.best_edge = best_edge.edge;
  878. }
  879. else
  880. {
  881. // Trivial blossom does not maintain best_edge_set.
  882. // If its current best_edge is invalid, recompute it.
  883. vertex_t x = b.base_vertex;
  884. vertex_t y = target(*b.best_edge, *g);
  885. blossom_t* by = vertex_top_blossom[y];
  886. BOOST_ASSERT(by != &b);
  887. if (by->label != LABEL_S)
  888. {
  889. // Consider all incident edges to recompute best_edge.
  890. least_slack_edge_t best_edge;
  891. for (const edge_t& e : make_iterator_range(out_edges(x, *g)))
  892. {
  893. BOOST_ASSERT(source(e, *g) == x);
  894. y = target(e, *g);
  895. by = vertex_top_blossom[y];
  896. if ((by != &b) && (by->label == LABEL_S))
  897. best_edge.update(e, edge_slack(e));
  898. }
  899. b.best_edge = best_edge.edge;
  900. }
  901. }
  902. }
  903. /** Recompute vertex_best_edge for the specified vertex. */
  904. void recompute_vertex_best_edge(vertex_t x)
  905. {
  906. least_slack_edge_t best_edge;
  907. for (const edge_t& e : make_iterator_range(out_edges(x, *g)))
  908. {
  909. BOOST_ASSERT(source(e, *g) == x);
  910. vertex_t y = target(e, *g);
  911. blossom_t* by = vertex_top_blossom[y];
  912. if (by->label == LABEL_S)
  913. best_edge.update(e, edge_slack(e));
  914. }
  915. vertex_best_edge[x] = best_edge.edge;
  916. }
  917. /** Remove the alternating trees with specified root vertices. */
  918. void remove_alternating_tree(vertex_t r1, vertex_t r2)
  919. {
  920. // Find blossoms that are part of the specified alternating trees.
  921. std::vector<blossom_t*> former_s_blossoms;
  922. for (vertex_t x : make_iterator_range(vertices(*g)))
  923. {
  924. blossom_t* b = vertex_top_blossom[x];
  925. if ((!b->parent)
  926. && (b->label != LABEL_NONE)
  927. && (b->tree_root == r1 || b->tree_root == r2))
  928. {
  929. // Build list of former S-blossoms.
  930. if (b->label == LABEL_S)
  931. former_s_blossoms.push_back(b);
  932. // Remove label.
  933. b->label = LABEL_NONE;
  934. }
  935. }
  936. vertex_map<char> blossom_recompute_best_edge(num_vertices(*g), vm);
  937. vertex_map<char> vertex_recompute_best_edge(num_vertices(*g), vm);
  938. // Visit former S-blossoms.
  939. for (blossom_t* b : former_s_blossoms)
  940. {
  941. // Clear best_edge tracking.
  942. b->best_edge.reset();
  943. auto ntb = b->nontrivial();
  944. if (ntb)
  945. ntb->best_edge_set.clear();
  946. // Visit edges that touch this blossom.
  947. for_vertices_in_blossom(*b,
  948. [&](vertex_t x)
  949. {
  950. // Mark former S-vertices.
  951. vertex_recompute_best_edge[x] = 1;
  952. for (const edge_t& e :
  953. make_iterator_range(out_edges(x, *g)))
  954. {
  955. // Mark S-blossoms adjacent to the former S-blossom.
  956. BOOST_ASSERT(source(e, *g) == x);
  957. vertex_t y = target(e, *g);
  958. blossom_t* by = vertex_top_blossom[y];
  959. if (by->label == LABEL_S)
  960. blossom_recompute_best_edge[by->base_vertex] = 1;
  961. // Mark non-S-vertices with least-slack edge to
  962. // former S-blossom.
  963. if (by->label != LABEL_S)
  964. {
  965. const auto& best_edge = vertex_best_edge[y];
  966. if (best_edge.has_value() && (*best_edge == e))
  967. vertex_recompute_best_edge[y] = 1;
  968. }
  969. }
  970. });
  971. }
  972. // Recompute delta3 tracking of affected S-blossoms.
  973. for (vertex_t x : make_iterator_range(vertices(*g)))
  974. {
  975. if (blossom_recompute_best_edge[x])
  976. refresh_delta3_blossom(*vertex_top_blossom[x]);
  977. }
  978. // Recompute vertex_best_edge of affected non-S-vertices.
  979. for (vertex_t x : make_iterator_range(vertices(*g)))
  980. {
  981. if (vertex_recompute_best_edge[x])
  982. recompute_vertex_best_edge(x);
  983. }
  984. refresh_scan_queue();
  985. }
  986. /**
  987. * Extend the alternating tree via the edge from S-vertex "x"
  988. * to unlabeled vertex "y".
  989. *
  990. * Assign label T to the blossom that contains "y", then assign
  991. * label S to the blossom matched to the newly labeled T-blossom.
  992. */
  993. void extend_tree_s_to_t(vertex_t x, vertex_t y)
  994. {
  995. blossom_t* bx = vertex_top_blossom[x];
  996. blossom_t* by = vertex_top_blossom[y];
  997. BOOST_ASSERT(bx->label == LABEL_S);
  998. BOOST_ASSERT(by->label == LABEL_NONE);
  999. by->label = LABEL_T;
  1000. by->tree_edge = std::make_pair(x, y);
  1001. by->tree_root = bx->tree_root;
  1002. vertex_t y2 = by->base_vertex;
  1003. vertex_t z = vertex_mate[y2];
  1004. BOOST_ASSERT(z != null_vertex());
  1005. blossom_t* bz = vertex_top_blossom[z];
  1006. BOOST_ASSERT(bz->label == LABEL_NONE);
  1007. BOOST_ASSERT(!bz->best_edge.has_value());
  1008. bz->label = LABEL_S;
  1009. bz->tree_edge = std::make_pair(y2, z);
  1010. bz->tree_root = by->tree_root;
  1011. add_vertices_to_scan_queue(*bz);
  1012. }
  1013. /**
  1014. * Add the edge between S-vertices "x" and "y".
  1015. *
  1016. * If the edge connects blossoms that are part of the same alternating
  1017. * tree, a new S-blossom is created.
  1018. *
  1019. * If the edge connects two different alternating trees, an augmenting
  1020. * path has been discovered. In this case the matching is augmented.
  1021. *
  1022. * @return true if the matching was augmented; otherwise false.
  1023. */
  1024. bool add_s_to_s_edge(vertex_t x, vertex_t y)
  1025. {
  1026. blossom_t* bx = vertex_top_blossom[x];
  1027. blossom_t* by = vertex_top_blossom[y];
  1028. BOOST_ASSERT(bx->label == LABEL_S);
  1029. BOOST_ASSERT(by->label == LABEL_S);
  1030. BOOST_ASSERT(bx != by);
  1031. alternating_path_t path = trace_alternating_paths(x, y);
  1032. // Check whether the path starts and ends in the same blossom.
  1033. blossom_t* b1 = vertex_top_blossom[path.front().first];
  1034. blossom_t* b2 = vertex_top_blossom[path.back().second];
  1035. if (b1 == b2)
  1036. {
  1037. make_blossom(path);
  1038. return false;
  1039. }
  1040. else
  1041. {
  1042. // Remove labels the two alternating trees on the augmenting path.
  1043. remove_alternating_tree(bx->tree_root, by->tree_root);
  1044. // Augment matching.
  1045. augment_matching(path);
  1046. return true;
  1047. }
  1048. }
  1049. /**
  1050. * Scan incident edges of newly labeled S-vertices.
  1051. *
  1052. * @return true if the matching was augmented; otherwise false.
  1053. */
  1054. bool scan_new_s_vertices()
  1055. {
  1056. while (!scan_queue.empty())
  1057. {
  1058. vertex_t x = scan_queue.front();
  1059. scan_queue.pop_front();
  1060. BOOST_ASSERT(vertex_top_blossom[x]->label == LABEL_S);
  1061. for (const edge_t& e : make_iterator_range(out_edges(x, *g)))
  1062. {
  1063. BOOST_ASSERT(source(e, *g) == x);
  1064. vertex_t y = target(e, *g);
  1065. // Note: top level blossom of x may change during this loop,
  1066. // so we must look it up on each pass.
  1067. blossom_t* bx = vertex_top_blossom[x];
  1068. blossom_t* by = vertex_top_blossom[y];
  1069. // Ignore internal edges in blossom.
  1070. if (bx == by)
  1071. continue;
  1072. // Ignore edges with negative slack to prevent numeric overflow.
  1073. if (get(edge_weights, e) < 0)
  1074. continue;
  1075. weight_t slack = edge_slack(e);
  1076. if (slack <= 0)
  1077. {
  1078. // Tight edge.
  1079. if (by->label == LABEL_NONE)
  1080. extend_tree_s_to_t(x, y);
  1081. else if (by->label == LABEL_S)
  1082. {
  1083. bool augmented = add_s_to_s_edge(x, y);
  1084. if (augmented)
  1085. return true;
  1086. }
  1087. }
  1088. else
  1089. {
  1090. // Track non-tight edges between S-blossoms.
  1091. if (by->label == LABEL_S)
  1092. add_delta3_edge(*bx, e, slack);
  1093. }
  1094. // Track all edges between S-blossom and non-S-blossom.
  1095. if (by->label != LABEL_S)
  1096. add_delta2_edge(y, e, slack);
  1097. }
  1098. }
  1099. return false;
  1100. }
  1101. /** Calculate a delta step in the dual LPP problem. */
  1102. delta_step_t calc_dual_delta_step()
  1103. {
  1104. delta_step_t delta{};
  1105. // Compute delta1: minimum dual variable of any S-vertex.
  1106. delta.kind = 1;
  1107. delta.value = (std::numeric_limits<weight_t>::max)();
  1108. for (vertex_t x : make_iterator_range(vertices(*g)))
  1109. {
  1110. if (vertex_top_blossom[x]->label == LABEL_S)
  1111. delta.value = (std::min)(delta.value, vertex_dual[x]);
  1112. }
  1113. // Compute delta2: minimum slack of edge from S-vertex to unlabeled.
  1114. least_slack_edge_t best_edge = get_least_slack_delta2_edge();
  1115. if (best_edge.edge.has_value() && (best_edge.slack <= delta.value))
  1116. {
  1117. delta.kind = 2;
  1118. delta.edge = *best_edge.edge;
  1119. delta.value = best_edge.slack;
  1120. }
  1121. // Compute delta3: half minimum slack of edge between S-blossoms.
  1122. best_edge = get_least_slack_delta3_edge();
  1123. if (best_edge.edge.has_value() && (best_edge.slack / 2 <= delta.value))
  1124. {
  1125. delta.kind = 3;
  1126. delta.edge = *best_edge.edge;
  1127. delta.value = best_edge.slack / 2;
  1128. }
  1129. // Compute delta4: half minimum dual of a top-level T-blossom.
  1130. for (nontrivial_blossom_t& blossom : nontrivial_blossom)
  1131. {
  1132. if ((!blossom.parent)
  1133. && (blossom.label == LABEL_T)
  1134. && (blossom.dual_var / 2 <= delta.value))
  1135. {
  1136. delta.kind = 4;
  1137. delta.blossom = &blossom;
  1138. delta.value = blossom.dual_var / 2;
  1139. }
  1140. }
  1141. return delta;
  1142. }
  1143. /** Apply a delta step to the dual LPP variables. */
  1144. void apply_delta_step(weight_t delta)
  1145. {
  1146. for (vertex_t x : make_iterator_range(vertices(*g)))
  1147. {
  1148. blossom_t* b = vertex_top_blossom[x];
  1149. if (b->label == LABEL_S)
  1150. vertex_dual[x] -= delta;
  1151. else if (b->label == LABEL_T)
  1152. vertex_dual[x] += delta;
  1153. }
  1154. for (nontrivial_blossom_t& blossom : nontrivial_blossom)
  1155. {
  1156. if (!blossom.parent)
  1157. {
  1158. if (blossom.label == LABEL_S)
  1159. blossom.dual_var += 2 * delta;
  1160. else if (blossom.label == LABEL_T)
  1161. blossom.dual_var -= 2 * delta;
  1162. }
  1163. }
  1164. }
  1165. /**
  1166. * Run one stage of the matching algorithm.
  1167. *
  1168. * @return True if the matching was successfully augmented;
  1169. * false if no further improvement is possible.
  1170. */
  1171. bool run_stage()
  1172. {
  1173. // Run substages.
  1174. while (true) {
  1175. bool augmented = scan_new_s_vertices();
  1176. if (augmented)
  1177. return true;
  1178. delta_step_t delta = calc_dual_delta_step();
  1179. apply_delta_step(delta.value);
  1180. if (delta.kind == 2)
  1181. {
  1182. vertex_t x = source(delta.edge, *g);
  1183. vertex_t y = target(delta.edge, *g);
  1184. if (vertex_top_blossom[x]->label != LABEL_S)
  1185. std::swap(x, y);
  1186. extend_tree_s_to_t(x, y);
  1187. }
  1188. else if (delta.kind == 3)
  1189. {
  1190. vertex_t x = source(delta.edge, *g);
  1191. vertex_t y = target(delta.edge, *g);
  1192. augmented = add_s_to_s_edge(x, y);
  1193. if (augmented)
  1194. return true;
  1195. }
  1196. else if (delta.kind == 4)
  1197. {
  1198. BOOST_ASSERT(delta.blossom);
  1199. expand_t_blossom(delta.blossom);
  1200. }
  1201. else
  1202. {
  1203. // No further improvement possible.
  1204. BOOST_ASSERT(delta.kind == 1);
  1205. return false;
  1206. }
  1207. }
  1208. }
  1209. /** Run the matching algorithm. */
  1210. void run()
  1211. {
  1212. // Assign label S to all vertices and put them in the queue.
  1213. for (vertex_t x : make_iterator_range(vertices(*g)))
  1214. {
  1215. BOOST_ASSERT(vertex_mate[x] == null_vertex());
  1216. blossom_t* bx = vertex_top_blossom[x];
  1217. BOOST_ASSERT(bx->label == LABEL_NONE);
  1218. BOOST_ASSERT(bx->base_vertex == x);
  1219. bx->label = LABEL_S;
  1220. bx->tree_edge = std::make_pair(null_vertex(), x);
  1221. bx->tree_root = x;
  1222. scan_queue.push_back(x);
  1223. }
  1224. // Improve the solution until no further improvement is possible.
  1225. while (run_stage()) ;
  1226. // Clear temporary data structures.
  1227. scan_queue.clear();
  1228. clear_best_edge();
  1229. }
  1230. /** Copy matching to specified map. */
  1231. template <typename MateMap>
  1232. void extract_matching(MateMap mate)
  1233. {
  1234. for (vertex_t x : make_iterator_range(vertices(*g)))
  1235. put(mate, x, vertex_mate[x]);
  1236. }
  1237. };
  1238. } // namespace detail
  1239. } // namespace graph
  1240. /**
  1241. * Compute a maximum-weighted matching in an undirected weighted graph.
  1242. *
  1243. * This function takes time O(V^3).
  1244. * This function uses memory size O(V + E).
  1245. *
  1246. * @param g Input graph.
  1247. * The graph type must be a model of VertexListGraph
  1248. * and EdgeListGraph and IncidenceGraph.
  1249. * The graph must be undirected.
  1250. * The graph may not contain parallel edges.
  1251. *
  1252. * @param mate ReadWritePropertyMap, mapping vertices to vertices.
  1253. * This map returns the result of the computation.
  1254. * For each vertex "v", "mate[v]" is the vertex that is
  1255. * matched to "v", or "null_vertex()" if "v" is not matched.
  1256. *
  1257. * @param vm ReadablePropertyMap, mapping vertices to indexes
  1258. * in range [0, num_vertices(g)).
  1259. *
  1260. * @param weights ReadablePropertyMap, mapping edges to edge weights.
  1261. * Edge weights must be integers or floating point values.
  1262. *
  1263. * @throw boost::bad_graph If the input graph is not valid.
  1264. */
  1265. template <typename Graph, typename MateMap, typename VertexIndexMap,
  1266. typename EdgeWeightMap>
  1267. void maximum_weighted_matching(
  1268. const Graph& g, MateMap mate, VertexIndexMap vm, EdgeWeightMap weights)
  1269. {
  1270. BOOST_CONCEPT_ASSERT((VertexListGraphConcept<Graph>));
  1271. BOOST_CONCEPT_ASSERT((EdgeListGraphConcept<Graph>));
  1272. BOOST_CONCEPT_ASSERT((IncidenceGraphConcept<Graph>));
  1273. BOOST_STATIC_ASSERT(is_undirected_graph<Graph>::value);
  1274. using vertex_t = typename graph_traits<Graph>::vertex_descriptor;
  1275. using edge_t = typename graph_traits<Graph>::edge_descriptor;
  1276. BOOST_CONCEPT_ASSERT((ReadWritePropertyMapConcept<MateMap, vertex_t>));
  1277. BOOST_CONCEPT_ASSERT(
  1278. (ReadablePropertyMapConcept<VertexIndexMap, vertex_t>));
  1279. BOOST_CONCEPT_ASSERT((ReadablePropertyMapConcept<EdgeWeightMap, edge_t>));
  1280. graph::detail::check_vertex_index_range(g, vm);
  1281. graph::detail::check_maximum_weighted_matching_edge_weights(g, weights);
  1282. graph::detail::maximum_weighted_matching_context<
  1283. Graph, VertexIndexMap, EdgeWeightMap>
  1284. matching(g, vm, weights);
  1285. matching.run();
  1286. matching.extract_matching(mate);
  1287. }
  1288. /**
  1289. * Compute a maximum-weighted matching in an undirected weighted graph.
  1290. *
  1291. * This overloaded function obtains edge weights from "get(edge_weight, g)".
  1292. */
  1293. template <typename Graph, typename MateMap, typename VertexIndexMap>
  1294. inline void maximum_weighted_matching(
  1295. const Graph& g, MateMap mate, VertexIndexMap vm)
  1296. {
  1297. maximum_weighted_matching(g, mate, vm, get(edge_weight, g));
  1298. }
  1299. /**
  1300. * Compute a maximum-weighted matching in an undirected weighted graph.
  1301. *
  1302. * This overloaded function obtains vertex indices from "get(vertex_index, g)"
  1303. * and edge weights from "get(edge_weight, g)".
  1304. */
  1305. template <typename Graph, typename MateMap>
  1306. inline void maximum_weighted_matching(const Graph& g, MateMap mate)
  1307. {
  1308. maximum_weighted_matching(g, mate, get(vertex_index, g));
  1309. }
  1310. } // namespace boost
  1311. #endif // BOOST_GRAPH_MAXIMUM_WEIGHTED_MATCHING_HPP