lemon/bipartite_matching.h
author deba
Tue, 28 Aug 2007 13:58:54 +0000
changeset 2466 feb7974cf4ec
parent 2463 19651a04d056
child 2488 da94e3b332f3
permissions -rw-r--r--
Redesign of augmenting path based matching
Small bug fix in the push-relabel based
deba@2040
     1
/* -*- C++ -*-
deba@2040
     2
 *
deba@2040
     3
 * This file is a part of LEMON, a generic C++ optimization library
deba@2040
     4
 *
alpar@2391
     5
 * Copyright (C) 2003-2007
deba@2040
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
deba@2040
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
deba@2040
     8
 *
deba@2040
     9
 * Permission to use, modify and distribute this software is granted
deba@2040
    10
 * provided that this copyright notice appears in all copies. For
deba@2040
    11
 * precise terms see the accompanying LICENSE file.
deba@2040
    12
 *
deba@2040
    13
 * This software is provided "AS IS" with no warranty of any kind,
deba@2040
    14
 * express or implied, and with no claim as to its suitability for any
deba@2040
    15
 * purpose.
deba@2040
    16
 *
deba@2040
    17
 */
deba@2040
    18
deba@2040
    19
#ifndef LEMON_BIPARTITE_MATCHING
deba@2040
    20
#define LEMON_BIPARTITE_MATCHING
deba@2040
    21
deba@2051
    22
#include <functional>
deba@2051
    23
deba@2051
    24
#include <lemon/bin_heap.h>
deba@2051
    25
#include <lemon/maps.h>
deba@2040
    26
deba@2040
    27
#include <iostream>
deba@2040
    28
deba@2040
    29
///\ingroup matching
deba@2040
    30
///\file
deba@2040
    31
///\brief Maximum matching algorithms in bipartite graphs.
deba@2462
    32
///
deba@2462
    33
///\note The pr_bipartite_matching.h file also contains algorithms to
deba@2462
    34
///solve maximum cardinality bipartite matching problems.
deba@2040
    35
deba@2040
    36
namespace lemon {
deba@2040
    37
deba@2040
    38
  /// \ingroup matching
deba@2040
    39
  ///
deba@2040
    40
  /// \brief Bipartite Max Cardinality Matching algorithm
deba@2040
    41
  ///
deba@2040
    42
  /// Bipartite Max Cardinality Matching algorithm. This class implements
deba@2051
    43
  /// the Hopcroft-Karp algorithm which has \f$ O(e\sqrt{n}) \f$ time
deba@2040
    44
  /// complexity.
deba@2462
    45
  ///
deba@2462
    46
  /// \note In several cases the push-relabel based algorithms have
deba@2462
    47
  /// better runtime performance than the augmenting path based ones. 
deba@2462
    48
  ///
deba@2462
    49
  /// \see PrBipartiteMatching
deba@2040
    50
  template <typename BpUGraph>
deba@2040
    51
  class MaxBipartiteMatching {
deba@2040
    52
  protected:
deba@2040
    53
deba@2040
    54
    typedef BpUGraph Graph;
deba@2040
    55
deba@2040
    56
    typedef typename Graph::Node Node;
deba@2040
    57
    typedef typename Graph::ANodeIt ANodeIt;
deba@2040
    58
    typedef typename Graph::BNodeIt BNodeIt;
deba@2040
    59
    typedef typename Graph::UEdge UEdge;
deba@2040
    60
    typedef typename Graph::UEdgeIt UEdgeIt;
deba@2040
    61
    typedef typename Graph::IncEdgeIt IncEdgeIt;
deba@2040
    62
deba@2040
    63
    typedef typename BpUGraph::template ANodeMap<UEdge> ANodeMatchingMap;
deba@2040
    64
    typedef typename BpUGraph::template BNodeMap<UEdge> BNodeMatchingMap;
deba@2040
    65
deba@2040
    66
deba@2040
    67
  public:
deba@2040
    68
deba@2040
    69
    /// \brief Constructor.
deba@2040
    70
    ///
deba@2040
    71
    /// Constructor of the algorithm. 
deba@2466
    72
    MaxBipartiteMatching(const BpUGraph& graph) 
deba@2466
    73
      : _matching(graph), _rmatching(graph), _reached(graph), _graph(&graph) {}
deba@2040
    74
deba@2040
    75
    /// \name Execution control
deba@2040
    76
    /// The simplest way to execute the algorithm is to use
deba@2040
    77
    /// one of the member functions called \c run().
deba@2040
    78
    /// \n
deba@2040
    79
    /// If you need more control on the execution,
deba@2040
    80
    /// first you must call \ref init() or one alternative for it.
deba@2040
    81
    /// Finally \ref start() will perform the matching computation or
deba@2040
    82
    /// with step-by-step execution you can augment the solution.
deba@2040
    83
deba@2040
    84
    /// @{
deba@2040
    85
deba@2040
    86
    /// \brief Initalize the data structures.
deba@2040
    87
    ///
deba@2040
    88
    /// It initalizes the data structures and creates an empty matching.
deba@2040
    89
    void init() {
deba@2466
    90
      for (ANodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
    91
        _matching.set(it, INVALID);
deba@2040
    92
      }
deba@2466
    93
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
    94
        _rmatching.set(it, INVALID);
deba@2466
    95
	_reached.set(it, -1);
deba@2040
    96
      }
deba@2466
    97
      _size = 0;
deba@2466
    98
      _phase = -1;
deba@2040
    99
    }
deba@2040
   100
deba@2040
   101
    /// \brief Initalize the data structures.
deba@2040
   102
    ///
deba@2040
   103
    /// It initalizes the data structures and creates a greedy
deba@2040
   104
    /// matching.  From this matching sometimes it is faster to get
deba@2040
   105
    /// the matching than from the initial empty matching.
deba@2040
   106
    void greedyInit() {
deba@2466
   107
      _size = 0;
deba@2466
   108
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   109
        _rmatching.set(it, INVALID);
deba@2466
   110
	_reached.set(it, 0);
deba@2040
   111
      }
deba@2466
   112
      for (ANodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   113
        _matching[it] = INVALID;
deba@2466
   114
        for (IncEdgeIt jt(*_graph, it); jt != INVALID; ++jt) {
deba@2466
   115
          if (_rmatching[_graph->bNode(jt)] == INVALID) {
deba@2466
   116
            _matching.set(it, jt);
deba@2466
   117
	    _rmatching.set(_graph->bNode(jt), jt);
deba@2466
   118
	    _reached.set(it, -1);
deba@2466
   119
            ++_size;
deba@2040
   120
            break;
deba@2040
   121
          }
deba@2040
   122
        }
deba@2040
   123
      }
deba@2466
   124
      _phase = 0;
deba@2040
   125
    }
deba@2040
   126
deba@2040
   127
    /// \brief Initalize the data structures with an initial matching.
deba@2040
   128
    ///
deba@2040
   129
    /// It initalizes the data structures with an initial matching.
deba@2040
   130
    template <typename MatchingMap>
deba@2386
   131
    void matchingInit(const MatchingMap& mm) {
deba@2466
   132
      for (ANodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   133
        _matching.set(it, INVALID);
deba@2040
   134
      }
deba@2466
   135
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   136
        _rmatching.set(it, INVALID);
deba@2466
   137
	_reached.set(it, 0);
deba@2040
   138
      }
deba@2466
   139
      _size = 0;
deba@2466
   140
      for (UEdgeIt it(*_graph); it != INVALID; ++it) {
deba@2386
   141
        if (mm[it]) {
deba@2466
   142
          ++_size;
deba@2466
   143
          _matching.set(_graph->aNode(it), it);
deba@2466
   144
          _rmatching.set(_graph->bNode(it), it);
deba@2466
   145
	  _reached.set(it, 0);
deba@2040
   146
        }
deba@2040
   147
      }
deba@2466
   148
      _phase = 0;
deba@2040
   149
    }
deba@2040
   150
deba@2040
   151
    /// \brief Initalize the data structures with an initial matching.
deba@2040
   152
    ///
deba@2040
   153
    /// It initalizes the data structures with an initial matching.
deba@2040
   154
    /// \return %True when the given map contains really a matching.
deba@2040
   155
    template <typename MatchingMap>
deba@2466
   156
    bool checkedMatchingInit(const MatchingMap& mm) {
deba@2466
   157
      for (ANodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   158
        _matching.set(it, INVALID);
deba@2040
   159
      }
deba@2466
   160
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   161
        _rmatching.set(it, INVALID);
deba@2466
   162
	_reached.set(it, 0);
deba@2040
   163
      }
deba@2466
   164
      _size = 0;
deba@2466
   165
      for (UEdgeIt it(*_graph); it != INVALID; ++it) {
deba@2386
   166
        if (mm[it]) {
deba@2466
   167
          ++_size;
deba@2466
   168
          if (_matching[_graph->aNode(it)] != INVALID) {
deba@2040
   169
            return false;
deba@2040
   170
          }
deba@2466
   171
          _matching.set(_graph->aNode(it), it);
deba@2466
   172
          if (_matching[_graph->bNode(it)] != INVALID) {
deba@2040
   173
            return false;
deba@2040
   174
          }
deba@2466
   175
          _matching.set(_graph->bNode(it), it);
deba@2466
   176
	  _reached.set(_graph->bNode(it), -1);
deba@2040
   177
        }
deba@2040
   178
      }
deba@2466
   179
      _phase = 0;
deba@2466
   180
      return true;
deba@2466
   181
    }
deba@2466
   182
deba@2466
   183
  private:
deba@2466
   184
    
deba@2466
   185
    bool _find_path(Node anode, int maxlevel,
deba@2466
   186
		    typename Graph::template BNodeMap<int>& level) {
deba@2466
   187
      for (IncEdgeIt it(*_graph, anode); it != INVALID; ++it) {
deba@2466
   188
	Node bnode = _graph->bNode(it); 
deba@2466
   189
	if (level[bnode] == maxlevel) {
deba@2466
   190
	  level.set(bnode, -1);
deba@2466
   191
	  if (maxlevel == 0) {
deba@2466
   192
	    _matching.set(anode, it);
deba@2466
   193
	    _rmatching.set(bnode, it);
deba@2466
   194
	    return true;
deba@2466
   195
	  } else {
deba@2466
   196
	    Node nnode = _graph->aNode(_rmatching[bnode]);
deba@2466
   197
	    if (_find_path(nnode, maxlevel - 1, level)) {
deba@2466
   198
	      _matching.set(anode, it);
deba@2466
   199
	      _rmatching.set(bnode, it);
deba@2466
   200
	      return true;
deba@2466
   201
	    }
deba@2466
   202
	  }
deba@2466
   203
	}
deba@2466
   204
      }
deba@2040
   205
      return false;
deba@2040
   206
    }
deba@2040
   207
deba@2466
   208
  public:
deba@2466
   209
deba@2040
   210
    /// \brief An augmenting phase of the Hopcroft-Karp algorithm
deba@2040
   211
    ///
deba@2040
   212
    /// It runs an augmenting phase of the Hopcroft-Karp
deba@2466
   213
    /// algorithm. This phase finds maximal edge disjoint augmenting
deba@2466
   214
    /// paths and augments on these paths. The algorithm consists at
