COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/max_matching.h @ 2023:f34f044a043c

Last change on this file since 2023:f34f044a043c was 2023:f34f044a043c, checked in by jacint, 18 years ago

Unionfind changes induced some bugs here. Also some augmentations made.

  • Property exe set to *
File size: 16.9 KB
RevLine 
[1077]1/* -*- C++ -*-
2 *
[1956]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
[1359]7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
[1077]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>
[1993]23#include <lemon/bits/invalid.h>
[1093]24#include <lemon/unionfind.h>
[1077]25#include <lemon/graph_utils.h>
26
27///\ingroup galgs
28///\file
29///\brief Maximum matching algorithm.
30
31namespace 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
[1090]52  ///writePos after running the algorithm.
[1077]53  ///
54  ///\param Graph The undirected graph type the algorithm runs on.
55  ///
56  ///\author Jacint Szabo 
57  template <typename Graph>
58  class MaxMatching {
[1165]59
60  protected:
61
[1077]62    typedef typename Graph::Node Node;
63    typedef typename Graph::Edge Edge;
[1909]64    typedef typename Graph::UEdge UEdge;
65    typedef typename Graph::UEdgeIt UEdgeIt;
[1077]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
[1165]86  protected:
[1077]87
88    static const int HEUR_density=2;
89    const Graph& g;
[1093]90    typename Graph::template NodeMap<Node> _mate;
[1077]91    typename Graph::template NodeMap<pos_enum> position;
92     
93  public:
94   
[1093]95    MaxMatching(const Graph& _g) : g(_g), _mate(_g,INVALID), position(_g) {}
[1077]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
[1090]101    ///heuristic of postponing shrinks for dense graphs.
[1587]102    void run() {
[1909]103      if ( countUEdges(g) < HEUR_density*countNodes(g) ) {
[1587]104        greedyMatching();
105        runEdmonds(0);
106      } else runEdmonds(1);
107    }
108
[1077]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,
[1090]114    ///giving a faster algorithm for dense graphs. 
[1587]115    void runEdmonds( int heur = 1 ) {
116     
[2023]117      //each vertex is put to C
[1587]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     
[2023]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.
[1587]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
[1077]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.
[1587]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    }
[1077]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.
[1587]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
[1077]181
182    ///Resets the actual matching to the empty matching.
183
184    ///Resets the actual matching to the empty matching. 
185    ///
[1587]186    void resetMatching() {
187      for(NodeIt v(g); v!=INVALID; ++v)
188        _mate.set(v,INVALID);     
189    }
[1077]190
[1093]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
[1165]199    ///Reads a matching from a \c Node valued \c Node map.
[1077]200
[1165]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.
[1077]204    template<typename NMapN>
205    void readNMapNode(NMapN& map) {
206      for(NodeIt v(g); v!=INVALID; ++v) {
[1093]207        _mate.set(v,map[v]);   
[1077]208      }
209    }
210   
[1165]211    ///Writes the stored matching to a \c Node valued \c Node map.
[1077]212
[1165]213    ///Writes the stored matching to a \c Node valued \c Node map. The
[1077]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) {
[1093]219        map.set(v,_mate[v]);   
[1077]220      }
221    }
222
[1909]223    ///Reads a matching from an \c UEdge valued \c Node map.
[1077]224
[1909]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
[1165]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
[1172]229    ///joining \c u to \c v will be an edge of the matching.
[1077]230    template<typename NMapE>
231    void readNMapEdge(NMapE& map) {
[2023]232      for(NodeIt v(g); v!=INVALID; ++v) {
233        UEdge e=map[v];
[1165]234        if ( e!=INVALID )
[1166]235          _mate.set(v,g.oppositeNode(v,e));
[1077]236      }
237    }
238   
[1909]239    ///Writes the matching stored to an \c UEdge valued \c Node map.
[1077]240
[1909]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
[1165]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.
[1077]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) {
[1093]250        if ( todo[v] && _mate[v]!=INVALID ) {
251          Node u=_mate[v];
[1077]252          for(IncEdgeIt e(g,v); e!=INVALID; ++e) {
[1158]253            if ( g.runningNode(e) == u ) {
[1077]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
[1165]266    ///Reads a matching from a \c bool valued \c Edge map.
[1077]267   
[1165]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
[1077]271    ///map[e]==true form the matching.
272    template<typename EMapB>
273    void readEMapBool(EMapB& map) {
[1909]274      for(UEdgeIt e(g); e!=INVALID; ++e) {
[1077]275        if ( map[e] ) {
276          Node u=g.source(e);     
277          Node v=g.target(e);
[1093]278          _mate.set(u,v);
279          _mate.set(v,u);
[1077]280        }
281      }
282    }
283
284
[1165]285    ///Writes the matching stored to a \c bool valued \c Edge map.
[1077]286
[1165]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.
[1077]291    template<typename EMapB>
292    void writeEMapBool (EMapB& map) const {
[1909]293      for(UEdgeIt e(g); e!=INVALID; ++e) map.set(e,false);
[1077]294
295      typename Graph::template NodeMap<bool> todo(g,true);
296      for(NodeIt v(g); v!=INVALID; ++v) {
[1093]297        if ( todo[v] && _mate[v]!=INVALID ) {
298          Node u=_mate[v];
[1077]299          for(IncEdgeIt e(g,v); e!=INVALID; ++e) {
[1158]300            if ( g.runningNode(e) == u ) {
[1077]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
[1090]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.
[1077]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
[1165]325 
[1077]326    void lateShrink(Node v, typename Graph::template NodeMap<Node>& ear, 
327                    UFE& blossom, UFE& tree);
328
[1234]329    void normShrink(Node v, typename Graph::template NodeMap<Node>& ear, 
[1077]330                    UFE& blossom, UFE& tree);
331
[2023]332    void shrink(Node x,Node y, typename Graph::template NodeMap<Node>& ear, 
333                UFE& blossom, UFE& tree,std::queue<Node>& Q);
[1077]334
[1234]335    void shrinkStep(Node& top, Node& middle, Node& bottom,
336                    typename Graph::template NodeMap<Node>& ear, 
[1077]337                    UFE& blossom, UFE& tree, std::queue<Node>& Q);
338
[2023]339    bool growOrAugment(Node& y, Node& x, typename Graph::template
340                       NodeMap<Node>& ear, UFE& blossom, UFE& tree,
341                       std::queue<Node>& Q);
342
[1234]343    void augment(Node x, typename Graph::template NodeMap<Node>& ear, 
[1077]344                 UFE& blossom, UFE& tree);
345
346  };
347
348
349  // **********************************************************************
350  //  IMPLEMENTATIONS
351  // **********************************************************************
352
353
354  template <typename Graph>
[2023]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().
[1077]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();
[2023]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);
[1077]376    }
377     
378    while ( !R.empty() ) {
379      Node x=R.front();
380      R.pop();
381       
382      for( IncEdgeIt e(g,x); e!=INVALID ; ++e ) {
[1158]383        Node y=g.runningNode(e);
[1077]384
[2023]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);
[1077]388       
389        while ( !Q.empty() ) {
390          Node x=Q.front();
391          Q.pop();
[2023]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);
[1077]399        }
400      } //for e
401    } // while ( !R.empty() )
402  }
403
404
405  template <typename Graph>
[1234]406  void MaxMatching<Graph>::normShrink(Node v,
407                                      typename Graph::template
408                                      NodeMap<Node>& ear, 
[1077]409                                      UFE& blossom, UFE& tree) {
[2023]410    //We have one tree, which we grow and shrink. If we augment then we
411    //return to the "for" cycle of runEdmonds().
412   
[1077]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 ) {
[1158]421        Node y=g.runningNode(e);
[1077]422             
423        switch ( position[y] ) {
424        case D:          //x and y must be in the same tree
[2023]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);
[1077]428          break;
429        case C:
[2023]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;
[1077]433          break;
434        default: break;
[2023]435        }
[1077]436      }
437    }
438  }
[2023]439 
[1077]440
441  template <typename Graph>
[2023]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);
[1077]477  }
478
[2023]479
480
[1077]481  template <typename Graph>
[1234]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) {
[2023]487    //We traverse a blossom and update everything.
488   
[1077]489    ear.set(top,bottom);
490    Node t=top;
491    while ( t!=middle ) {
[1093]492      Node u=_mate[t];
[1077]493      t=ear[u];
494      ear.set(t,u);
495    }
[1093]496    bottom=_mate[middle];
[1077]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
[2023]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
[1077]539  template <typename Graph>
[1234]540  void MaxMatching<Graph>::augment(Node x,
541                                   typename Graph::template NodeMap<Node>& ear, 
[1077]542                                   UFE& blossom, UFE& tree) {
[1093]543    Node v=_mate[x];
[1077]544    while ( v!=INVALID ) {
545       
546      Node u=ear[v];
[1093]547      _mate.set(v,u);
[1077]548      Node tmp=v;
[1093]549      v=_mate[u];
550      _mate.set(u,tmp);
[1077]551    }
[2023]552    Node y=blossom.find(x);
[1077]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    }
[2023]563    tree.eraseClass(y);
[1077]564
565  }
566
567  /// @}
568 
569} //END OF NAMESPACE LEMON
570
[1165]571#endif //LEMON_MAX_MATCHING_H
Note: See TracBrowser for help on using the repository browser.