2 * src/lemon/max_matching.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Combinatorial Optimization Research Group, EGRES).
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
17 #ifndef LEMON_MAX_MATCHING_H
18 #define LEMON_MAX_MATCHING_H
22 #include <unionfind.h>
23 #include <lemon/graph_utils.h>
27 ///\brief Maximum matching algorithm.
34 ///Edmonds' alternating forest maximum matching algorithm.
36 ///This class provides Edmonds' alternating forest matching
37 ///algorithm. The starting matching (if any) can be passed to the
38 ///algorithm using read-in functions \ref readNMapNode, \ref
39 ///readNMapEdge or \ref readEMapBool depending on the container. The
40 ///resulting maximum matching can be attained by write-out functions
41 ///\ref writeNMapNode, \ref writeNMapEdge or \ref writeEMapBool
42 ///depending on the preferred container.
44 ///The dual side of a matching is a map of the nodes to
45 ///MaxMatching::pos_enum, having values D, A and C showing the
46 ///Gallai-Edmonds decomposition of the graph. The nodes in D induce
47 ///a graph with factor-critical components, the nodes in A form the
48 ///barrier, and the nodes in C induce a graph having a perfect
49 ///matching. This decomposition can be attained by calling \ref
50 ///writePos after running the algorithm. Before subsequent runs,
51 ///the function \ref resetPos() must be called.
53 ///\param Graph The undirected graph type the algorithm runs on.
55 ///\author Jacint Szabo
56 template <typename Graph>
58 typedef typename Graph::Node Node;
59 typedef typename Graph::Edge Edge;
60 typedef typename Graph::UndirEdgeIt UndirEdgeIt;
61 typedef typename Graph::NodeIt NodeIt;
62 typedef typename Graph::IncEdgeIt IncEdgeIt;
64 typedef UnionFindEnum<Node, Graph::template NodeMap> UFE;
68 ///Indicates the Gallai-Edmonds decomposition of the graph.
70 ///Indicates the Gallai-Edmonds decomposition of the graph, which
71 ///shows an upper bound on the size of a maximum matching. The
72 ///nodes with pos_enum \c D induce a graph with factor-critical
73 ///components, the nodes in \c A form the canonical barrier, and the
74 ///nodes in \c C induce a graph having a perfect matching.
83 static const int HEUR_density=2;
85 typename Graph::template NodeMap<Node> mate;
86 typename Graph::template NodeMap<pos_enum> position;
90 MaxMatching(const Graph& _g) : g(_g), mate(_g,INVALID), position(_g,C) {}
92 ///Runs Edmonds' algorithm.
94 ///Runs Edmonds' algorithm for sparse graphs (number of edges <
95 ///2*number of nodes), and a heuristical Edmonds' algorithm with a
96 ///heuristic of postponing shrinks for dense graphs. \pre Before
97 ///the subsequent calls \ref resetPos must be called.
100 ///Runs Edmonds' algorithm.
102 ///If heur=0 it runs Edmonds' algorithm. If heur=1 it runs
103 ///Edmonds' algorithm with a heuristic of postponing shrinks,
104 ///giving a faster algorithm for dense graphs. \pre Before the
105 ///subsequent calls \ref resetPos must be called.
106 void runEdmonds( int heur );
108 ///Finds a greedy matching starting from the actual matching.
110 ///Starting form the actual matching stored, it finds a maximal
112 void greedyMatching();
114 ///Returns the size of the actual matching stored.
116 ///Returns the size of the actual matching stored. After \ref
117 ///run() it returns the size of a maximum matching in the graph.
120 ///Resets the map storing the Gallai-Edmonds decomposition.
122 ///Resets the map storing the Gallai-Edmonds decomposition of the
123 ///graph, making it possible to run the algorithm. Must be called
124 ///before all runs of the Edmonds algorithm, except for the first
128 ///Resets the actual matching to the empty matching.
130 ///Resets the actual matching to the empty matching.
132 void resetMatching();
134 ///Reads a matching from a \c Node map of \c Nodes.
136 ///Reads a matching from a \c Node map of \c Nodes. This map must be \e
137 ///symmetric, i.e. if \c map[u]==v then \c map[v]==u must hold, and
138 ///\c uv will be an edge of the matching.
139 template<typename NMapN>
140 void readNMapNode(NMapN& map) {
141 for(NodeIt v(g); v!=INVALID; ++v) {
146 ///Writes the stored matching to a \c Node map of \c Nodes.
148 ///Writes the stored matching to a \c Node map of \c Nodes. The
149 ///resulting map will be \e symmetric, i.e. if \c map[u]==v then \c
150 ///map[v]==u will hold, and now \c uv is an edge of the matching.
151 template<typename NMapN>
152 void writeNMapNode (NMapN& map) const {
153 for(NodeIt v(g); v!=INVALID; ++v) {
158 ///Reads a matching from a \c Node map of \c Edges.
160 ///Reads a matching from a \c Node map of incident \c Edges. This
161 ///map must have the property that if \c G.target(map[u])==v then \c
162 ///G.target(map[v])==u must hold, and now this edge is an edge of
164 template<typename NMapE>
165 void readNMapEdge(NMapE& map) {
166 for(NodeIt v(g); v!=INVALID; ++v) {
169 g.source(e) == v ? mate.set(v,g.target(e)) : mate.set(v,g.source(e));
173 ///Writes the matching stored to a \c Node map of \c Edges.
175 ///Writes the stored matching to a \c Node map of incident \c
176 ///Edges. This map will have the property that if \c
177 ///g.target(map[u])==v then \c g.target(map[v])==u holds, and now this
178 ///edge is an edge of the matching.
179 template<typename NMapE>
180 void writeNMapEdge (NMapE& map) const {
181 typename Graph::template NodeMap<bool> todo(g,true);
182 for(NodeIt v(g); v!=INVALID; ++v) {
183 if ( todo[v] && mate[v]!=INVALID ) {
185 for(IncEdgeIt e(g,v); e!=INVALID; ++e) {
186 if ( g.target(e) == u ) {
199 ///Reads a matching from an \c Edge map of \c bools.
201 ///Reads a matching from an \c Edge map of \c bools. This map must
202 ///have the property that there are no two adjacent edges \c e, \c
203 ///f with \c map[e]==map[f]==true. The edges \c e with \c
204 ///map[e]==true form the matching.
205 template<typename EMapB>
206 void readEMapBool(EMapB& map) {
207 for(UndirEdgeIt e(g); e!=INVALID; ++e) {
218 ///Writes the matching stored to an \c Edge map of \c bools.
220 ///Writes the matching stored to an \c Edge map of \c bools. This
221 ///map will have the property that there are no two adjacent edges
222 ///\c e, \c f with \c map[e]==map[f]==true. The edges \c e with \c
223 ///map[e]==true form the matching.
224 template<typename EMapB>
225 void writeEMapBool (EMapB& map) const {
226 for(UndirEdgeIt e(g); e!=INVALID; ++e) map.set(e,false);
228 typename Graph::template NodeMap<bool> todo(g,true);
229 for(NodeIt v(g); v!=INVALID; ++v) {
230 if ( todo[v] && mate[v]!=INVALID ) {
232 for(IncEdgeIt e(g,v); e!=INVALID; ++e) {
233 if ( g.target(e) == u ) {
245 ///Writes the canonical decomposition of the graph after running
248 ///After calling any run methods of the class, and before calling
249 ///\ref resetPos(), it writes the Gallai-Edmonds canonical
250 ///decomposition of the graph. \c map must be a node map
251 ///of \ref pos_enum 's.
252 template<typename NMapEnum>
253 void writePos (NMapEnum& map) const {
254 for(NodeIt v(g); v!=INVALID; ++v) map.set(v,position[v]);
259 void lateShrink(Node v, typename Graph::template NodeMap<Node>& ear,
260 UFE& blossom, UFE& tree);
262 void normShrink(Node v, typename Graph::NodeMap<Node>& ear,
263 UFE& blossom, UFE& tree);
265 bool noShrinkStep(Node x, typename Graph::NodeMap<Node>& ear,
266 UFE& blossom, UFE& tree, std::queue<Node>& Q);
268 void shrinkStep(Node& top, Node& middle, Node& bottom, typename Graph::NodeMap<Node>& ear,
269 UFE& blossom, UFE& tree, std::queue<Node>& Q);
271 void augment(Node x, typename Graph::NodeMap<Node>& ear,
272 UFE& blossom, UFE& tree);
277 // **********************************************************************
279 // **********************************************************************
282 template <typename Graph>
283 void MaxMatching<Graph>::run() {
284 if ( countUndirEdges(g) < HEUR_density*countNodes(g) ) {
287 } else runEdmonds(1);
291 template <typename Graph>
292 void MaxMatching<Graph>::runEdmonds( int heur=1 ) {
294 typename Graph::template NodeMap<Node> ear(g,INVALID);
295 //undefined for the base nodes of the blossoms (i.e. for the
296 //representative elements of UFE blossom) and for the nodes in C
298 typename UFE::MapType blossom_base(g);
299 UFE blossom(blossom_base);
300 typename UFE::MapType tree_base(g);
303 for(NodeIt v(g); v!=INVALID; ++v) {
304 if ( position[v]==C && mate[v]==INVALID ) {
308 if ( heur == 1 ) lateShrink( v, ear, blossom, tree );
309 else normShrink( v, ear, blossom, tree );
315 template <typename Graph>
316 void MaxMatching<Graph>::lateShrink(Node v, typename Graph::template NodeMap<Node>& ear,
317 UFE& blossom, UFE& tree) {
319 std::queue<Node> Q; //queue of the totally unscanned nodes
322 //queue of the nodes which must be scanned for a possible shrink
324 while ( !Q.empty() ) {
327 if ( noShrinkStep( x, ear, blossom, tree, Q ) ) return;
331 while ( !R.empty() ) {
335 for( IncEdgeIt e(g,x); e!=INVALID ; ++e ) {
338 if ( position[y] == D && blossom.find(x) != blossom.find(y) ) {
339 //x and y must be in the same tree
341 typename Graph::template NodeMap<bool> path(g,false);
343 Node b=blossom.find(x);
346 while ( b!=INVALID ) {
347 b=blossom.find(ear[b]);
350 } //going till the root
353 Node middle=blossom.find(top);
355 while ( !path[middle] )
356 shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
360 middle=blossom.find(top);
362 Node blossom_base=blossom.find(base);
363 while ( middle!=blossom_base )
364 shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
366 blossom.makeRep(base);
367 } // if shrink is needed
369 while ( !Q.empty() ) {
372 if ( noShrinkStep(x, ear, blossom, tree, Q) ) return;
376 } // while ( !R.empty() )
380 template <typename Graph>
381 void MaxMatching<Graph>::normShrink(Node v, typename Graph::NodeMap<Node>& ear,
382 UFE& blossom, UFE& tree) {
384 std::queue<Node> Q; //queue of the unscanned nodes
386 while ( !Q.empty() ) {
391 for( IncEdgeIt e(g,x); e!=INVALID; ++e ) {
394 switch ( position[y] ) {
395 case D: //x and y must be in the same tree
397 if ( blossom.find(x) != blossom.find(y) ) { //shrink
398 typename Graph::template NodeMap<bool> path(g,false);
400 Node b=blossom.find(x);
403 while ( b!=INVALID ) {
404 b=blossom.find(ear[b]);
407 } //going till the root
410 Node middle=blossom.find(top);
412 while ( !path[middle] )
413 shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
417 middle=blossom.find(top);
419 Node blossom_base=blossom.find(base);
420 while ( middle!=blossom_base )
421 shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
423 blossom.makeRep(base);
427 if ( mate[y]!=INVALID ) { //grow
436 tree.join(y,blossom.find(x));
440 augment(x, ear, blossom, tree);
452 template <typename Graph>
453 void MaxMatching<Graph>::greedyMatching() {
454 for(NodeIt v(g); v!=INVALID; ++v)
455 if ( mate[v]==INVALID ) {
456 for( IncEdgeIt e(g,v); e!=INVALID ; ++e ) {
458 if ( mate[y]==INVALID && y!=v ) {
467 template <typename Graph>
468 int MaxMatching<Graph>::size() const {
470 for(NodeIt v(g); v!=INVALID; ++v) {
471 if ( mate[v]!=INVALID ) {
478 template <typename Graph>
479 void MaxMatching<Graph>::resetPos() {
480 for(NodeIt v(g); v!=INVALID; ++v)
484 template <typename Graph>
485 void MaxMatching<Graph>::resetMatching() {
486 for(NodeIt v(g); v!=INVALID; ++v)
490 template <typename Graph>
491 bool MaxMatching<Graph>::noShrinkStep(Node x, typename Graph::NodeMap<Node>& ear,
492 UFE& blossom, UFE& tree, std::queue<Node>& Q) {
493 for( IncEdgeIt e(g,x); e!= INVALID; ++e ) {
496 if ( position[y]==C ) {
497 if ( mate[y]!=INVALID ) { //grow
505 tree.join(y,blossom.find(x));
509 augment(x, ear, blossom, tree);
519 template <typename Graph>
520 void MaxMatching<Graph>::shrinkStep(Node& top, Node& middle, Node& bottom, typename Graph::NodeMap<Node>& ear,
521 UFE& blossom, UFE& tree, std::queue<Node>& Q) {
524 while ( t!=middle ) {
530 position.set(bottom,D);
533 Node oldmiddle=middle;
534 middle=blossom.find(top);
536 tree.erase(oldmiddle);
537 blossom.insert(bottom);
538 blossom.join(bottom, oldmiddle);
539 blossom.join(top, oldmiddle);
542 template <typename Graph>
543 void MaxMatching<Graph>::augment(Node x, typename Graph::NodeMap<Node>& ear,
544 UFE& blossom, UFE& tree) {
546 while ( v!=INVALID ) {
554 typename UFE::ItemIt it;
555 for (tree.first(it,blossom.find(x)); tree.valid(it); tree.next(it)) {
556 if ( position[it] == D ) {
557 typename UFE::ItemIt b_it;
558 for (blossom.first(b_it,it); blossom.valid(b_it); blossom.next(b_it)) {
559 position.set( b_it ,C);
561 blossom.eraseClass(it);
562 } else position.set( it ,C);
570 } //END OF NAMESPACE LEMON