deba@2466
   215
    /// most of \f$ O(\sqrt{n}) \f$ phase and one phase is \f$ O(e)
deba@2466
   216
    /// \f$ long.
deba@2040
   217
    bool augment() {
deba@2040
   218
deba@2466
   219
      ++_phase;
deba@2466
   220
      
deba@2466
   221
      typename Graph::template BNodeMap<int> _level(*_graph, -1);
deba@2466
   222
      typename Graph::template ANodeMap<bool> _found(*_graph, false);
deba@2040
   223
deba@2466
   224
      std::vector<Node> queue, aqueue;
deba@2466
   225
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   226
        if (_rmatching[it] == INVALID) {
deba@2040
   227
          queue.push_back(it);
deba@2466
   228
          _reached.set(it, _phase);
deba@2466
   229
	  _level.set(it, 0);
deba@2040
   230
        }
deba@2040
   231
      }
deba@2040
   232
deba@2040
   233
      bool success = false;
deba@2040
   234
deba@2466
   235
      int level = 0;
deba@2040
   236
      while (!success && !queue.empty()) {
deba@2466
   237
        std::vector<Node> nqueue;
deba@2386
   238
        for (int i = 0; i < int(queue.size()); ++i) {
deba@2466
   239
          Node bnode = queue[i];
deba@2466
   240
          for (IncEdgeIt jt(*_graph, bnode); jt != INVALID; ++jt) {
deba@2466
   241
            Node anode = _graph->aNode(jt);
deba@2466
   242
            if (_matching[anode] == INVALID) {
deba@2466
   243
deba@2466
   244
	      if (!_found[anode]) {
deba@2466
   245
		if (_find_path(anode, level, _level)) {
deba@2466
   246
		  ++_size;
deba@2466
   247
		}
deba@2466
   248
		_found.set(anode, true);
deba@2466
   249
	      }
deba@2040
   250
              success = true;
deba@2040
   251
            } else {           
deba@2466
   252
              Node nnode = _graph->bNode(_matching[anode]);
deba@2466
   253
              if (_reached[nnode] != _phase) {
deba@2466
   254
                _reached.set(nnode, _phase);
deba@2466
   255
                nqueue.push_back(nnode);
deba@2466
   256
		_level.set(nnode, level + 1);
deba@2040
   257
              }
deba@2040
   258
            }
deba@2040
   259
          }
deba@2040
   260
        }
deba@2466
   261
	++level;
deba@2466
   262
        queue.swap(nqueue);
deba@2040
   263
      }
deba@2466
   264
      
deba@2040
   265
      return success;
deba@2040
   266
    }
deba@2466
   267
  private:
deba@2466
   268
    
deba@2466
   269
    void _find_path_bfs(Node anode,
deba@2466
   270
			typename Graph::template ANodeMap<UEdge>& pred) {
deba@2466
   271
      while (true) {
deba@2466
   272
	UEdge uedge = pred[anode];
deba@2466
   273
	Node bnode = _graph->bNode(uedge);
deba@2040
   274
deba@2466
   275
	UEdge nedge = _rmatching[bnode];
deba@2466
   276
deba@2466
   277
	_matching.set(anode, uedge);
deba@2466
   278
	_rmatching.set(bnode, uedge);
deba@2466
   279
deba@2466
   280
	if (nedge == INVALID) break;
deba@2466
   281
	anode = _graph->aNode(nedge);
deba@2466
   282
      }
deba@2466
   283
    }
deba@2466
   284
deba@2466
   285
  public:
deba@2466
   286
deba@2466
   287
    /// \brief An augmenting phase with single path augementing
deba@2040
   288
    ///
deba@2466
   289
    /// This phase finds only one augmenting paths and augments on
deba@2466
   290
    /// these paths. The algorithm consists at most of \f$ O(n) \f$
deba@2466
   291
    /// phase and one phase is \f$ O(e) \f$ long.
deba@2466
   292
    bool simpleAugment() { 
deba@2466
   293
      ++_phase;
deba@2466
   294
      
deba@2466
   295
      typename Graph::template ANodeMap<UEdge> _pred(*_graph);
deba@2040
   296
deba@2466
   297
      std::vector<Node> queue, aqueue;
deba@2466
   298
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   299
        if (_rmatching[it] == INVALID) {
deba@2040
   300
          queue.push_back(it);
deba@2466
   301
          _reached.set(it, _phase);
deba@2040
   302
        }
deba@2040
   303
      }
deba@2040
   304
deba@2466
   305
      bool success = false;
deba@2466
   306
deba@2466
   307
      int level = 0;
deba@2466
   308
      while (!success && !queue.empty()) {
deba@2466
   309
        std::vector<Node> nqueue;
deba@2386
   310
        for (int i = 0; i < int(queue.size()); ++i) {
deba@2466
   311
          Node bnode = queue[i];
deba@2466
   312
          for (IncEdgeIt jt(*_graph, bnode); jt != INVALID; ++jt) {
deba@2466
   313
            Node anode = _graph->aNode(jt);
deba@2466
   314
            if (_matching[anode] == INVALID) {
deba@2466
   315
	      _pred.set(anode, jt);
deba@2466
   316
	      _find_path_bfs(anode, _pred);
deba@2466
   317
	      ++_size;
deba@2466
   318
	      return true;
deba@2040
   319
            } else {           
deba@2466
   320
              Node nnode = _graph->bNode(_matching[anode]);
deba@2466
   321
              if (_reached[nnode] != _phase) {
deba@2466
   322
		_pred.set(anode, jt);
deba@2466
   323
		_reached.set(nnode, _phase);
deba@2466
   324
                nqueue.push_back(nnode);
deba@2040
   325
              }
deba@2040
   326
            }
deba@2040
   327
          }
deba@2040
   328
        }
deba@2466
   329
	++level;
deba@2466
   330
        queue.swap(nqueue);
deba@2040
   331
      }
deba@2040
   332
      
deba@2466
   333
      return success;
deba@2040
   334
    }
deba@2040
   335
deba@2466
   336
deba@2466
   337
deba@2040
   338
    /// \brief Starts the algorithm.
deba@2040
   339
    ///
deba@2040
   340
    /// Starts the algorithm. It runs augmenting phases until the optimal
deba@2040
   341
    /// solution reached.
deba@2040
   342
    void start() {
deba@2040
   343
      while (augment()) {}
deba@2040
   344
    }
deba@2040
   345
deba@2040
   346
    /// \brief Runs the algorithm.
deba@2040
   347
    ///
deba@2040
   348
    /// It just initalize the algorithm and then start it.
deba@2040
   349
    void run() {
deba@2058
   350
      greedyInit();
deba@2040
   351
      start();
deba@2040
   352
    }
deba@2040
   353
deba@2040
   354
    /// @}
deba@2040
   355
deba@2040
   356
    /// \name Query Functions
deba@2040
   357
    /// The result of the %Matching algorithm can be obtained using these
deba@2040
   358
    /// functions.\n
deba@2040
   359
    /// Before the use of these functions,
deba@2040
   360
    /// either run() or start() must be called.
deba@2040
   361
    
deba@2040
   362
    ///@{
deba@2040
   363
deba@2466
   364
    /// \brief Return true if the given uedge is in the matching.
deba@2466
   365
    /// 
deba@2466
   366
    /// It returns true if the given uedge is in the matching.
deba@2466
   367
    bool matchingEdge(const UEdge& edge) const {
deba@2466
   368
      return _matching[_graph->aNode(edge)] == edge;
deba@2466
   369
    }
deba@2466
   370
deba@2466
   371
    /// \brief Returns the matching edge from the node.
deba@2466
   372
    /// 
deba@2466
   373
    /// Returns the matching edge from the node. If there is not such
deba@2466
   374
    /// edge it gives back \c INVALID.
deba@2466
   375
    /// \note If the parameter node is a B-node then the running time is
deba@2466
   376
    /// propotional to the degree of the node.
deba@2466
   377
    UEdge matchingEdge(const Node& node) const {
deba@2466
   378
      if (_graph->aNode(node)) {
deba@2466
   379
        return _matching[node];
deba@2466
   380
      } else {
deba@2466
   381
        return _rmatching[node];
deba@2466
   382
      }
deba@2466
   383
    }
deba@2466
   384
deba@2462
   385
    /// \brief Set true all matching uedge in the map.
deba@2462
   386
    /// 
deba@2462
   387
    /// Set true all matching uedge in the map. It does not change the
deba@2462
   388
    /// value mapped to the other uedges.
deba@2462
   389
    /// \return The number of the matching edges.
deba@2462
   390
    template <typename MatchingMap>
deba@2462
   391
    int quickMatching(MatchingMap& mm) const {
deba@2466
   392
      for (ANodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   393
        if (_matching[it] != INVALID) {
deba@2466
   394
          mm.set(_matching[it], true);
deba@2462
   395
        }
deba@2462
   396
      }
deba@2466
   397
      return _size;
deba@2462
   398
    }
deba@2462
   399
deba@2462
   400
    /// \brief Set true all matching uedge in the map and the others to false.
deba@2462
   401
    /// 
deba@2462
   402
    /// Set true all matching uedge in the map and the others to false.
deba@2462
   403
    /// \return The number of the matching edges.
deba@2462
   404
    template <typename MatchingMap>
deba@2462
   405
    int matching(MatchingMap& mm) const {
deba@2466
   406
      for (UEdgeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   407
        mm.set(it, it == _matching[_graph->aNode(it)]);
deba@2462
   408
      }
deba@2466
   409
      return _size;
deba@2462
   410
    }
deba@2462
   411
deba@2463
   412
    ///Gives back the matching in an ANodeMap.
deba@2463
   413
deba@2463
   414
    ///Gives back the matching in an ANodeMap. The parameter should
deba@2463
   415
    ///be a write ANodeMap of UEdge values.
deba@2463
   416
    ///\return The number of the matching edges.
deba@2463
   417
    template<class MatchingMap>
deba@2463
   418
    int aMatching(MatchingMap& mm) const {
deba@2466
   419
      for (ANodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   420
        mm.set(it, _matching[it]);
deba@2463
   421
      }
deba@2466
   422
      return _size;
deba@2463
   423
    }
deba@2463
   424
deba@2463
   425
    ///Gives back the matching in a BNodeMap.
deba@2463
   426
deba@2463
   427
    ///Gives back the matching in a BNodeMap. The parameter should
deba@2463
   428
    ///be a write BNodeMap of UEdge values.
deba@2463
   429
    ///\return The number of the matching edges.
deba@2463
   430
    template<class MatchingMap>
deba@2463
   431
    int bMatching(MatchingMap& mm) const {
deba@2466
   432
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   433
        mm.set(it, _rmatching[it]);
deba@2463
   434
      }
deba@2466
   435
      return _size;
deba@2462
   436
    }
deba@2462
   437
deba@2462
   438
    /// \brief Returns a minimum covering of the nodes.
deba@2040
   439
    ///
deba@2040
   440
    /// The minimum covering set problem is the dual solution of the
deba@2462
   441
    /// maximum bipartite matching. It provides a solution for this
deba@2040
   442
    /// problem what is proof of the optimality of the matching.
deba@2040
   443
    /// \return The size of the cover set.
deba@2040
   444
    template <typename CoverMap>
