COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/lemon/max_matching.h @ 1139:f59038affc7e

Last change on this file since 1139:f59038affc7e was 1093:31834bad3e84, checked in by jacint, 19 years ago

Adding a function which returns the mate of a node.

  • Property exe set to *
File size: 15.7 KB
Line 
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 <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
29namespace 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    ///Returns the mate of a node in the actual matching.
124
125    ///Returns the mate of a \c node in the actual matching.
126    ///Returns INVALID if the \c node is not covered by the actual matching.
127    Node mate(Node& node) const {
128      return _mate[node];
129    }
130
131    ///Reads a matching from a \c Node map of \c Nodes.
132
133    ///Reads a matching from a \c Node map of \c Nodes. This map must be \e
134    ///symmetric, i.e. if \c map[u]==v then \c map[v]==u must hold, and
135    ///\c uv will be an edge of the matching.
136    template<typename NMapN>
137    void readNMapNode(NMapN& map) {
138      for(NodeIt v(g); v!=INVALID; ++v) {
139        _mate.set(v,map[v]);   
140      }
141    }
142   
143    ///Writes the stored matching to a \c Node map of \c Nodes.
144
145    ///Writes the stored matching to a \c Node map of \c Nodes. The
146    ///resulting map will be \e symmetric, i.e. if \c map[u]==v then \c
147    ///map[v]==u will hold, and now \c uv is an edge of the matching.
148    template<typename NMapN>
149    void writeNMapNode (NMapN& map) const {
150      for(NodeIt v(g); v!=INVALID; ++v) {
151        map.set(v,_mate[v]);   
152      }
153    }
154
155    ///Reads a matching from a \c Node map of \c Edges.
156
157    ///Reads a matching from a \c Node map of incident \c Edges. This
158    ///map must have the property that if \c G.target(map[u])==v then \c
159    ///G.target(map[v])==u must hold, and now this edge is an edge of
160    ///the matching.
161    template<typename NMapE>
162    void readNMapEdge(NMapE& map) {
163     for(NodeIt v(g); v!=INVALID; ++v) {
164        Edge e=map[v];
165        if ( g.valid(e) )
166          g.source(e) == v ? _mate.set(v,g.target(e)) : _mate.set(v,g.source(e));
167      }
168    }
169   
170    ///Writes the matching stored to a \c Node map of \c Edges.
171
172    ///Writes the stored matching to a \c Node map of incident \c
173    ///Edges. This map will have the property that if \c
174    ///g.target(map[u])==v then \c g.target(map[v])==u holds, and now this
175    ///edge is an edge of the matching.
176    template<typename NMapE>
177    void writeNMapEdge (NMapE& map)  const {
178      typename Graph::template NodeMap<bool> todo(g,true);
179      for(NodeIt v(g); v!=INVALID; ++v) {
180        if ( todo[v] && _mate[v]!=INVALID ) {
181          Node u=_mate[v];
182          for(IncEdgeIt e(g,v); e!=INVALID; ++e) {
183            if ( g.target(e) == u ) {
184              map.set(u,e);
185              map.set(v,e);
186              todo.set(u,false);
187              todo.set(v,false);
188              break;
189            }
190          }
191        }
192      }
193    }
194
195
196    ///Reads a matching from an \c Edge map of \c bools.
197   
198    ///Reads a matching from an \c Edge map of \c bools. This map must
199    ///have the property that there are no two adjacent edges \c e, \c
200    ///f with \c map[e]==map[f]==true. The edges \c e with \c
201    ///map[e]==true form the matching.
202    template<typename EMapB>
203    void readEMapBool(EMapB& map) {
204      for(UndirEdgeIt e(g); e!=INVALID; ++e) {
205        if ( map[e] ) {
206          Node u=g.source(e);     
207          Node v=g.target(e);
208          _mate.set(u,v);
209          _mate.set(v,u);
210        }
211      }
212    }
213
214
215    ///Writes the matching stored to an \c Edge map of \c bools.
216
217    ///Writes the matching stored to an \c Edge map of \c bools. This
218    ///map will have the property that there are no two adjacent edges
219    ///\c e, \c f with \c map[e]==map[f]==true. The edges \c e with \c
220    ///map[e]==true form the matching.
221    template<typename EMapB>
222    void writeEMapBool (EMapB& map) const {
223      for(UndirEdgeIt e(g); e!=INVALID; ++e) map.set(e,false);
224
225      typename Graph::template NodeMap<bool> todo(g,true);
226      for(NodeIt v(g); v!=INVALID; ++v) {
227        if ( todo[v] && _mate[v]!=INVALID ) {
228          Node u=_mate[v];
229          for(IncEdgeIt e(g,v); e!=INVALID; ++e) {
230            if ( g.target(e) == u ) {
231              map.set(e,true);
232              todo.set(u,false);
233              todo.set(v,false);
234              break;
235            }
236          }
237        }
238      }
239    }
240
241
242    ///Writes the canonical decomposition of the graph after running
243    ///the algorithm.
244
245    ///After calling any run methods of the class, it writes the
246    ///Gallai-Edmonds canonical decomposition of the graph. \c map
247    ///must be a node map of \ref pos_enum 's.
248    template<typename NMapEnum>
249    void writePos (NMapEnum& map) const {
250      for(NodeIt v(g); v!=INVALID; ++v)  map.set(v,position[v]);
251    }
252
253  private:
254
255    void lateShrink(Node v, typename Graph::template NodeMap<Node>& ear, 
256                    UFE& blossom, UFE& tree);
257
258    void normShrink(Node v, typename Graph::NodeMap<Node>& ear, 
259                    UFE& blossom, UFE& tree);
260
261    bool noShrinkStep(Node x, typename Graph::NodeMap<Node>& ear, 
262                      UFE& blossom, UFE& tree, std::queue<Node>& Q);
263
264    void shrinkStep(Node& top, Node& middle, Node& bottom, typename Graph::NodeMap<Node>& ear, 
265                    UFE& blossom, UFE& tree, std::queue<Node>& Q);
266
267    void augment(Node x, typename Graph::NodeMap<Node>& ear, 
268                 UFE& blossom, UFE& tree);
269
270  };
271
272
273  // **********************************************************************
274  //  IMPLEMENTATIONS
275  // **********************************************************************
276
277
278  template <typename Graph>
279  void MaxMatching<Graph>::run() {
280    if ( countUndirEdges(g) < HEUR_density*countNodes(g) ) {
281      greedyMatching();
282      runEdmonds(0);
283    } else runEdmonds(1);
284  }
285
286
287  template <typename Graph>
288  void MaxMatching<Graph>::runEdmonds( int heur=1 ) {
289
290    for(NodeIt v(g); v!=INVALID; ++v)
291      position.set(v,C);     
292
293    typename Graph::template NodeMap<Node> ear(g,INVALID);
294    //undefined for the base nodes of the blossoms (i.e. for the
295    //representative elements of UFE blossom) and for the nodes in C
296 
297    typename UFE::MapType blossom_base(g);
298    UFE blossom(blossom_base);
299    typename UFE::MapType tree_base(g);
300    UFE tree(tree_base);
301
302    for(NodeIt v(g); v!=INVALID; ++v) {
303      if ( position[v]==C && _mate[v]==INVALID ) {
304        blossom.insert(v);
305        tree.insert(v);
306        position.set(v,D);
307        if ( heur == 1 ) lateShrink( v, ear, blossom, tree );
308        else normShrink( v, ear, blossom, tree );
309      }
310    }
311  }
312
313   
314  template <typename Graph>
315  void MaxMatching<Graph>::lateShrink(Node v, typename Graph::template NodeMap<Node>& ear, 
316                                      UFE& blossom, UFE& tree) {
317
318    std::queue<Node> Q;   //queue of the totally unscanned nodes
319    Q.push(v); 
320    std::queue<Node> R;   
321    //queue of the nodes which must be scanned for a possible shrink
322     
323    while ( !Q.empty() ) {
324      Node x=Q.front();
325      Q.pop();
326      if ( noShrinkStep( x, ear, blossom, tree, Q ) ) return;
327      else R.push(x);
328    }
329     
330    while ( !R.empty() ) {
331      Node x=R.front();
332      R.pop();
333       
334      for( IncEdgeIt e(g,x); e!=INVALID ; ++e ) {
335        Node y=g.target(e);
336
337        if ( position[y] == D && blossom.find(x) != blossom.find(y) ) {
338          //x and y must be in the same tree
339       
340          typename Graph::template NodeMap<bool> path(g,false);
341
342          Node b=blossom.find(x);
343          path.set(b,true);
344          b=_mate[b];
345          while ( b!=INVALID ) {
346            b=blossom.find(ear[b]);
347            path.set(b,true);
348            b=_mate[b];
349          } //going till the root
350       
351          Node top=y;
352          Node middle=blossom.find(top);
353          Node bottom=x;
354          while ( !path[middle] )
355            shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
356                 
357          Node base=middle;
358          top=x;
359          middle=blossom.find(top);
360          bottom=y;
361          Node blossom_base=blossom.find(base);
362          while ( middle!=blossom_base )
363            shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
364                 
365          blossom.makeRep(base);
366        } // if shrink is needed
367
368        while ( !Q.empty() ) {
369          Node x=Q.front();
370          Q.pop();
371          if ( noShrinkStep(x, ear, blossom, tree, Q) ) return;
372          else R.push(x);
373        }
374      } //for e
375    } // while ( !R.empty() )
376  }
377
378
379  template <typename Graph>
380  void MaxMatching<Graph>::normShrink(Node v, typename Graph::NodeMap<Node>& ear, 
381                                      UFE& blossom, UFE& tree) {
382
383    std::queue<Node> Q;   //queue of the unscanned nodes
384    Q.push(v); 
385    while ( !Q.empty() ) {
386
387      Node x=Q.front();
388      Q.pop();
389       
390      for( IncEdgeIt e(g,x); e!=INVALID; ++e ) {
391        Node y=g.target(e);
392             
393        switch ( position[y] ) {
394        case D:          //x and y must be in the same tree
395
396          if ( blossom.find(x) != blossom.find(y) ) { //shrink
397            typename Graph::template NodeMap<bool> path(g,false);
398             
399            Node b=blossom.find(x);
400            path.set(b,true);
401            b=_mate[b];
402            while ( b!=INVALID ) {
403              b=blossom.find(ear[b]);
404              path.set(b,true);
405              b=_mate[b];
406            } //going till the root
407       
408            Node top=y;
409            Node middle=blossom.find(top);
410            Node bottom=x;
411            while ( !path[middle] )
412              shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
413               
414            Node base=middle;
415            top=x;
416            middle=blossom.find(top);
417            bottom=y;
418            Node blossom_base=blossom.find(base);
419            while ( middle!=blossom_base )
420              shrinkStep(top, middle, bottom, ear, blossom, tree, Q);
421               
422            blossom.makeRep(base);
423          }
424          break;
425        case C:
426          if ( _mate[y]!=INVALID ) {   //grow
427
428            ear.set(y,x);
429            Node w=_mate[y];
430            blossom.insert(w);
431            position.set(y,A);
432            position.set(w,D);
433            tree.insert(y);
434            tree.insert(w);
435            tree.join(y,blossom.find(x)); 
436            tree.join(w,y); 
437            Q.push(w);
438          } else {                 //augment 
439            augment(x, ear, blossom, tree);
440            _mate.set(x,y);
441            _mate.set(y,x);
442            return;
443          } //if
444          break;
445        default: break;
446        }
447      }
448    }
449  }
450
451  template <typename Graph>
452  void MaxMatching<Graph>::greedyMatching() {
453    for(NodeIt v(g); v!=INVALID; ++v)
454      if ( _mate[v]==INVALID ) {
455        for( IncEdgeIt e(g,v); e!=INVALID ; ++e ) {
456          Node y=g.target(e);
457          if ( _mate[y]==INVALID && y!=v ) {
458            _mate.set(v,y);
459            _mate.set(y,v);
460            break;
461          }
462        }
463      }
464  }
465   
466  template <typename Graph>
467  int MaxMatching<Graph>::size() const {
468    int s=0;
469    for(NodeIt v(g); v!=INVALID; ++v) {
470      if ( _mate[v]!=INVALID ) {
471        ++s;
472      }
473    }
474    return (int)s/2;
475  }
476
477  template <typename Graph>
478  void MaxMatching<Graph>::resetMatching() {
479    for(NodeIt v(g); v!=INVALID; ++v)
480      _mate.set(v,INVALID);     
481  }
482
483  template <typename Graph>
484  bool MaxMatching<Graph>::noShrinkStep(Node x, typename Graph::NodeMap<Node>& ear, 
485                                        UFE& blossom, UFE& tree, std::queue<Node>& Q) {
486    for( IncEdgeIt e(g,x); e!= INVALID; ++e ) {
487      Node y=g.target(e);
488       
489      if ( position[y]==C ) {
490        if ( _mate[y]!=INVALID ) {       //grow
491          ear.set(y,x);
492          Node w=_mate[y];
493          blossom.insert(w);
494          position.set(y,A);
495          position.set(w,D);
496          tree.insert(y);
497          tree.insert(w);
498          tree.join(y,blossom.find(x)); 
499          tree.join(w,y); 
500          Q.push(w);
501        } else {                      //augment
502          augment(x, ear, blossom, tree);
503          _mate.set(x,y);
504          _mate.set(y,x);
505          return true;
506        }
507      }
508    }
509    return false;
510  }
511
512  template <typename Graph>
513  void MaxMatching<Graph>::shrinkStep(Node& top, Node& middle, Node& bottom, typename Graph::NodeMap<Node>& ear, 
514                                      UFE& blossom, UFE& tree, std::queue<Node>& Q) {
515    ear.set(top,bottom);
516    Node t=top;
517    while ( t!=middle ) {
518      Node u=_mate[t];
519      t=ear[u];
520      ear.set(t,u);
521    }
522    bottom=_mate[middle];
523    position.set(bottom,D);
524    Q.push(bottom);
525    top=ear[bottom];           
526    Node oldmiddle=middle;
527    middle=blossom.find(top);
528    tree.erase(bottom);
529    tree.erase(oldmiddle);
530    blossom.insert(bottom);
531    blossom.join(bottom, oldmiddle);
532    blossom.join(top, oldmiddle);
533  }
534
535  template <typename Graph>
536  void MaxMatching<Graph>::augment(Node x, typename Graph::NodeMap<Node>& ear, 
537                                   UFE& blossom, UFE& tree) {
538    Node v=_mate[x];
539    while ( v!=INVALID ) {
540       
541      Node u=ear[v];
542      _mate.set(v,u);
543      Node tmp=v;
544      v=_mate[u];
545      _mate.set(u,tmp);
546    }
547    typename UFE::ItemIt it;
548    for (tree.first(it,blossom.find(x)); tree.valid(it); tree.next(it)) {   
549      if ( position[it] == D ) {
550        typename UFE::ItemIt b_it;
551        for (blossom.first(b_it,it); blossom.valid(b_it); blossom.next(b_it)) { 
552          position.set( b_it ,C);
553        }
554        blossom.eraseClass(it);
555      } else position.set( it ,C);
556    }
557    tree.eraseClass(x);
558
559  }
560
561  /// @}
562 
563} //END OF NAMESPACE LEMON
564
565#endif //EDMONDS_H
Note: See TracBrowser for help on using the repository browser.