src/lemon/max_matching.h
author deba
Fri, 04 Mar 2005 17:16:01 +0000
changeset 1192 aa4483befa56
parent 1172 37338ae42a2b
child 1234 49d018060749
permissions -rwxr-xr-x
Adding GraphEdgeSet and GraphNodeSet classes to graph_utils.h.
     1 /* -*- C++ -*-
     2  * src/lemon/max_matching.h - Part of LEMON, a generic C++ optimization library
     3  *
     4  * Copyright (C) 2005 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     5  * (Egervary Combinatorial Optimization Research Group, EGRES).
     6  *
     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.
    10  *
    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
    13  * purpose.
    14  *
    15  */
    16 
    17 #ifndef LEMON_MAX_MATCHING_H
    18 #define LEMON_MAX_MATCHING_H
    19 
    20 #include <queue>
    21 #include <lemon/invalid.h>
    22 #include <lemon/unionfind.h>
    23 #include <lemon/graph_utils.h>
    24 
    25 ///\ingroup galgs
    26 ///\file
    27 ///\brief Maximum matching algorithm.
    28 
    29 namespace lemon {
    30 
    31   /// \addtogroup galgs
    32   /// @{
    33 
    34   ///Edmonds' alternating forest maximum matching algorithm.
    35 
    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. 
    43   ///
    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. 
    51   ///
    52   ///\param Graph The undirected graph type the algorithm runs on.
    53   ///
    54   ///\author Jacint Szabo  
    55   template <typename Graph>
    56   class MaxMatching {
    57 
    58   protected:
    59 
    60     typedef typename Graph::Node Node;
    61     typedef typename Graph::Edge Edge;
    62     typedef typename Graph::UndirEdge UndirEdge;
    63     typedef typename Graph::UndirEdgeIt UndirEdgeIt;
    64     typedef typename Graph::NodeIt NodeIt;
    65     typedef typename Graph::IncEdgeIt IncEdgeIt;
    66 
    67     typedef UnionFindEnum<Node, Graph::template NodeMap> UFE;
    68 
    69   public:
    70     
    71     ///Indicates the Gallai-Edmonds decomposition of the graph.
    72 
    73     ///Indicates the Gallai-Edmonds decomposition of the graph, which
    74     ///shows an upper bound on the size of a maximum matching. The
    75     ///nodes with pos_enum \c D induce a graph with factor-critical
    76     ///components, the nodes in \c A form the canonical barrier, and the
    77     ///nodes in \c C induce a graph having a perfect matching. 
    78     enum pos_enum {
    79       D=0,
    80       A=1,
    81       C=2
    82     }; 
    83 
    84   protected:
    85 
    86     static const int HEUR_density=2;
    87     const Graph& g;
    88     typename Graph::template NodeMap<Node> _mate;
    89     typename Graph::template NodeMap<pos_enum> position;
    90      
    91   public:
    92     
    93     MaxMatching(const Graph& _g) : g(_g), _mate(_g,INVALID), position(_g) {}
    94 
    95     ///Runs Edmonds' algorithm.
    96 
    97     ///Runs Edmonds' algorithm for sparse graphs (number of edges <
    98     ///2*number of nodes), and a heuristical Edmonds' algorithm with a
    99     ///heuristic of postponing shrinks for dense graphs. 
   100     inline void run();
   101 
   102     ///Runs Edmonds' algorithm.
   103     
   104     ///If heur=0 it runs Edmonds' algorithm. If heur=1 it runs
   105     ///Edmonds' algorithm with a heuristic of postponing shrinks,
   106     ///giving a faster algorithm for dense graphs.  
   107     void runEdmonds( int heur );
   108 
   109     ///Finds a greedy matching starting from the actual matching.
   110     
   111     ///Starting form the actual matching stored, it finds a maximal
   112     ///greedy matching.
   113     void greedyMatching();
   114 
   115     ///Returns the size of the actual matching stored.
   116 
   117     ///Returns the size of the actual matching stored. After \ref
   118     ///run() it returns the size of a maximum matching in the graph.
   119     int size() const;
   120 
   121     ///Resets the actual matching to the empty matching.
   122 
   123     ///Resets the actual matching to the empty matching.  
   124     ///
   125     void resetMatching();
   126 
   127     ///Returns the mate of a node in the actual matching.
   128 
   129     ///Returns the mate of a \c node in the actual matching. 
   130     ///Returns INVALID if the \c node is not covered by the actual matching. 
   131     Node mate(Node& node) const {
   132       return _mate[node];
   133     } 
   134 
   135     ///Reads a matching from a \c Node valued \c Node map.
   136 
   137     ///Reads a matching from a \c Node valued \c Node map. This map
   138     ///must be \e symmetric, i.e. if \c map[u]==v then \c map[v]==u
   139     ///must hold, and \c uv will be an edge of the matching.
   140     template<typename NMapN>
   141     void readNMapNode(NMapN& map) {
   142       for(NodeIt v(g); v!=INVALID; ++v) {
   143 	_mate.set(v,map[v]);   
   144       } 
   145     } 
   146     
   147     ///Writes the stored matching to a \c Node valued \c Node map.
   148 
   149     ///Writes the stored matching to a \c Node valued \c Node map. The
   150     ///resulting map will be \e symmetric, i.e. if \c map[u]==v then \c
   151     ///map[v]==u will hold, and now \c uv is an edge of the matching.
   152     template<typename NMapN>
   153     void writeNMapNode (NMapN& map) const {
   154       for(NodeIt v(g); v!=INVALID; ++v) {
   155 	map.set(v,_mate[v]);   
   156       } 
   157     } 
   158 
   159     ///Reads a matching from an \c UndirEdge valued \c Node map.
   160 
   161     ///Reads a matching from an \c UndirEdge valued \c Node map. \c
   162     ///map[v] must be an \c UndirEdge incident to \c v. This map must
   163     ///have the property that if \c g.oppositeNode(u,map[u])==v then
   164     ///\c \c g.oppositeNode(v,map[v])==u holds, and now some edge
   165     ///joining \c u to \c v will be an edge of the matching.
   166     template<typename NMapE>
   167     void readNMapEdge(NMapE& map) {
   168      for(NodeIt v(g); v!=INVALID; ++v) {
   169        UndirEdge e=map[v];
   170 	if ( e!=INVALID )
   171 	  _mate.set(v,g.oppositeNode(v,e));
   172       } 
   173     } 
   174     
   175     ///Writes the matching stored to an \c UndirEdge valued \c Node map.
   176 
   177     ///Writes the stored matching to an \c UndirEdge valued \c Node
   178     ///map. \c map[v] will be an \c UndirEdge incident to \c v. This
   179     ///map will have the property that if \c g.oppositeNode(u,map[u])
   180     ///== v then \c map[u]==map[v] holds, and now this edge is an edge
   181     ///of the matching.
   182     template<typename NMapE>
   183     void writeNMapEdge (NMapE& map)  const {
   184       typename Graph::template NodeMap<bool> todo(g,true); 
   185       for(NodeIt v(g); v!=INVALID; ++v) {
   186 	if ( todo[v] && _mate[v]!=INVALID ) {
   187 	  Node u=_mate[v];
   188 	  for(IncEdgeIt e(g,v); e!=INVALID; ++e) {
   189 	    if ( g.runningNode(e) == u ) {
   190 	      map.set(u,e);
   191 	      map.set(v,e);
   192 	      todo.set(u,false);
   193 	      todo.set(v,false);
   194 	      break;
   195 	    }
   196 	  }
   197 	}
   198       } 
   199     }
   200 
   201 
   202     ///Reads a matching from a \c bool valued \c Edge map.
   203     
   204     ///Reads a matching from a \c bool valued \c Edge map. This map
   205     ///must have the property that there are no two incident edges \c
   206     ///e, \c f with \c map[e]==map[f]==true. The edges \c e with \c
   207     ///map[e]==true form the matching.
   208     template<typename EMapB>
   209     void readEMapBool(EMapB& map) {
   210       for(UndirEdgeIt e(g); e!=INVALID; ++e) {
   211 	if ( map[e] ) {
   212 	  Node u=g.source(e);	  
   213 	  Node v=g.target(e);
   214 	  _mate.set(u,v);
   215 	  _mate.set(v,u);
   216 	} 
   217       } 
   218     }
   219 
   220 
   221     ///Writes the matching stored to a \c bool valued \c Edge map.
   222 
   223     ///Writes the matching stored to a \c bool valued \c Edge
   224     ///map. This map will have the property that there are no two
   225     ///incident edges \c e, \c f with \c map[e]==map[f]==true. The
   226     ///edges \c e with \c map[e]==true form the matching.
   227     template<typename EMapB>
   228     void writeEMapBool (EMapB& map) const {
   229       for(UndirEdgeIt e(g); e!=INVALID; ++e) map.set(e,false);
   230 
   231       typename Graph::template NodeMap<bool> todo(g,true); 
   232       for(NodeIt v(g); v!=INVALID; ++v) {
   233 	if ( todo[v] && _mate[v]!=INVALID ) {
   234 	  Node u=_mate[v];
   235 	  for(IncEdgeIt e(g,v); e!=INVALID; ++e) {
   236 	    if ( g.runningNode(e) == u ) {
   237 	      map.set(e,true);
   238 	      todo.set(u,false);
   239 	      todo.set(v,false);
   240 	      break;
   241 	    }
   242 	  }
   243 	}
   244       } 
   245     }
   246 
   247 
   248     ///Writes the canonical decomposition of the graph after running
   249     ///the algorithm.
   250 
   251     ///After calling any run methods of the class, it writes the
   252     ///Gallai-Edmonds canonical decomposition of the graph. \c map
   253     ///must be a node map of \ref pos_enum 's.
   254     template<typename NMapEnum>
   255     void writePos (NMapEnum& map) const {
   256       for(NodeIt v(g); v!=INVALID; ++v)  map.set(v,position[v]);
   257     }
   258 
   259   private: 
   260 
   261  
   262     void lateShrink(Node v, typename Graph::template NodeMap<Node>& ear,  
   263 		    UFE& blossom, UFE& tree);
   264 
   265     void normShrink(Node v, typename Graph::NodeMap<Node>& ear,  
   266 		    UFE& blossom, UFE& tree);
   267 
   268     bool noShrinkStep(Node x, typename Graph::NodeMap<Node>& ear,  
   269 		      UFE& blossom, UFE& tree, std::queue<Node>& Q);
   270 
   271     void shrinkStep(Node& top, Node& middle, Node& bottom, typename Graph::NodeMap<Node>& ear,  
   272 		    UFE& blossom, UFE& tree, std::queue<Node>& Q);
   273 
   274     void augment(Node x, typename Graph::NodeMap<Node>& ear,  
   275 		 UFE& blossom, UFE& tree);
   276 
   277   };
   278 
   279 
   280   // **********************************************************************
   281   //  IMPLEMENTATIONS
   282   // **********************************************************************
   283 
   284 
   285   template <typename Graph>
   286   void MaxMatching<Graph>::run() {
   287     if ( countUndirEdges(g) < HEUR_density*countNodes(g) ) {
   288       greedyMatching();
   289       runEdmonds(0);
   290     } else runEdmonds(1);
   291   }
   292 
   293 
   294   template <typename Graph>
   295   void MaxMatching<Graph>::runEdmonds( int heur=1 ) {
   296 
   297     for(NodeIt v(g); v!=INVALID; ++v)
   298       position.set(v,C);      
   299 
   300     typename Graph::template NodeMap<Node> ear(g,INVALID); 
   301     //undefined for the base nodes of the blossoms (i.e. for the
   302     //representative elements of UFE blossom) and for the nodes in C 
   303 
   304     typename UFE::MapType blossom_base(g);
   305     UFE blossom(blossom_base);
   306     typename UFE::MapType tree_base(g);
   307     UFE tree(tree_base);
   308     //If these UFE's would be members of the class then also
   309     //blossom_base and tree_base should be a member.
   310 
   311     for(NodeIt v(g); v!=INVALID; ++v) {
   312       if ( position[v]==C && _mate[v]==INVALID ) {
   313 	blossom.insert(v);
   314 	tree.insert(v); 
   315 	position.set(v,D);
   316 	if ( heur == 1 ) lateShrink( v, ear, blossom, tree );
   317 	else normShrink( v, ear, blossom, tree );
   318       }
   319     }
   320   }
   321 
   322     
   323   template <typename Graph>
   324   void MaxMatching<Graph>::lateShrink(Node v, typename Graph::template NodeMap<Node>& ear,  
   325 				      UFE& blossom, UFE& tree) {
   326 
   327     std::queue<Node> Q;   //queue of the totally unscanned nodes
   328     Q.push(v);  
   329     std::queue<Node> R;   
   330     //queue of the nodes which must be scanned for a possible shrink
   331       
   332     while ( !Q.empty() ) {
   333       Node x=Q.front();
   334       Q.pop();
   335       if ( noShrinkStep( x, ear, blossom, tree, Q ) ) return;
   336       else R.push(x);
   337     }
   338       
   339     while ( !R.empty() ) {
   340       Node x=R.front();
   341       R.pop();
   342 	
   343       for( IncEdgeIt e(g,x); e!=INVALID ; ++e ) {
   344 	Node y=g.runningNode(e);
   345 
   346 	if ( position[y] == D && blossom.find(x) != blossom.find(y) ) { 
   347 	  //x and y must be in the same tree
   348 	
   349 	  typename Graph::template NodeMap<bool> path(g,false);
   350 
   351 	  Node b=blossom.find(x);
   352 	  path.set(b,true);
   353 	  b=_mate[b];
   354 	  while ( b!=INVALID ) { 
   355 	    b=blossom.find(ear[b]);
   356 	    path.set(b,true);
   357 	    b=_mate[b];
   358 	  } //going till the root
   359 	
   360 	  Node top=y;
   361 	  Node middle=blossom.find(top);
   362 	  Node bottom=x;
   363 	  while ( !path[middle] )
   364 	    shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
   365 		  
   366 	  Node base=middle;
   367 	  top=x;
   368 	  middle=blossom.find(top);
   369 	  bottom=y;
   370 	  Node blossom_base=blossom.find(base);
   371 	  while ( middle!=blossom_base )
   372 	    shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
   373 		  
   374 	  blossom.makeRep(base);
   375 	} // if shrink is needed
   376 
   377 	while ( !Q.empty() ) {
   378 	  Node x=Q.front();
   379 	  Q.pop();
   380 	  if ( noShrinkStep(x, ear, blossom, tree, Q) ) return;
   381 	  else R.push(x);
   382 	}
   383       } //for e
   384     } // while ( !R.empty() )
   385   }
   386 
   387 
   388   template <typename Graph>
   389   void MaxMatching<Graph>::normShrink(Node v, typename Graph::NodeMap<Node>& ear,  
   390 				      UFE& blossom, UFE& tree) {
   391 
   392     std::queue<Node> Q;   //queue of the unscanned nodes
   393     Q.push(v);  
   394     while ( !Q.empty() ) {
   395 
   396       Node x=Q.front();
   397       Q.pop();
   398 	
   399       for( IncEdgeIt e(g,x); e!=INVALID; ++e ) {
   400 	Node y=g.runningNode(e);
   401 	      
   402 	switch ( position[y] ) {
   403 	case D:          //x and y must be in the same tree
   404 
   405 	  if ( blossom.find(x) != blossom.find(y) ) { //shrink
   406 	    typename Graph::template NodeMap<bool> path(g,false);
   407 	      
   408 	    Node b=blossom.find(x);
   409 	    path.set(b,true);
   410 	    b=_mate[b];
   411 	    while ( b!=INVALID ) { 
   412 	      b=blossom.find(ear[b]);
   413 	      path.set(b,true);
   414 	      b=_mate[b];
   415 	    } //going till the root
   416 	
   417 	    Node top=y;
   418 	    Node middle=blossom.find(top);
   419 	    Node bottom=x;
   420 	    while ( !path[middle] )
   421 	      shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
   422 		
   423 	    Node base=middle;
   424 	    top=x;
   425 	    middle=blossom.find(top);
   426 	    bottom=y;
   427 	    Node blossom_base=blossom.find(base);
   428 	    while ( middle!=blossom_base )
   429 	      shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
   430 		
   431 	    blossom.makeRep(base);
   432 	  }
   433 	  break;
   434 	case C:
   435 	  if ( _mate[y]!=INVALID ) {   //grow
   436 
   437 	    ear.set(y,x);
   438 	    Node w=_mate[y];
   439 	    blossom.insert(w);
   440 	    position.set(y,A); 
   441 	    position.set(w,D); 
   442 	    tree.insert(y);
   443 	    tree.insert(w);
   444 	    tree.join(y,blossom.find(x));  
   445 	    tree.join(w,y);  
   446 	    Q.push(w);
   447 	  } else {                 //augment  
   448 	    augment(x, ear, blossom, tree);
   449 	    _mate.set(x,y);
   450 	    _mate.set(y,x);
   451 	    return;
   452 	  } //if 
   453 	  break;
   454 	default: break;
   455 	}
   456       }
   457     }
   458   }
   459 
   460   template <typename Graph>
   461   void MaxMatching<Graph>::greedyMatching() {
   462     for(NodeIt v(g); v!=INVALID; ++v)
   463       if ( _mate[v]==INVALID ) {
   464 	for( IncEdgeIt e(g,v); e!=INVALID ; ++e ) {
   465 	  Node y=g.runningNode(e);
   466 	  if ( _mate[y]==INVALID && y!=v ) {
   467 	    _mate.set(v,y);
   468 	    _mate.set(y,v);
   469 	    break;
   470 	  }
   471 	}
   472       } 
   473   }
   474    
   475   template <typename Graph>
   476   int MaxMatching<Graph>::size() const {
   477     int s=0;
   478     for(NodeIt v(g); v!=INVALID; ++v) {
   479       if ( _mate[v]!=INVALID ) {
   480 	++s;
   481       }
   482     }
   483     return s/2;
   484   }
   485 
   486   template <typename Graph>
   487   void MaxMatching<Graph>::resetMatching() {
   488     for(NodeIt v(g); v!=INVALID; ++v)
   489       _mate.set(v,INVALID);      
   490   }
   491 
   492   template <typename Graph>
   493   bool MaxMatching<Graph>::noShrinkStep(Node x, typename Graph::NodeMap<Node>& ear,  
   494 					UFE& blossom, UFE& tree, std::queue<Node>& Q) {
   495     for( IncEdgeIt e(g,x); e!= INVALID; ++e ) {
   496       Node y=g.runningNode(e);
   497 	
   498       if ( position[y]==C ) {
   499 	if ( _mate[y]!=INVALID ) {       //grow
   500 	  ear.set(y,x);
   501 	  Node w=_mate[y];
   502 	  blossom.insert(w);
   503 	  position.set(y,A);
   504 	  position.set(w,D);
   505 	  tree.insert(y);
   506 	  tree.insert(w);
   507 	  tree.join(y,blossom.find(x));  
   508 	  tree.join(w,y);  
   509 	  Q.push(w);
   510 	} else {                      //augment 
   511 	  augment(x, ear, blossom, tree);
   512 	  _mate.set(x,y);
   513 	  _mate.set(y,x);
   514 	  return true;
   515 	}
   516       }
   517     }
   518     return false;
   519   }
   520 
   521   template <typename Graph>
   522   void MaxMatching<Graph>::shrinkStep(Node& top, Node& middle, Node& bottom, typename Graph::NodeMap<Node>& ear,  
   523 				      UFE& blossom, UFE& tree, std::queue<Node>& Q) {
   524     ear.set(top,bottom);
   525     Node t=top;
   526     while ( t!=middle ) {
   527       Node u=_mate[t];
   528       t=ear[u];
   529       ear.set(t,u);
   530     } 
   531     bottom=_mate[middle];
   532     position.set(bottom,D);
   533     Q.push(bottom);
   534     top=ear[bottom];		
   535     Node oldmiddle=middle;
   536     middle=blossom.find(top);
   537     tree.erase(bottom);
   538     tree.erase(oldmiddle);
   539     blossom.insert(bottom);
   540     blossom.join(bottom, oldmiddle);
   541     blossom.join(top, oldmiddle);
   542   }
   543 
   544   template <typename Graph>
   545   void MaxMatching<Graph>::augment(Node x, typename Graph::NodeMap<Node>& ear,  
   546 				   UFE& blossom, UFE& tree) { 
   547     Node v=_mate[x];
   548     while ( v!=INVALID ) {
   549 	
   550       Node u=ear[v];
   551       _mate.set(v,u);
   552       Node tmp=v;
   553       v=_mate[u];
   554       _mate.set(u,tmp);
   555     }
   556     typename UFE::ItemIt it;
   557     for (tree.first(it,blossom.find(x)); tree.valid(it); tree.next(it)) {   
   558       if ( position[it] == D ) {
   559 	typename UFE::ItemIt b_it;
   560 	for (blossom.first(b_it,it); blossom.valid(b_it); blossom.next(b_it)) {  
   561 	  position.set( b_it ,C);
   562 	}
   563 	blossom.eraseClass(it);
   564       } else position.set( it ,C);
   565     }
   566     tree.eraseClass(x);
   567 
   568   }
   569 
   570   /// @}
   571   
   572 } //END OF NAMESPACE LEMON
   573 
   574 #endif //LEMON_MAX_MATCHING_H