deba@2058
   445
    int coverSet(CoverMap& covering) const {
deba@2040
   446
deba@2466
   447
      int size = 0;
deba@2466
   448
      for (ANodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   449
	bool cn = _matching[it] != INVALID && 
deba@2466
   450
	  _reached[_graph->bNode(_matching[it])] == _phase;
deba@2466
   451
        covering.set(it, cn);
deba@2466
   452
        if (cn) ++size;
deba@2040
   453
      }
deba@2466
   454
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   455
	bool cn = _reached[it] != _phase;
deba@2466
   456
        covering.set(it, cn);
deba@2466
   457
        if (cn) ++size;
deba@2040
   458
      }
deba@2040
   459
      return size;
deba@2040
   460
    }
deba@2040
   461
deba@2462
   462
    /// \brief Gives back a barrier on the A-nodes
deba@2466
   463
    ///    
deba@2462
   464
    /// The barrier is s subset of the nodes on the same side of the
deba@2462
   465
    /// graph, which size minus its neighbours is exactly the
deba@2462
   466
    /// unmatched nodes on the A-side.  
deba@2462
   467
    /// \retval barrier A WriteMap on the ANodes with bool value.
deba@2462
   468
    template <typename BarrierMap>
deba@2462
   469
    void aBarrier(BarrierMap& barrier) const {
deba@2462
   470
deba@2466
   471
      for (ANodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   472
        barrier.set(it, _matching[it] == INVALID || 
deba@2466
   473
		    _reached[_graph->bNode(_matching[it])] != _phase);
deba@2040
   474
      }
deba@2040
   475
    }
deba@2040
   476
deba@2462
   477
    /// \brief Gives back a barrier on the B-nodes
deba@2466
   478
    ///    
deba@2462
   479
    /// The barrier is s subset of the nodes on the same side of the
deba@2462
   480
    /// graph, which size minus its neighbours is exactly the
deba@2462
   481
    /// unmatched nodes on the B-side.  
deba@2462
   482
    /// \retval barrier A WriteMap on the BNodes with bool value.
deba@2462
   483
    template <typename BarrierMap>
deba@2462
   484
    void bBarrier(BarrierMap& barrier) const {
deba@2462
   485
deba@2466
   486
      for (BNodeIt it(*_graph); it != INVALID; ++it) {
deba@2466
   487
        barrier.set(it, _reached[it] == _phase);
deba@2462
   488
      }
deba@2466
   489
    }
deba@2462
   490
deba@2466
   491
    /// \brief Gives back the number of the matching edges.
deba@2466
   492
    ///
deba@2466
   493
    /// Gives back the number of the matching edges.
deba@2466
   494
    int matchingSize() const {
deba@2466
   495
      return _size;
deba@2040
   496
    }
deba@2040
   497
deba@2040
   498
    /// @}
deba@2040
   499
deba@2040
   500
  private:
deba@2040
   501
deba@2466
   502
    typename BpUGraph::template ANodeMap<UEdge> _matching;
deba@2466
   503
    typename BpUGraph::template BNodeMap<UEdge> _rmatching;
deba@2040
   504
deba@2466
   505
    typename BpUGraph::template BNodeMap<int> _reached;
deba@2466
   506
deba@2466
   507
    int _phase;
deba@2466
   508
    const Graph *_graph;
deba@2466
   509
deba@2466
   510
    int _size;
deba@2051
   511
  
deba@2051
   512
  };
deba@2051
   513
deba@2058
   514
  /// \ingroup matching
deba@2058
   515
  ///
deba@2058
   516
  /// \brief Maximum cardinality bipartite matching
deba@2058
   517
  ///
deba@2058
   518
  /// This function calculates the maximum cardinality matching
deba@2058
   519
  /// in a bipartite graph. It gives back the matching in an undirected
deba@2058
   520
  /// edge map.
deba@2058
   521
  ///
deba@2058
   522
  /// \param graph The bipartite graph.
deba@2463
   523
  /// \return The size of the matching.
deba@2463
   524
  template <typename BpUGraph>
deba@2463
   525
  int maxBipartiteMatching(const BpUGraph& graph) {
deba@2463
   526
    MaxBipartiteMatching<BpUGraph> bpmatching(graph);
deba@2463
   527
    bpmatching.run();
deba@2463
   528
    return bpmatching.matchingSize();
deba@2463
   529
  }
deba@2463
   530
deba@2463
   531
  /// \ingroup matching
deba@2463
   532
  ///
deba@2463
   533
  /// \brief Maximum cardinality bipartite matching
deba@2463
   534
  ///
deba@2463
   535
  /// This function calculates the maximum cardinality matching
deba@2463
   536
  /// in a bipartite graph. It gives back the matching in an undirected
deba@2463
   537
  /// edge map.
deba@2463
   538
  ///
deba@2463
   539
  /// \param graph The bipartite graph.
deba@2463
   540
  /// \retval matching The ANodeMap of UEdges which will be set to covered
deba@2463
   541
  /// matching undirected edge.
deba@2058
   542
  /// \return The size of the matching.
deba@2058
   543
  template <typename BpUGraph, typename MatchingMap>
deba@2058
   544
  int maxBipartiteMatching(const BpUGraph& graph, MatchingMap& matching) {
deba@2058
   545
    MaxBipartiteMatching<BpUGraph> bpmatching(graph);
deba@2058
   546
    bpmatching.run();
deba@2463
   547
    bpmatching.aMatching(matching);
deba@2463
   548
    return bpmatching.matchingSize();
deba@2463
   549
  }
deba@2463
   550
deba@2463
   551
  /// \ingroup matching
deba@2463
   552
  ///
deba@2463
   553
  /// \brief Maximum cardinality bipartite matching
deba@2463
   554
  ///
deba@2463
   555
  /// This function calculates the maximum cardinality matching
deba@2463
   556
  /// in a bipartite graph. It gives back the matching in an undirected
deba@2463
   557
  /// edge map.
deba@2463
   558
  ///
deba@2463
   559
  /// \param graph The bipartite graph.
deba@2463
   560
  /// \retval matching The ANodeMap of UEdges which will be set to covered
deba@2463
   561
  /// matching undirected edge.
deba@2463
   562
  /// \retval barrier The BNodeMap of bools which will be set to a barrier
deba@2463
   563
  /// of the BNode-set.
deba@2463
   564
  /// \return The size of the matching.
deba@2463
   565
  template <typename BpUGraph, typename MatchingMap, typename BarrierMap>
deba@2463
   566
  int maxBipartiteMatching(const BpUGraph& graph, 
deba@2463
   567
			   MatchingMap& matching, BarrierMap& barrier) {
deba@2463
   568
    MaxBipartiteMatching<BpUGraph> bpmatching(graph);
deba@2463
   569
    bpmatching.run();
deba@2463
   570
    bpmatching.aMatching(matching);
deba@2463
   571
    bpmatching.bBarrier(barrier);
deba@2058
   572
    return bpmatching.matchingSize();
deba@2058
   573
  }
deba@2058
   574
deba@2051
   575
  /// \brief Default traits class for weighted bipartite matching algoritms.
deba@2051
   576
  ///
deba@2051
   577
  /// Default traits class for weighted bipartite matching algoritms.
deba@2051
   578
  /// \param _BpUGraph The bipartite undirected graph type.
deba@2051
   579
  /// \param _WeightMap Type of weight map.
deba@2051
   580
  template <typename _BpUGraph, typename _WeightMap>
deba@2051
   581
  struct WeightedBipartiteMatchingDefaultTraits {
deba@2051
   582
    /// \brief The type of the weight of the undirected edges.
deba@2051
   583
    typedef typename _WeightMap::Value Value;
deba@2051
   584
deba@2051
   585
    /// The undirected bipartite graph type the algorithm runs on. 
deba@2051
   586
    typedef _BpUGraph BpUGraph;
deba@2051
   587
deba@2051
   588
    /// The map of the edges weights
deba@2051
   589
    typedef _WeightMap WeightMap;
deba@2051
   590
deba@2051
   591
    /// \brief The cross reference type used by heap.
deba@2051
   592
    ///
deba@2051
   593
    /// The cross reference type used by heap.
deba@2051
   594
    /// Usually it is \c Graph::NodeMap<int>.
deba@2051
   595
    typedef typename BpUGraph::template NodeMap<int> HeapCrossRef;
deba@2051
   596
deba@2051
   597
    /// \brief Instantiates a HeapCrossRef.
deba@2051
   598
    ///
deba@2051
   599
    /// This function instantiates a \ref HeapCrossRef. 
deba@2051
   600
    /// \param graph is the graph, to which we would like to define the 
deba@2051
   601
    /// HeapCrossRef.
deba@2051
   602
    static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
   603
      return new HeapCrossRef(graph);
deba@2051
   604
    }
deba@2051
   605
    
deba@2051
   606
    /// \brief The heap type used by weighted matching algorithms.
deba@2051
   607
    ///
deba@2051
   608
    /// The heap type used by weighted matching algorithms. It should
deba@2051
   609
    /// minimize the priorities and the heap's key type is the graph's
deba@2051
   610
    /// anode graph's node.
deba@2051
   611
    ///
deba@2051
   612
    /// \sa BinHeap
mqrelly@2263
   613
    typedef BinHeap<Value, HeapCrossRef> Heap;
deba@2051
   614
    
deba@2051
   615
    /// \brief Instantiates a Heap.
deba@2051
   616
    ///
deba@2051
   617
    /// This function instantiates a \ref Heap. 
deba@2051
   618
    /// \param crossref The cross reference of the heap.
deba@2051
   619
    static Heap *createHeap(HeapCrossRef& crossref) {
deba@2051
   620
      return new Heap(crossref);
deba@2051
   621
    }
deba@2051
   622
deba@2051
   623
  };
deba@2051
   624
deba@2051
   625
deba@2051
   626
  /// \ingroup matching
deba@2051
   627
  ///
deba@2051
   628
  /// \brief Bipartite Max Weighted Matching algorithm
deba@2051
   629
  ///
deba@2051
   630
  /// This class implements the bipartite Max Weighted Matching
deba@2051
   631
  /// algorithm.  It uses the successive shortest path algorithm to
deba@2051
   632
  /// calculate the maximum weighted matching in the bipartite
deba@2051
   633
  /// graph. The algorithm can be used also to calculate the maximum
deba@2051
   634
  /// cardinality maximum weighted matching. The time complexity
deba@2051
   635
  /// of the algorithm is \f$ O(ne\log(n)) \f$ with the default binary
deba@2051
   636
  /// heap implementation but this can be improved to 
deba@2051
   637
  /// \f$ O(n^2\log(n)+ne) \f$ if we use fibonacci heaps.
deba@2051
   638
  ///
deba@2051
   639
  /// The algorithm also provides a potential function on the nodes
deba@2051
   640
  /// which a dual solution of the matching algorithm and it can be
deba@2051
   641
  /// used to proof the optimality of the given pimal solution.
deba@2051
   642
#ifdef DOXYGEN
deba@2051
   643
  template <typename _BpUGraph, typename _WeightMap, typename _Traits>
deba@2051
   644
#else
deba@2051
   645
  template <typename _BpUGraph, 
deba@2051
   646
            typename _WeightMap = typename _BpUGraph::template UEdgeMap<int>,
