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