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