deba@2051
   647
            typename _Traits = WeightedBipartiteMatchingDefaultTraits<_BpUGraph, _WeightMap> >
deba@2051
   648
#endif
deba@2051
   649
  class MaxWeightedBipartiteMatching {
deba@2051
   650
  public:
deba@2051
   651
deba@2051
   652
    typedef _Traits Traits;
deba@2051
   653
    typedef typename Traits::BpUGraph BpUGraph;
deba@2051
   654
    typedef typename Traits::WeightMap WeightMap;
deba@2051
   655
    typedef typename Traits::Value Value;
deba@2051
   656
deba@2051
   657
  protected:
deba@2051
   658
deba@2051
   659
    typedef typename Traits::HeapCrossRef HeapCrossRef;
deba@2051
   660
    typedef typename Traits::Heap Heap; 
deba@2051
   661
deba@2051
   662
    
deba@2051
   663
    typedef typename BpUGraph::Node Node;
deba@2051
   664
    typedef typename BpUGraph::ANodeIt ANodeIt;
deba@2051
   665
    typedef typename BpUGraph::BNodeIt BNodeIt;
deba@2051
   666
    typedef typename BpUGraph::UEdge UEdge;
deba@2051
   667
    typedef typename BpUGraph::UEdgeIt UEdgeIt;
deba@2051
   668
    typedef typename BpUGraph::IncEdgeIt IncEdgeIt;
deba@2051
   669
deba@2051
   670
    typedef typename BpUGraph::template ANodeMap<UEdge> ANodeMatchingMap;
deba@2051
   671
    typedef typename BpUGraph::template BNodeMap<UEdge> BNodeMatchingMap;
deba@2051
   672
deba@2051
   673
    typedef typename BpUGraph::template ANodeMap<Value> ANodePotentialMap;
deba@2051
   674
    typedef typename BpUGraph::template BNodeMap<Value> BNodePotentialMap;
deba@2051
   675
deba@2051
   676
deba@2051
   677
  public:
deba@2051
   678
deba@2051
   679
    /// \brief \ref Exception for uninitialized parameters.
deba@2051
   680
    ///
deba@2051
   681
    /// This error represents problems in the initialization
deba@2051
   682
    /// of the parameters of the algorithms.
deba@2051
   683
    class UninitializedParameter : public lemon::UninitializedParameter {
deba@2051
   684
    public:
alpar@2151
   685
      virtual const char* what() const throw() {
deba@2051
   686
	return "lemon::MaxWeightedBipartiteMatching::UninitializedParameter";
deba@2051
   687
      }
deba@2051
   688
    };
deba@2051
   689
deba@2051
   690
    ///\name Named template parameters
deba@2051
   691
deba@2051
   692
    ///@{
deba@2051
   693
deba@2051
   694
    template <class H, class CR>
deba@2051
   695
    struct DefHeapTraits : public Traits {
deba@2051
   696
      typedef CR HeapCrossRef;
deba@2051
   697
      typedef H Heap;
deba@2051
   698
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &) {
deba@2051
   699
	throw UninitializedParameter();
deba@2051
   700
      }
deba@2051
   701
      static Heap *createHeap(HeapCrossRef &) {
deba@2051
   702
	throw UninitializedParameter();
deba@2051
   703
      }
deba@2051
   704
    };
deba@2051
   705
deba@2051
   706
    /// \brief \ref named-templ-param "Named parameter" for setting heap 
deba@2051
   707
    /// and cross reference type
deba@2051
   708
    ///
deba@2051
   709
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
   710
    /// reference type
deba@2051
   711
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
   712
    struct DefHeap
deba@2051
   713
      : public MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   714
                                            DefHeapTraits<H, CR> > { 
deba@2051
   715
      typedef MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   716
                                           DefHeapTraits<H, CR> > Create;
deba@2051
   717
    };
deba@2051
   718
deba@2051
   719
    template <class H, class CR>
deba@2051
   720
    struct DefStandardHeapTraits : public Traits {
deba@2051
   721
      typedef CR HeapCrossRef;
deba@2051
   722
      typedef H Heap;
deba@2051
   723
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
   724
	return new HeapCrossRef(graph);
deba@2051
   725
      }
deba@2051
   726
      static Heap *createHeap(HeapCrossRef &crossref) {
deba@2051
   727
	return new Heap(crossref);
deba@2051
   728
      }
deba@2051
   729
    };
deba@2051
   730
deba@2051
   731
    /// \brief \ref named-templ-param "Named parameter" for setting heap and 
deba@2051
   732
    /// cross reference type with automatic allocation
deba@2051
   733
    ///
deba@2051
   734
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
   735
    /// reference type. It can allocate the heap and the cross reference 
deba@2051
   736
    /// object if the cross reference's constructor waits for the graph as 
deba@2051
   737
    /// parameter and the heap's constructor waits for the cross reference.
deba@2051
   738
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
   739
    struct DefStandardHeap
deba@2051
   740
      : public MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   741
                                            DefStandardHeapTraits<H, CR> > { 
deba@2051
   742
      typedef MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   743
                                           DefStandardHeapTraits<H, CR> > 
deba@2051
   744
      Create;
deba@2051
   745
    };
deba@2051
   746
deba@2051
   747
    ///@}
deba@2051
   748
deba@2051
   749
deba@2051
   750
    /// \brief Constructor.
deba@2051
   751
    ///
deba@2051
   752
    /// Constructor of the algorithm. 
deba@2051
   753
    MaxWeightedBipartiteMatching(const BpUGraph& _graph, 
deba@2051
   754
                                 const WeightMap& _weight) 
deba@2051
   755
      : graph(&_graph), weight(&_weight),
deba@2051
   756
        anode_matching(_graph), bnode_matching(_graph),
deba@2051
   757
        anode_potential(_graph), bnode_potential(_graph),
deba@2051
   758
        _heap_cross_ref(0), local_heap_cross_ref(false),
deba@2051
   759
        _heap(0), local_heap(0) {}
deba@2051
   760
deba@2051
   761
    /// \brief Destructor.
deba@2051
   762
    ///
deba@2051
   763
    /// Destructor of the algorithm.
deba@2051
   764
    ~MaxWeightedBipartiteMatching() {
deba@2051
   765
      destroyStructures();
deba@2051
   766
    }
deba@2051
   767
deba@2051
   768
    /// \brief Sets the heap and the cross reference used by algorithm.
deba@2051
   769
    ///
deba@2051
   770
    /// Sets the heap and the cross reference used by algorithm.
deba@2051
   771
    /// If you don't use this function before calling \ref run(),
deba@2051
   772
    /// it will allocate one. The destuctor deallocates this
deba@2051
   773
    /// automatically allocated map, of course.
deba@2051
   774
    /// \return \c (*this)
deba@2386
   775
    MaxWeightedBipartiteMatching& heap(Heap& hp, HeapCrossRef &cr) {
deba@2051
   776
      if(local_heap_cross_ref) {
deba@2051
   777
	delete _heap_cross_ref;
deba@2051
   778
	local_heap_cross_ref = false;
deba@2051
   779
      }
deba@2386
   780
      _heap_cross_ref = &cr;
deba@2051
   781
      if(local_heap) {
deba@2051
   782
	delete _heap;
deba@2051
   783
	local_heap = false;
deba@2051
   784
      }
deba@2386
   785
      _heap = &hp;
deba@2051
   786
      return *this;
deba@2051
   787
    }
deba@2051
   788
deba@2051
   789
    /// \name Execution control
deba@2051
   790
    /// The simplest way to execute the algorithm is to use
deba@2051
   791
    /// one of the member functions called \c run().
deba@2051
   792
    /// \n
deba@2051
   793
    /// If you need more control on the execution,
deba@2051
   794
    /// first you must call \ref init() or one alternative for it.
deba@2051
   795
    /// Finally \ref start() will perform the matching computation or
deba@2051
   796
    /// with step-by-step execution you can augment the solution.
deba@2051
   797
deba@2051
   798
    /// @{
deba@2051
   799
deba@2051
   800
    /// \brief Initalize the data structures.
deba@2051
   801
    ///
deba@2051
   802
    /// It initalizes the data structures and creates an empty matching.
deba@2051
   803
    void init() {
deba@2051
   804
      initStructures();
deba@2051
   805
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   806
        anode_matching[it] = INVALID;
deba@2051
   807
        anode_potential[it] = 0;
deba@2051
   808
      }
deba@2051
   809
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   810
        bnode_matching[it] = INVALID;
deba@2051
   811
        bnode_potential[it] = 0;
deba@2051
   812
        for (IncEdgeIt jt(*graph, it); jt != INVALID; ++jt) {
deba@2058
   813
          if ((*weight)[jt] > bnode_potential[it]) {
deba@2058
   814
            bnode_potential[it] = (*weight)[jt];
deba@2051
   815
          }
deba@2051
   816
        }
deba@2051
   817
      }
deba@2051
   818
      matching_value = 0;
deba@2051
   819
      matching_size = 0;
deba@2051
   820
    }
deba@2051
   821
deba@2051
   822
deba@2051
   823
    /// \brief An augmenting phase of the weighted matching algorithm
deba@2051
   824
    ///
deba@2051
   825
    /// It runs an augmenting phase of the weighted matching 
alpar@2352
   826
    /// algorithm. This phase finds the best augmenting path and 
deba@2051
   827
    /// augments only on this paths. 
deba@2051
   828
    ///
deba@2051
   829
    /// The algorithm consists at most 
deba@2051
   830
    /// of \f$ O(n) \f$ phase and one phase is \f$ O(n\log(n)+e) \f$ 
deba@2051
   831
    /// long with Fibonacci heap or \f$ O((n+e)\log(n)) \f$ long 
deba@2051
   832
    /// with binary heap.
deba@2051
   833
    /// \param decrease If the given parameter true the matching value
deba@2051
   834
    /// can be decreased in the augmenting phase. If we would like
deba@2051
   835
    /// to calculate the maximum cardinality maximum weighted matching
deba@2051
   836
    /// then we should let the algorithm to decrease the matching
deba@2051
   837
    /// value in order to increase the number of the matching edges.
deba@2051
   838
    bool augment(bool decrease = false) {
deba@2051
   839
deba@2051
   840
      typename BpUGraph::template BNodeMap<Value> bdist(*graph);
deba@2051
   841
      typename BpUGraph::template BNodeMap<UEdge> bpred(*graph, INVALID);
deba@2051
   842
deba@2051
   843
      Node bestNode = INVALID;
deba@2051
   844
      Value bestValue = 0;
deba@2051
   845
deba@2051
   846
      _heap->clear();
deba@2051
   847
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   848
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
deba@2051
   849
      }
deba@2051
   850
deba@2051
   851
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   852
        if (anode_matching[it] == INVALID) {
deba@2051
   853
          _heap->push(it, 0);
deba@2051
   854
        }
deba@2051
   855
      }
deba@2051
   856
deba@2051
   857
      Value bdistMax = 0;
deba@2051
   858
      while (!_heap->empty()) {
deba@2051
   859
        Node anode = _heap->top();
deba@2051
   860
        Value avalue = _heap->prio();
deba@2051
   861
        _heap->pop();
deba@2051
   862
        for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2051
   863
          if (jt == anode_matching[anode]) continue;
deba@2051
   864
          Node bnode = graph->bNode(jt);
deba@2058
   865
          Value bvalue = avalue  - (*weight)[jt] +
deba@2058
   866
            anode_potential[anode] + bnode_potential[bnode];
deba@2051
   867
          if (bpred[bnode] == INVALID || bvalue < bdist[bnode]) {
deba@2051
   868
            bdist[bnode] = bvalue;
deba@2051
   869
            bpred[bnode] = jt;
deba@2051
   870
          }
deba@2051
   871
          if (bvalue > bdistMax) {
deba@2051
   872
            bdistMax = bvalue;
deba@2051
   873
          }
deba@2051
   874
          if (bnode_matching[bnode] != INVALID) {
deba@2051
   875
            Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2051
   876
            switch (_heap->state(newanode)) {
deba@2051
   877
            case Heap::PRE_HEAP:
deba@2051
   878
              _heap->push(newanode, bvalue);
deba@2051
   879
              break;
deba@2051
   880
            case Heap::IN_HEAP:
deba@2051
   881
              if (bvalue < (*_heap)[newanode]) {
deba@2051
   882
                _heap->decrease(newanode, bvalue);
deba@2051
   883
              }
deba@2051
   884
              break;
deba@2051
   885
            case Heap::POST_HEAP:
deba@2051
   886
              break;
deba@2051
   887
            }
deba@2051
   888
          } else {
deba@2051
   889
            if (bestNode == INVALID || 
deba@2058
   890
                bnode_potential[bnode] - bvalue > bestValue) {
deba@2058
   891
              bestValue = bnode_potential[bnode] - bvalue;
deba@2051
   892
              bestNode = bnode;
deba@2051
   893
            }
deba@2051
   894
          }
deba@2051
   895
        }
deba@2051
   896
      }
deba@2051
   897
deba@2051
   898
      if (bestNode == INVALID || (!decrease && bestValue < 0)) {
deba@2051
   899
        return false;
deba@2051
   900
      }
deba@2051
   901
deba@2051
   902
      matching_value += bestValue;
deba@2051
   903
      ++matching_size;
deba@2051
   904
deba@2051
   905
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   906
        if (bpred[it] != INVALID) {
deba@2058
   907
          bnode_potential[it] -= bdist[it];
deba@2051
   908
        } else {
deba@2058
   909
          bnode_potential[it] -= bdistMax;
deba@2051
   910
        }
deba@2051
   911
      }
deba@2051
   912
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   913
        if (anode_matching[it] != INVALID) {
deba@2051
   914
          Node bnode = graph->bNode(anode_matching[it]);
deba@2051
   915
          if (bpred[bnode] != INVALID) {
deba@2051
   916
            anode_potential[it] += bdist[bnode];
deba@2051
   917
          } else {
deba@2051
   918
            anode_potential[it] += bdistMax;
deba@2051
   919
          }
deba@2051
   920
        }
deba@2051
   921
      }
deba@2051
   922
deba@2051
   923
      while (bestNode != INVALID) {
deba@2051
   924
        UEdge uedge = bpred[bestNode];
deba@2051
   925
        Node anode = graph->aNode(uedge);
deba@2051
   926
        
deba@2051
   927
        bnode_matching[bestNode] = uedge;
deba@2051
   928
        if (anode_matching[anode] != INVALID) {
deba@2051
   929
          bestNode = graph->bNode(anode_matching[anode]);
deba@2051
   930
        } else {
deba@2051
   931
          bestNode = INVALID;
deba@2051
   932
        }
deba@2051
   933
        anode_matching[anode] = uedge;
deba@2051
   934
      }
deba@2051
   935
deba@2051
   936
deba@2051
   937
      return true;
deba@2051
   938
    }
deba@2051
   939
deba@2051
   940
    /// \brief Starts the algorithm.
deba@2051
   941
    ///
deba@2051
   942
    /// Starts the algorithm. It runs augmenting phases until the
deba@2051
   943
    /// optimal solution reached.
deba@2051
   944
    ///
deba@2051
   945
    /// \param maxCardinality If the given value is true it will
deba@2051
   946
    /// calculate the maximum cardinality maximum matching instead of
deba@2051
   947
    /// the maximum matching.
deba@2051
   948
    void start(bool maxCardinality = false) {
deba@2051
   949
      while (augment(maxCardinality)) {}
deba@2051
   950
    }
deba@2051
   951
deba@2051
   952
    /// \brief Runs the algorithm.
deba@2051
   953
    ///
deba@2051
   954
    /// It just initalize the algorithm and then start it.
deba@2051
   955
    ///
deba@2051
   956
    /// \param maxCardinality If the given value is true it will
deba@2051
   957
    /// calculate the maximum cardinality maximum matching instead of
deba@2051
   958
    /// the maximum matching.
deba@2051
   959
    void run(bool maxCardinality = false) {
deba@2051
   960
      init();
deba@2051
   961
      start(maxCardinality);
deba@2051
   962
    }
deba@2051
   963
deba@2051
   964
    /// @}
deba@2051
   965
deba@2051
   966
    /// \name Query Functions
deba@2051
   967
    /// The result of the %Matching algorithm can be obtained using these
deba@2051
   968
    /// functions.\n
deba@2051
   969
    /// Before the use of these functions,
deba@2051
   970
    /// either run() or start() must be called.
deba@2051
   971
    
deba@2051
   972
    ///@{
deba@2051
   973
deba@2051
   974
    /// \brief Gives back the potential in the NodeMap
deba@2051
   975
    ///
deba@2058
   976
    /// Gives back the potential in the NodeMap. The matching is optimal
deba@2058
   977
    /// with the current number of edges if \f$ \pi(a) + \pi(b) - w(ab) = 0 \f$
deba@2058
   978
    /// for each matching edges and \f$ \pi(a) + \pi(b) - w(ab) \ge 0 \f$
deba@2058
   979
    /// for each edges. 
deba@2051
   980
    template <typename PotentialMap>
deba@2386
   981
    void potential(PotentialMap& pt) const {
deba@2051
   982
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2463
   983
        pt.set(it, anode_potential[it]);
deba@2051
   984
      }
deba@2051
   985
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2463
   986
        pt.set(it, bnode_potential[it]);
deba@2051
   987
      }
deba@2051
   988
    }
deba@2051
   989
deba@2051
   990
    /// \brief Set true all matching uedge in the map.
deba@2051
   991
    /// 
deba@2051
   992
    /// Set true all matching uedge in the map. It does not change the
deba@2051
   993
    /// value mapped to the other uedges.
deba@2051
   994
    /// \return The number of the matching edges.
deba@2051
   995
    template <typename MatchingMap>
deba@2386
   996
    int quickMatching(MatchingMap& mm) const {
deba@2051
   997
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   998
        if (anode_matching[it] != INVALID) {
deba@2463
   999
          mm.set(anode_matching[it], true);
deba@2051
  1000
        }
deba@2051
  1001
      }
deba@2051
  1002
      return matching_size;
deba@2051
  1003
    }
deba@2051
  1004
deba@2051
  1005
    /// \brief Set true all matching uedge in the map and the others to false.
deba@2051
  1006
    /// 
deba@2051
  1007
    /// Set true all matching uedge in the map and the others to false.
deba@2051
  1008
    /// \return The number of the matching edges.
deba@2051
  1009
    template <typename MatchingMap>
deba@2386
  1010
    int matching(MatchingMap& mm) const {
deba@2051
  1011
      for (UEdgeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1012
        mm.set(it, it == anode_matching[graph->aNode(it)]);
deba@2463
  1013
      }
deba@2463
  1014
      return matching_size;
deba@2463
  1015
    }
deba@2463
  1016
deba@2463
  1017
    ///Gives back the matching in an ANodeMap.
deba@2463
  1018
deba@2463
  1019
    ///Gives back the matching in an ANodeMap. The parameter should
deba@2463
  1020
    ///be a write ANodeMap of UEdge values.
deba@2463
  1021
    ///\return The number of the matching edges.
deba@2463
  1022
    template<class MatchingMap>
deba@2463
  1023
    int aMatching(MatchingMap& mm) const {
deba@2463
  1024
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1025
        mm.set(it, anode_matching[it]);
deba@2463
  1026
      }
deba@2463
  1027
      return matching_size;
deba@2463
  1028
    }
deba@2463
  1029
deba@2463
  1030
    ///Gives back the matching in a BNodeMap.
deba@2463
  1031
deba@2463
  1032
    ///Gives back the matching in a BNodeMap. The parameter should
deba@2463
  1033
    ///be a write BNodeMap of UEdge values.
deba@2463
  1034
    ///\return The number of the matching edges.
deba@2463
  1035
    template<class MatchingMap>
deba@2463
  1036
    int bMatching(MatchingMap& mm) const {
deba@2463
  1037
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1038
        mm.set(it, bnode_matching[it]);
deba@2051
  1039
      }
deba@2051
  1040
      return matching_size;
deba@2051
  1041
    }
deba@2051
  1042
deba@2051
  1043
deba@2051
  1044
    /// \brief Return true if the given uedge is in the matching.
deba@2051
  1045
    /// 
deba@2051
  1046
    /// It returns true if the given uedge is in the matching.
deba@2058
  1047
    bool matchingEdge(const UEdge& edge) const {
deba@2051
  1048
      return anode_matching[graph->aNode(edge)] == edge;
deba@2051
  1049
    }
deba@2051
  1050
deba@2051
  1051
    /// \brief Returns the matching edge from the node.
deba@2051
  1052
    /// 
deba@2051
  1053
    /// Returns the matching edge from the node. If there is not such
deba@2051
  1054
    /// edge it gives back \c INVALID.
deba@2058
  1055
    UEdge matchingEdge(const Node& node) const {
deba@2051
  1056
      if (graph->aNode(node)) {
deba@2051
  1057
        return anode_matching[node];
deba@2051
  1058
      } else {
deba@2051
  1059
        return bnode_matching[node];
deba@2051
  1060
      }
deba@2051
  1061
    }
deba@2051
  1062
deba@2051
  1063
    /// \brief Gives back the sum of weights of the matching edges.
deba@2051
  1064
    ///
deba@2051
  1065
    /// Gives back the sum of weights of the matching edges.
deba@2051
  1066
    Value matchingValue() const {
deba@2051
  1067
      return matching_value;
deba@2051
  1068
    }
deba@2051
  1069
deba@2051
  1070
    /// \brief Gives back the number of the matching edges.
deba@2051
  1071
    ///
deba@2051
  1072
    /// Gives back the number of the matching edges.
deba@2051
  1073
    int matchingSize() const {
deba@2051
  1074
      return matching_size;
deba@2051
  1075
    }
deba@2051
  1076
deba@2051
  1077
    /// @}
deba@2051
  1078
deba@2051
  1079
  private:
deba@2051
  1080
deba@2051
  1081
    void initStructures() {
deba@2051
  1082
      if (!_heap_cross_ref) {
deba@2051
  1083
	local_heap_cross_ref = true;
deba@2051
  1084
	_heap_cross_ref = Traits::createHeapCrossRef(*graph);
deba@2051
  1085
      }
deba@2051
  1086
      if (!_heap) {
deba@2051
  1087
	local_heap = true;
deba@2051
  1088
	_heap = Traits::createHeap(*_heap_cross_ref);
deba@2051
  1089
      }
deba@2051
  1090
    }
deba@2051
  1091
deba@2051
  1092
    void destroyStructures() {
deba@2051
  1093
      if (local_heap_cross_ref) delete _heap_cross_ref;
deba@2051
  1094
      if (local_heap) delete _heap;
deba@2051
  1095
    }
deba@2051
  1096
deba@2051
  1097
deba@2051
  1098
  private:
deba@2051
  1099
    
deba@2051
  1100
    const BpUGraph *graph;
deba@2051
  1101
    const WeightMap* weight;
deba@2051
  1102
deba@2051
  1103
    ANodeMatchingMap anode_matching;
deba@2051
  1104
    BNodeMatchingMap bnode_matching;
deba@2051
  1105
deba@2051
  1106
    ANodePotentialMap anode_potential;
deba@2051
  1107
    BNodePotentialMap bnode_potential;
deba@2051
  1108
deba@2051
  1109
    Value matching_value;
deba@2051
  1110
    int matching_size;
deba@2051
  1111
deba@2051
  1112
    HeapCrossRef *_heap_cross_ref;
deba@2051
  1113
    bool local_heap_cross_ref;
deba@2051
  1114
deba@2051
  1115
    Heap *_heap;
deba@2051
  1116
    bool local_heap;
deba@2051
  1117
  
deba@2051
  1118
  };
deba@2051
  1119
deba@2058
  1120
  /// \ingroup matching
deba@2058
  1121
  ///
deba@2058
  1122
  /// \brief Maximum weighted bipartite matching
deba@2058
  1123
  ///
deba@2058
  1124
  /// This function calculates the maximum weighted matching
deba@2058
  1125
  /// in a bipartite graph. It gives back the matching in an undirected
deba@2058
  1126
  /// edge map.
deba@2058
  1127
  ///
deba@2058
  1128
  /// \param graph The bipartite graph.
deba@2058
  1129
  /// \param weight The undirected edge map which contains the weights.
deba@2058
  1130
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1131
  /// the matching.
deba@2058
  1132
  /// \return The value of the matching.
deba@2058
  1133
  template <typename BpUGraph, typename WeightMap, typename MatchingMap>
deba@2058
  1134
  typename WeightMap::Value 
deba@2058
  1135
  maxWeightedBipartiteMatching(const BpUGraph& graph, const WeightMap& weight,
deba@2058
  1136
                               MatchingMap& matching) {
deba@2058
  1137
    MaxWeightedBipartiteMatching<BpUGraph, WeightMap> 
deba@2058
  1138
      bpmatching(graph, weight);
deba@2058
  1139
    bpmatching.run();
deba@2058
  1140
    bpmatching.matching(matching);
deba@2058
  1141
    return bpmatching.matchingValue();
deba@2058
  1142
  }
deba@2058
  1143
deba@2058
  1144
  /// \ingroup matching
deba@2058
  1145
  ///
deba@2058
  1146
  /// \brief Maximum weighted maximum cardinality bipartite matching
deba@2058
  1147
  ///
deba@2058
  1148
  /// This function calculates the maximum weighted of the maximum cardinality
deba@2058
  1149
  /// matchings of a bipartite graph. It gives back the matching in an 
deba@2058
  1150
  /// undirected edge map.
deba@2058
  1151
  ///
deba@2058
  1152
  /// \param graph The bipartite graph.
deba@2058
  1153
  /// \param weight The undirected edge map which contains the weights.
deba@2058
  1154
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1155
  /// the matching.
deba@2058
  1156
  /// \return The value of the matching.
deba@2058
  1157
  template <typename BpUGraph, typename WeightMap, typename MatchingMap>
deba@2058
  1158
  typename WeightMap::Value 
deba@2058
  1159
  maxWeightedMaxBipartiteMatching(const BpUGraph& graph, 
deba@2058
  1160
                                  const WeightMap& weight,
deba@2058
  1161
                                  MatchingMap& matching) {
deba@2058
  1162
    MaxWeightedBipartiteMatching<BpUGraph, WeightMap> 
deba@2058
  1163
      bpmatching(graph, weight);
deba@2058
  1164
    bpmatching.run(true);
deba@2058
  1165
    bpmatching.matching(matching);
deba@2058
  1166
    return bpmatching.matchingValue();
deba@2058
  1167
  }
deba@2058
  1168
deba@2051
  1169
  /// \brief Default traits class for minimum cost bipartite matching
deba@2051
  1170
  /// algoritms.
deba@2051
  1171
  ///
deba@2051
  1172
  /// Default traits class for minimum cost bipartite matching
deba@2051
  1173
  /// algoritms.  
deba@2051
  1174
  ///
deba@2051
  1175
  /// \param _BpUGraph The bipartite undirected graph
deba@2051
  1176
  /// type.  
deba@2051
  1177
  ///
deba@2051
  1178
  /// \param _CostMap Type of cost map.
deba@2051
  1179
  template <typename _BpUGraph, typename _CostMap>
deba@2051
  1180
  struct MinCostMaxBipartiteMatchingDefaultTraits {
deba@2051
  1181
    /// \brief The type of the cost of the undirected edges.
deba@2051
  1182
    typedef typename _CostMap::Value Value;
deba@2051
  1183
deba@2051
  1184
    /// The undirected bipartite graph type the algorithm runs on. 
deba@2051
  1185
    typedef _BpUGraph BpUGraph;
deba@2051
  1186
deba@2051
  1187
    /// The map of the edges costs
deba@2051
  1188
    typedef _CostMap CostMap;
deba@2051
  1189
deba@2051
  1190
    /// \brief The cross reference type used by heap.
deba@2051
  1191
    ///
deba@2051
  1192
    /// The cross reference type used by heap.
deba@2051
  1193
    /// Usually it is \c Graph::NodeMap<int>.
deba@2051
  1194
    typedef typename BpUGraph::template NodeMap<int> HeapCrossRef;
deba@2051
  1195
deba@2051
  1196
    /// \brief Instantiates a HeapCrossRef.
deba@2051
  1197
    ///
deba@2051
  1198
    /// This function instantiates a \ref HeapCrossRef. 
deba@2051
  1199
    /// \param graph is the graph, to which we would like to define the 
deba@2051
  1200
    /// HeapCrossRef.
deba@2051
  1201
    static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
  1202
      return new HeapCrossRef(graph);
deba@2051
  1203
    }
deba@2051
  1204
    
deba@2051
  1205
    /// \brief The heap type used by costed matching algorithms.
deba@2051
  1206
    ///
deba@2051
  1207
    /// The heap type used by costed matching algorithms. It should
deba@2051
  1208
    /// minimize the priorities and the heap's key type is the graph's
deba@2051
  1209
    /// anode graph's node.
deba@2051
  1210
    ///
deba@2051
  1211
    /// \sa BinHeap
deba@2269
  1212
    typedef BinHeap<Value, HeapCrossRef> Heap;
deba@2051
  1213
    
deba@2051
  1214
    /// \brief Instantiates a Heap.
deba@2051
  1215
    ///
deba@2051
  1216
    /// This function instantiates a \ref Heap. 
deba@2051
  1217
    /// \param crossref The cross reference of the heap.
deba@2051
  1218
    static Heap *createHeap(HeapCrossRef& crossref) {
deba@2051
  1219
      return new Heap(crossref);
deba@2051
  1220
    }
deba@2051
  1221
deba@2051
  1222
  };
deba@2051
  1223
deba@2051
  1224
deba@2051
  1225
  /// \ingroup matching
deba@2051
  1226
  ///
deba@2051
  1227
  /// \brief Bipartite Min Cost Matching algorithm
deba@2051
  1228
  ///
deba@2051
  1229
  /// This class implements the bipartite Min Cost Matching algorithm.
deba@2051
  1230
  /// It uses the successive shortest path algorithm to calculate the
deba@2051
  1231
  /// minimum cost maximum matching in the bipartite graph. The time
deba@2051
  1232
  /// complexity of the algorithm is \f$ O(ne\log(n)) \f$ with the
deba@2051
  1233
  /// default binary heap implementation but this can be improved to
deba@2051
  1234
  /// \f$ O(n^2\log(n)+ne) \f$ if we use fibonacci heaps.
deba@2051
  1235
  ///
deba@2051
  1236
  /// The algorithm also provides a potential function on the nodes
deba@2051
  1237
  /// which a dual solution of the matching algorithm and it can be
deba@2051
  1238
  /// used to proof the optimality of the given pimal solution.
deba@2051
  1239
#ifdef DOXYGEN
deba@2051
  1240
  template <typename _BpUGraph, typename _CostMap, typename _Traits>
deba@2051
  1241
#else
deba@2051
  1242
  template <typename _BpUGraph, 
deba@2051
  1243
            typename _CostMap = typename _BpUGraph::template UEdgeMap<int>,
deba@2051
  1244
            typename _Traits = MinCostMaxBipartiteMatchingDefaultTraits<_BpUGraph, _CostMap> >
deba@2051
  1245
#endif
deba@2051
  1246
  class MinCostMaxBipartiteMatching {
deba@2051
  1247
  public:
deba@2051
  1248
deba@2051
  1249
    typedef _Traits Traits;
deba@2051
  1250
    typedef typename Traits::BpUGraph BpUGraph;
deba@2051
  1251
    typedef typename Traits::CostMap CostMap;
deba@2051
  1252
    typedef typename Traits::Value Value;
deba@2051
  1253
deba@2051
  1254
  protected:
deba@2051
  1255
deba@2051
  1256
    typedef typename Traits::HeapCrossRef HeapCrossRef;
deba@2051
  1257
    typedef typename Traits::Heap Heap; 
deba@2051
  1258
deba@2051
  1259
    
deba@2051
  1260
    typedef typename BpUGraph::Node Node;
deba@2051
  1261
    typedef typename BpUGraph::ANodeIt ANodeIt;
deba@2051
  1262
    typedef typename BpUGraph::BNodeIt BNodeIt;
deba@2051
  1263
    typedef typename BpUGraph::UEdge UEdge;
deba@2051
  1264
    typedef typename BpUGraph::UEdgeIt UEdgeIt;
deba@2051
  1265
    typedef typename BpUGraph::IncEdgeIt IncEdgeIt;
deba@2051
  1266
deba@2051
  1267
    typedef typename BpUGraph::template ANodeMap<UEdge> ANodeMatchingMap;
deba@2051
  1268
    typedef typename BpUGraph::template BNodeMap<UEdge> BNodeMatchingMap;
deba@2051
  1269
deba@2051
  1270
    typedef typename BpUGraph::template ANodeMap<Value> ANodePotentialMap;
deba@2051
  1271
    typedef typename BpUGraph::template BNodeMap<Value> BNodePotentialMap;
deba@2051
  1272
deba@2051
  1273
deba@2051
  1274
  public:
deba@2051
  1275
deba@2051
  1276
    /// \brief \ref Exception for uninitialized parameters.
deba@2051
  1277
    ///
deba@2051
  1278
    /// This error represents problems in the initialization
deba@2051
  1279
    /// of the parameters of the algorithms.
deba@2051
  1280
    class UninitializedParameter : public lemon::UninitializedParameter {
deba@2051
  1281
    public:
alpar@2151
  1282
      virtual const char* what() const throw() {
deba@2051
  1283
	return "lemon::MinCostMaxBipartiteMatching::UninitializedParameter";
deba@2051
  1284
      }
deba@2051
  1285
    };
deba@2051
  1286
deba@2051
  1287
    ///\name Named template parameters
deba@2051
  1288
deba@2051
  1289
    ///@{
deba@2051
  1290
deba@2051
  1291
    template <class H, class CR>
deba@2051
  1292
    struct DefHeapTraits : public Traits {
deba@2051
  1293
      typedef CR HeapCrossRef;
deba@2051
  1294
      typedef H Heap;
deba@2051
  1295
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &) {
deba@2051
  1296
	throw UninitializedParameter();
deba@2051
  1297
      }
deba@2051
  1298
      static Heap *createHeap(HeapCrossRef &) {
deba@2051
  1299
	throw UninitializedParameter();
deba@2051
  1300
      }
deba@2051
  1301
    };
deba@2051
  1302
deba@2051
  1303
    /// \brief \ref named-templ-param "Named parameter" for setting heap 
deba@2051
  1304
    /// and cross reference type
deba@2051
  1305
    ///
deba@2051
  1306
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
  1307
    /// reference type
deba@2051
  1308
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
  1309
    struct DefHeap
deba@2051
  1310
      : public MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1311
                                            DefHeapTraits<H, CR> > { 
deba@2051
  1312
      typedef MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1313
                                           DefHeapTraits<H, CR> > Create;
deba@2051
  1314
    };
deba@2051
  1315
deba@2051
  1316
    template <class H, class CR>
deba@2051
  1317
    struct DefStandardHeapTraits : public Traits {
deba@2051
  1318
      typedef CR HeapCrossRef;
deba@2051
  1319
      typedef H Heap;
deba@2051
  1320
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
  1321
	return new HeapCrossRef(graph);
deba@2051
  1322
      }
deba@2051
  1323
      static Heap *createHeap(HeapCrossRef &crossref) {
deba@2051
  1324
	return new Heap(crossref);
deba@2051
  1325
      }
deba@2051
  1326
    };
deba@2051
  1327
deba@2051
  1328
    /// \brief \ref named-templ-param "Named parameter" for setting heap and 
deba@2051
  1329
    /// cross reference type with automatic allocation
deba@2051
  1330
    ///
deba@2051
  1331
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
  1332
    /// reference type. It can allocate the heap and the cross reference 
deba@2051
  1333
    /// object if the cross reference's constructor waits for the graph as 
deba@2051
  1334
    /// parameter and the heap's constructor waits for the cross reference.
deba@2051
  1335
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
  1336
    struct DefStandardHeap
deba@2051
  1337
      : public MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1338
                                            DefStandardHeapTraits<H, CR> > { 
deba@2051
  1339
      typedef MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1340
                                           DefStandardHeapTraits<H, CR> > 
deba@2051
  1341
      Create;
deba@2051
  1342
    };
deba@2051
  1343
deba@2051
  1344
    ///@}
deba@2051
  1345
deba@2051
  1346
deba@2051
  1347
    /// \brief Constructor.
deba@2051
  1348
    ///
deba@2051
  1349
    /// Constructor of the algorithm. 
deba@2051
  1350
    MinCostMaxBipartiteMatching(const BpUGraph& _graph, 
deba@2051
  1351
                                 const CostMap& _cost) 
deba@2051
  1352
      : graph(&_graph), cost(&_cost),
deba@2051
  1353
        anode_matching(_graph), bnode_matching(_graph),
deba@2051
  1354
        anode_potential(_graph), bnode_potential(_graph),
deba@2051
  1355
        _heap_cross_ref(0), local_heap_cross_ref(false),
deba@2051
  1356
        _heap(0), local_heap(0) {}
deba@2051
  1357
deba@2051
  1358
    /// \brief Destructor.
deba@2051
  1359
    ///
deba@2051
  1360
    /// Destructor of the algorithm.
deba@2051
  1361
    ~MinCostMaxBipartiteMatching() {
deba@2051
  1362
      destroyStructures();
deba@2051
  1363
    }
deba@2051
  1364
deba@2051
  1365
    /// \brief Sets the heap and the cross reference used by algorithm.
deba@2051
  1366
    ///
deba@2051
  1367
    /// Sets the heap and the cross reference used by algorithm.
deba@2051
  1368
    /// If you don't use this function before calling \ref run(),
deba@2051
  1369
    /// it will allocate one. The destuctor deallocates this
deba@2051
  1370
    /// automatically allocated map, of course.
deba@2051
  1371
    /// \return \c (*this)
deba@2386
  1372
    MinCostMaxBipartiteMatching& heap(Heap& hp, HeapCrossRef &cr) {
deba@2051
  1373
      if(local_heap_cross_ref) {
deba@2051
  1374
	delete _heap_cross_ref;
deba@2051
  1375
	local_heap_cross_ref = false;
deba@2051
  1376
      }
deba@2386
  1377
      _heap_cross_ref = &cr;
deba@2051
  1378
      if(local_heap) {
deba@2051
  1379
	delete _heap;
deba@2051
  1380
	local_heap = false;
deba@2051
  1381
      }
deba@2386
  1382
      _heap = &hp;
deba@2051
  1383
      return *this;
deba@2051
  1384
    }
deba@2051
  1385
deba@2051
  1386
    /// \name Execution control
deba@2051
  1387
    /// The simplest way to execute the algorithm is to use
deba@2051
  1388
    /// one of the member functions called \c run().
deba@2051
  1389
    /// \n
deba@2051
  1390
    /// If you need more control on the execution,
deba@2051
  1391
    /// first you must call \ref init() or one alternative for it.
deba@2051
  1392
    /// Finally \ref start() will perform the matching computation or
deba@2051
  1393
    /// with step-by-step execution you can augment the solution.
deba@2051
  1394
deba@2051
  1395
    /// @{
deba@2051
  1396
deba@2051
  1397
    /// \brief Initalize the data structures.
deba@2051
  1398
    ///
deba@2051
  1399
    /// It initalizes the data structures and creates an empty matching.
deba@2051
  1400
    void init() {
deba@2051
  1401
      initStructures();
deba@2051
  1402
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1403
        anode_matching[it] = INVALID;
deba@2051
  1404
        anode_potential[it] = 0;
deba@2051
  1405
      }
deba@2051
  1406
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1407
        bnode_matching[it] = INVALID;
deba@2051
  1408
        bnode_potential[it] = 0;
deba@2051
  1409
      }
deba@2051
  1410
      matching_cost = 0;
deba@2051
  1411
      matching_size = 0;
deba@2051
  1412
    }
deba@2051
  1413
deba@2051
  1414
deba@2051
  1415
    /// \brief An augmenting phase of the costed matching algorithm
deba@2051
  1416
    ///
deba@2051
  1417
    /// It runs an augmenting phase of the matching algorithm. The
deba@2051
  1418
    /// phase finds the best augmenting path and augments only on this
deba@2051
  1419
    /// paths.
deba@2051
  1420
    ///
deba@2051
  1421
    /// The algorithm consists at most 
deba@2051
  1422
    /// of \f$ O(n) \f$ phase and one phase is \f$ O(n\log(n)+e) \f$ 
deba@2051
  1423
    /// long with Fibonacci heap or \f$ O((n+e)\log(n)) \f$ long 
deba@2051
  1424
    /// with binary heap.
deba@2051
  1425
    bool augment() {
deba@2051
  1426
deba@2051
  1427
      typename BpUGraph::template BNodeMap<Value> bdist(*graph);
deba@2051
  1428
      typename BpUGraph::template BNodeMap<UEdge> bpred(*graph, INVALID);
deba@2051
  1429
deba@2051
  1430
      Node bestNode = INVALID;
deba@2051
  1431
      Value bestValue = 0;
deba@2051
  1432
deba@2051
  1433
      _heap->clear();
deba@2051
  1434
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1435
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
deba@2051
  1436
      }
deba@2051
  1437
deba@2051
  1438
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1439
        if (anode_matching[it] == INVALID) {
deba@2051
  1440
          _heap->push(it, 0);
deba@2051
  1441
        }
deba@2051
  1442
      }
deba@2136
  1443
      Value bdistMax = 0;
deba@2051
  1444
deba@2051
  1445
      while (!_heap->empty()) {
deba@2051
  1446
        Node anode = _heap->top();
deba@2051
  1447
        Value avalue = _heap->prio();
deba@2051
  1448
        _heap->pop();
deba@2051
  1449
        for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2051
  1450
          if (jt == anode_matching[anode]) continue;
deba@2051
  1451
          Node bnode = graph->bNode(jt);
deba@2051
  1452
          Value bvalue = avalue + (*cost)[jt] + 
deba@2051
  1453
            anode_potential[anode] - bnode_potential[bnode];
deba@2051
  1454
          if (bpred[bnode] == INVALID || bvalue < bdist[bnode]) {
deba@2051
  1455
            bdist[bnode] = bvalue;
deba@2051
  1456
            bpred[bnode] = jt;
deba@2051
  1457
          }
deba@2136
  1458
          if (bvalue > bdistMax) {
deba@2136
  1459
            bdistMax = bvalue;
deba@2136
  1460
          }
deba@2051
  1461
          if (bnode_matching[bnode] != INVALID) {
deba@2051
  1462
            Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2051
  1463
            switch (_heap->state(newanode)) {
deba@2051
  1464
            case Heap::PRE_HEAP:
deba@2051
  1465
              _heap->push(newanode, bvalue);
deba@2051
  1466
              break;
deba@2051
  1467
            case Heap::IN_HEAP:
deba@2051
  1468
              if (bvalue < (*_heap)[newanode]) {
deba@2051
  1469
                _heap->decrease(newanode, bvalue);
deba@2051
  1470
              }
deba@2051
  1471
              break;
deba@2051
  1472
            case Heap::POST_HEAP:
deba@2051
  1473
              break;
deba@2051
  1474
            }
deba@2051
  1475
          } else {
deba@2051
  1476
            if (bestNode == INVALID || 
deba@2051
  1477
                bvalue + bnode_potential[bnode] < bestValue) {
deba@2051
  1478
              bestValue = bvalue + bnode_potential[bnode];
deba@2051
  1479
              bestNode = bnode;
deba@2051
  1480
            }
deba@2051
  1481
          }
deba@2051
  1482
        }
deba@2051
  1483
      }
deba@2051
  1484
deba@2051
  1485
      if (bestNode == INVALID) {
deba@2051
  1486
        return false;
deba@2051
  1487
      }
deba@2051
  1488
deba@2051
  1489
      matching_cost += bestValue;
deba@2051
  1490
      ++matching_size;
deba@2051
  1491
deba@2051
  1492
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1493
        if (bpred[it] != INVALID) {
deba@2051
  1494
          bnode_potential[it] += bdist[it];
deba@2136
  1495
        } else {
deba@2136
  1496
          bnode_potential[it] += bdistMax;
deba@2051
  1497
        }
deba@2051
  1498
      }
deba@2051
  1499
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1500
        if (anode_matching[it] != INVALID) {
deba@2051
  1501
          Node bnode = graph->bNode(anode_matching[it]);
deba@2051
  1502
          if (bpred[bnode] != INVALID) {
deba@2051
  1503
            anode_potential[it] += bdist[bnode];
deba@2136
  1504
          } else {
deba@2136
  1505
            anode_potential[it] += bdistMax;
deba@2051
  1506
          }
deba@2051
  1507
        }
deba@2051
  1508
      }
deba@2051
  1509
deba@2051
  1510
      while (bestNode != INVALID) {
deba@2051
  1511
        UEdge uedge = bpred[bestNode];
deba@2051
  1512
        Node anode = graph->aNode(uedge);
deba@2051
  1513
        
deba@2051
  1514
        bnode_matching[bestNode] = uedge;
deba@2051
  1515
        if (anode_matching[anode] != INVALID) {
deba@2051
  1516
          bestNode = graph->bNode(anode_matching[anode]);
deba@2051
  1517
        } else {
deba@2051
  1518
          bestNode = INVALID;
deba@2051
  1519
        }
deba@2051
  1520
        anode_matching[anode] = uedge;
deba@2051
  1521
      }
deba@2051
  1522
deba@2051
  1523
deba@2051
  1524
      return true;
deba@2051
  1525
    }
deba@2051
  1526
deba@2051
  1527
    /// \brief Starts the algorithm.
deba@2051
  1528
    ///
deba@2051
  1529
    /// Starts the algorithm. It runs augmenting phases until the
deba@2051
  1530
    /// optimal solution reached.
deba@2051
  1531
    void start() {
deba@2051
  1532
      while (augment()) {}
deba@2051
  1533
    }
deba@2051
  1534
deba@2051
  1535
    /// \brief Runs the algorithm.
deba@2051
  1536
    ///
deba@2051
  1537
    /// It just initalize the algorithm and then start it.
deba@2051
  1538
    void run() {
deba@2051
  1539
      init();
deba@2051
  1540
      start();
deba@2051
  1541
    }
deba@2051
  1542
deba@2051
  1543
    /// @}
deba@2051
  1544
deba@2051
  1545
    /// \name Query Functions
deba@2051
  1546
    /// The result of the %Matching algorithm can be obtained using these
deba@2051
  1547
    /// functions.\n
deba@2051
  1548
    /// Before the use of these functions,
deba@2051
  1549
    /// either run() or start() must be called.
deba@2051
  1550
    
deba@2051
  1551
    ///@{
deba@2051
  1552
deba@2051
  1553
    /// \brief Gives back the potential in the NodeMap
deba@2051
  1554
    ///
deba@2463
  1555
    /// Gives back the potential in the NodeMap. The matching is optimal
deba@2463
  1556
    /// with the current number of edges if \f$ \pi(a) + \pi(b) - w(ab) = 0 \f$
deba@2463
  1557
    /// for each matching edges and \f$ \pi(a) + \pi(b) - w(ab) \ge 0 \f$
deba@2463
  1558
    /// for each edges. 
deba@2051
  1559
    template <typename PotentialMap>
deba@2386
  1560
    void potential(PotentialMap& pt) const {
deba@2051
  1561
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1562
        pt.set(it, anode_potential[it]);
deba@2051
  1563
      }
deba@2051
  1564
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1565
        pt.set(it, bnode_potential[it]);
deba@2051
  1566
      }
deba@2051
  1567
    }
deba@2051
  1568
deba@2051
  1569
    /// \brief Set true all matching uedge in the map.
deba@2051
  1570
    /// 
deba@2051
  1571
    /// Set true all matching uedge in the map. It does not change the
deba@2051
  1572
    /// value mapped to the other uedges.
deba@2051
  1573
    /// \return The number of the matching edges.
deba@2051
  1574
    template <typename MatchingMap>
deba@2386
  1575
    int quickMatching(MatchingMap& mm) const {
deba@2051
  1576
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1577
        if (anode_matching[it] != INVALID) {
deba@2463
  1578
          mm.set(anode_matching[it], true);
deba@2051
  1579
        }
deba@2051
  1580
      }
deba@2051
  1581
      return matching_size;
deba@2051
  1582
    }
deba@2051
  1583
deba@2051
  1584
    /// \brief Set true all matching uedge in the map and the others to false.
deba@2051
  1585
    /// 
deba@2051
  1586
    /// Set true all matching uedge in the map and the others to false.
deba@2051
  1587
    /// \return The number of the matching edges.
deba@2051
  1588
    template <typename MatchingMap>
deba@2386
  1589
    int matching(MatchingMap& mm) const {
deba@2051
  1590
      for (UEdgeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1591
        mm.set(it, it == anode_matching[graph->aNode(it)]);
deba@2051
  1592
      }
deba@2051
  1593
      return matching_size;
deba@2051
  1594
    }
deba@2051
  1595
deba@2463
  1596
    /// \brief Gives back the matching in an ANodeMap.
deba@2463
  1597
    ///
deba@2463
  1598
    /// Gives back the matching in an ANodeMap. The parameter should
deba@2463
  1599
    /// be a write ANodeMap of UEdge values.
deba@2463
  1600
    /// \return The number of the matching edges.
deba@2463
  1601
    template<class MatchingMap>
deba@2463
  1602
    int aMatching(MatchingMap& mm) const {
deba@2463
  1603
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1604
        mm.set(it, anode_matching[it]);
deba@2463
  1605
      }
deba@2463
  1606
      return matching_size;
deba@2463
  1607
    }
deba@2463
  1608
deba@2463
  1609
    /// \brief Gives back the matching in a BNodeMap.
deba@2463
  1610
    ///
deba@2463
  1611
    /// Gives back the matching in a BNodeMap. The parameter should
deba@2463
  1612
    /// be a write BNodeMap of UEdge values.
deba@2463
  1613
    /// \return The number of the matching edges.
deba@2463
  1614
    template<class MatchingMap>
deba@2463
  1615
    int bMatching(MatchingMap& mm) const {
deba@2463
  1616
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1617
        mm.set(it, bnode_matching[it]);
deba@2463
  1618
      }
deba@2463
  1619
      return matching_size;
deba@2463
  1620
    }
deba@2051
  1621
deba@2051
  1622
    /// \brief Return true if the given uedge is in the matching.
deba@2051
  1623
    /// 
deba@2051
  1624
    /// It returns true if the given uedge is in the matching.
deba@2058
  1625
    bool matchingEdge(const UEdge& edge) const {
deba@2051
  1626
      return anode_matching[graph->aNode(edge)] == edge;
deba@2051
  1627
    }
deba@2051
  1628
deba@2051
  1629
    /// \brief Returns the matching edge from the node.
deba@2051
  1630
    /// 
deba@2051
  1631
    /// Returns the matching edge from the node. If there is not such
deba@2051
  1632
    /// edge it gives back \c INVALID.
deba@2058
  1633
    UEdge matchingEdge(const Node& node) const {
deba@2051
  1634
      if (graph->aNode(node)) {
deba@2051
  1635
        return anode_matching[node];
deba@2051
  1636
      } else {
deba@2051
  1637
        return bnode_matching[node];
deba@2051
  1638
      }
deba@2051
  1639
    }
deba@2051
  1640
deba@2051
  1641
    /// \brief Gives back the sum of costs of the matching edges.
deba@2051
  1642
    ///
deba@2051
  1643
    /// Gives back the sum of costs of the matching edges.
deba@2051
  1644
    Value matchingCost() const {
deba@2051
  1645
      return matching_cost;
deba@2051
  1646
    }
deba@2051
  1647
deba@2051
  1648
    /// \brief Gives back the number of the matching edges.
deba@2051
  1649
    ///
deba@2051
  1650
    /// Gives back the number of the matching edges.
deba@2051
  1651
    int matchingSize() const {
deba@2051
  1652
      return matching_size;
deba@2051
  1653
    }
deba@2051
  1654
deba@2051
  1655
    /// @}
deba@2051
  1656
deba@2051
  1657
  private:
deba@2051
  1658
deba@2051
  1659
    void initStructures() {
deba@2051
  1660
      if (!_heap_cross_ref) {
deba@2051
  1661
	local_heap_cross_ref = true;
deba@2051
  1662
	_heap_cross_ref = Traits::createHeapCrossRef(*graph);
deba@2051
  1663
      }
deba@2051
  1664
      if (!_heap) {
deba@2051
  1665
	local_heap = true;
deba@2051
  1666
	_heap = Traits::createHeap(*_heap_cross_ref);
deba@2051
  1667
      }
deba@2051
  1668
    }
deba@2051
  1669
deba@2051
  1670
    void destroyStructures() {
deba@2051
  1671
      if (local_heap_cross_ref) delete _heap_cross_ref;
deba@2051
  1672
      if (local_heap) delete _heap;
deba@2051
  1673
    }
deba@2051
  1674
deba@2051
  1675
deba@2051
  1676
  private:
deba@2051
  1677
    
deba@2051
  1678
    const BpUGraph *graph;
deba@2051
  1679
    const CostMap* cost;
deba@2051
  1680
deba@2051
  1681
    ANodeMatchingMap anode_matching;
deba@2051
  1682
    BNodeMatchingMap bnode_matching;
deba@2051
  1683
deba@2051
  1684
    ANodePotentialMap anode_potential;
deba@2051
  1685
    BNodePotentialMap bnode_potential;
deba@2051
  1686
deba@2051
  1687
    Value matching_cost;
deba@2051
  1688
    int matching_size;
deba@2051
  1689
deba@2051
  1690
    HeapCrossRef *_heap_cross_ref;
deba@2051
  1691
    bool local_heap_cross_ref;
deba@2051
  1692
deba@2051
  1693
    Heap *_heap;
deba@2051
  1694
    bool local_heap;
deba@2040
  1695
  
deba@2040
  1696
  };
deba@2040
  1697
deba@2058
  1698
  /// \ingroup matching
deba@2058
  1699
  ///
deba@2058
  1700
  /// \brief Minimum cost maximum cardinality bipartite matching
deba@2058
  1701
  ///
deba@2463
  1702
  /// This function calculates the maximum cardinality matching with
deba@2463
  1703
  /// minimum cost of a bipartite graph. It gives back the matching in
deba@2463
  1704
  /// an undirected edge map.
deba@2058
  1705
  ///
deba@2058
  1706
  /// \param graph The bipartite graph.
deba@2058
  1707
  /// \param cost The undirected edge map which contains the costs.
deba@2058
  1708
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1709
  /// the matching.
deba@2058
  1710
  /// \return The cost of the matching.
deba@2058
  1711
  template <typename BpUGraph, typename CostMap, typename MatchingMap>
deba@2058
  1712
  typename CostMap::Value 
deba@2058
  1713
  minCostMaxBipartiteMatching(const BpUGraph& graph, 
deba@2058
  1714
                              const CostMap& cost,
deba@2058
  1715
                              MatchingMap& matching) {
deba@2058
  1716
    MinCostMaxBipartiteMatching<BpUGraph, CostMap> 
deba@2058
  1717
      bpmatching(graph, cost);
deba@2058
  1718
    bpmatching.run();
deba@2058
  1719
    bpmatching.matching(matching);
deba@2058
  1720
    return bpmatching.matchingCost();
deba@2058
  1721
  }
deba@2058
  1722
deba@2040
  1723
}
deba@2040
  1724
deba@2040
  1725
#endif