lemon/bipartite_matching.h
author hegyi
Mon, 07 Apr 2008 16:28:20 +0000
changeset 2600 e5530c0a018c
parent 2550 f26368148b9c
permissions -rw-r--r--
NEWS file updated for Release 0.7
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@2553
     5
 * Copyright (C) 2003-2008
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@2488
   118
	    _reached.set(_graph->bNode(jt), -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@2550
   581
  struct MaxWeightedBipartiteMatchingDefaultTraits {
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@2550
   594
    /// Usually it is \c Graph::ANodeMap<int>.
deba@2550
   595
    typedef typename BpUGraph::template ANodeMap<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@2550
   647
            typename _Traits = 
deba@2550
   648
	    MaxWeightedBipartiteMatchingDefaultTraits<_BpUGraph, _WeightMap> >
deba@2051
   649
#endif
deba@2051
   650
  class MaxWeightedBipartiteMatching {
deba@2051
   651
  public:
deba@2051
   652
deba@2051
   653
    typedef _Traits Traits;
deba@2051
   654
    typedef typename Traits::BpUGraph BpUGraph;
deba@2051
   655
    typedef typename Traits::WeightMap WeightMap;
deba@2051
   656
    typedef typename Traits::Value Value;
deba@2051
   657
deba@2051
   658
  protected:
deba@2051
   659
deba@2051
   660
    typedef typename Traits::HeapCrossRef HeapCrossRef;
deba@2051
   661
    typedef typename Traits::Heap Heap; 
deba@2051
   662
deba@2051
   663
    
deba@2051
   664
    typedef typename BpUGraph::Node Node;
deba@2051
   665
    typedef typename BpUGraph::ANodeIt ANodeIt;
deba@2051
   666
    typedef typename BpUGraph::BNodeIt BNodeIt;
deba@2051
   667
    typedef typename BpUGraph::UEdge UEdge;
deba@2051
   668
    typedef typename BpUGraph::UEdgeIt UEdgeIt;
deba@2051
   669
    typedef typename BpUGraph::IncEdgeIt IncEdgeIt;
deba@2051
   670
deba@2051
   671
    typedef typename BpUGraph::template ANodeMap<UEdge> ANodeMatchingMap;
deba@2051
   672
    typedef typename BpUGraph::template BNodeMap<UEdge> BNodeMatchingMap;
deba@2051
   673
deba@2051
   674
    typedef typename BpUGraph::template ANodeMap<Value> ANodePotentialMap;
deba@2051
   675
    typedef typename BpUGraph::template BNodeMap<Value> BNodePotentialMap;
deba@2051
   676
deba@2051
   677
deba@2051
   678
  public:
deba@2051
   679
deba@2051
   680
    /// \brief \ref Exception for uninitialized parameters.
deba@2051
   681
    ///
deba@2051
   682
    /// This error represents problems in the initialization
deba@2051
   683
    /// of the parameters of the algorithms.
deba@2051
   684
    class UninitializedParameter : public lemon::UninitializedParameter {
deba@2051
   685
    public:
alpar@2151
   686
      virtual const char* what() const throw() {
deba@2051
   687
	return "lemon::MaxWeightedBipartiteMatching::UninitializedParameter";
deba@2051
   688
      }
deba@2051
   689
    };
deba@2051
   690
deba@2051
   691
    ///\name Named template parameters
deba@2051
   692
deba@2051
   693
    ///@{
deba@2051
   694
deba@2051
   695
    template <class H, class CR>
deba@2051
   696
    struct DefHeapTraits : public Traits {
deba@2051
   697
      typedef CR HeapCrossRef;
deba@2051
   698
      typedef H Heap;
deba@2051
   699
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &) {
deba@2051
   700
	throw UninitializedParameter();
deba@2051
   701
      }
deba@2051
   702
      static Heap *createHeap(HeapCrossRef &) {
deba@2051
   703
	throw UninitializedParameter();
deba@2051
   704
      }
deba@2051
   705
    };
deba@2051
   706
deba@2051
   707
    /// \brief \ref named-templ-param "Named parameter" for setting heap 
deba@2051
   708
    /// and cross reference type
deba@2051
   709
    ///
deba@2051
   710
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
   711
    /// reference type
deba@2051
   712
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
   713
    struct DefHeap
deba@2051
   714
      : public MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   715
                                            DefHeapTraits<H, CR> > { 
deba@2051
   716
      typedef MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   717
                                           DefHeapTraits<H, CR> > Create;
deba@2051
   718
    };
deba@2051
   719
deba@2051
   720
    template <class H, class CR>
deba@2051
   721
    struct DefStandardHeapTraits : public Traits {
deba@2051
   722
      typedef CR HeapCrossRef;
deba@2051
   723
      typedef H Heap;
deba@2051
   724
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
   725
	return new HeapCrossRef(graph);
deba@2051
   726
      }
deba@2051
   727
      static Heap *createHeap(HeapCrossRef &crossref) {
deba@2051
   728
	return new Heap(crossref);
deba@2051
   729
      }
deba@2051
   730
    };
deba@2051
   731
deba@2051
   732
    /// \brief \ref named-templ-param "Named parameter" for setting heap and 
deba@2051
   733
    /// cross reference type with automatic allocation
deba@2051
   734
    ///
deba@2051
   735
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
   736
    /// reference type. It can allocate the heap and the cross reference 
deba@2051
   737
    /// object if the cross reference's constructor waits for the graph as 
deba@2051
   738
    /// parameter and the heap's constructor waits for the cross reference.
deba@2051
   739
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
   740
    struct DefStandardHeap
deba@2051
   741
      : public MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   742
                                            DefStandardHeapTraits<H, CR> > { 
deba@2051
   743
      typedef MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   744
                                           DefStandardHeapTraits<H, CR> > 
deba@2051
   745
      Create;
deba@2051
   746
    };
deba@2051
   747
deba@2051
   748
    ///@}
deba@2051
   749
deba@2051
   750
deba@2051
   751
    /// \brief Constructor.
deba@2051
   752
    ///
deba@2051
   753
    /// Constructor of the algorithm. 
deba@2051
   754
    MaxWeightedBipartiteMatching(const BpUGraph& _graph, 
deba@2051
   755
                                 const WeightMap& _weight) 
deba@2051
   756
      : graph(&_graph), weight(&_weight),
deba@2051
   757
        anode_matching(_graph), bnode_matching(_graph),
deba@2051
   758
        anode_potential(_graph), bnode_potential(_graph),
deba@2051
   759
        _heap_cross_ref(0), local_heap_cross_ref(false),
deba@2051
   760
        _heap(0), local_heap(0) {}
deba@2051
   761
deba@2051
   762
    /// \brief Destructor.
deba@2051
   763
    ///
deba@2051
   764
    /// Destructor of the algorithm.
deba@2051
   765
    ~MaxWeightedBipartiteMatching() {
deba@2051
   766
      destroyStructures();
deba@2051
   767
    }
deba@2051
   768
deba@2051
   769
    /// \brief Sets the heap and the cross reference used by algorithm.
deba@2051
   770
    ///
deba@2051
   771
    /// Sets the heap and the cross reference used by algorithm.
deba@2051
   772
    /// If you don't use this function before calling \ref run(),
deba@2051
   773
    /// it will allocate one. The destuctor deallocates this
deba@2051
   774
    /// automatically allocated map, of course.
deba@2051
   775
    /// \return \c (*this)
deba@2386
   776
    MaxWeightedBipartiteMatching& heap(Heap& hp, HeapCrossRef &cr) {
deba@2051
   777
      if(local_heap_cross_ref) {
deba@2051
   778
	delete _heap_cross_ref;
deba@2051
   779
	local_heap_cross_ref = false;
deba@2051
   780
      }
deba@2386
   781
      _heap_cross_ref = &cr;
deba@2051
   782
      if(local_heap) {
deba@2051
   783
	delete _heap;
deba@2051
   784
	local_heap = false;
deba@2051
   785
      }
deba@2386
   786
      _heap = &hp;
deba@2051
   787
      return *this;
deba@2051
   788
    }
deba@2051
   789
deba@2051
   790
    /// \name Execution control
deba@2051
   791
    /// The simplest way to execute the algorithm is to use
deba@2051
   792
    /// one of the member functions called \c run().
deba@2051
   793
    /// \n
deba@2051
   794
    /// If you need more control on the execution,
deba@2051
   795
    /// first you must call \ref init() or one alternative for it.
deba@2051
   796
    /// Finally \ref start() will perform the matching computation or
deba@2051
   797
    /// with step-by-step execution you can augment the solution.
deba@2051
   798
deba@2051
   799
    /// @{
deba@2051
   800
deba@2051
   801
    /// \brief Initalize the data structures.
deba@2051
   802
    ///
deba@2051
   803
    /// It initalizes the data structures and creates an empty matching.
deba@2051
   804
    void init() {
deba@2051
   805
      initStructures();
deba@2051
   806
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   807
        anode_matching[it] = INVALID;
deba@2051
   808
        anode_potential[it] = 0;
deba@2051
   809
      }
deba@2051
   810
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   811
        bnode_matching[it] = INVALID;
deba@2051
   812
        bnode_potential[it] = 0;
deba@2051
   813
        for (IncEdgeIt jt(*graph, it); jt != INVALID; ++jt) {
deba@2058
   814
          if ((*weight)[jt] > bnode_potential[it]) {
deba@2058
   815
            bnode_potential[it] = (*weight)[jt];
deba@2051
   816
          }
deba@2051
   817
        }
deba@2051
   818
      }
deba@2051
   819
      matching_value = 0;
deba@2051
   820
      matching_size = 0;
deba@2051
   821
    }
deba@2051
   822
deba@2051
   823
deba@2051
   824
    /// \brief An augmenting phase of the weighted matching algorithm
deba@2051
   825
    ///
deba@2051
   826
    /// It runs an augmenting phase of the weighted matching 
alpar@2352
   827
    /// algorithm. This phase finds the best augmenting path and 
deba@2051
   828
    /// augments only on this paths. 
deba@2051
   829
    ///
deba@2051
   830
    /// The algorithm consists at most 
deba@2051
   831
    /// of \f$ O(n) \f$ phase and one phase is \f$ O(n\log(n)+e) \f$ 
deba@2051
   832
    /// long with Fibonacci heap or \f$ O((n+e)\log(n)) \f$ long 
deba@2051
   833
    /// with binary heap.
deba@2051
   834
    /// \param decrease If the given parameter true the matching value
deba@2051
   835
    /// can be decreased in the augmenting phase. If we would like
deba@2051
   836
    /// to calculate the maximum cardinality maximum weighted matching
deba@2051
   837
    /// then we should let the algorithm to decrease the matching
deba@2051
   838
    /// value in order to increase the number of the matching edges.
deba@2051
   839
    bool augment(bool decrease = false) {
deba@2051
   840
deba@2051
   841
      typename BpUGraph::template BNodeMap<Value> bdist(*graph);
deba@2051
   842
      typename BpUGraph::template BNodeMap<UEdge> bpred(*graph, INVALID);
deba@2051
   843
deba@2051
   844
      Node bestNode = INVALID;
deba@2051
   845
      Value bestValue = 0;
deba@2051
   846
deba@2051
   847
      _heap->clear();
deba@2051
   848
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   849
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
deba@2051
   850
      }
deba@2051
   851
deba@2051
   852
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   853
        if (anode_matching[it] == INVALID) {
deba@2051
   854
          _heap->push(it, 0);
deba@2051
   855
        }
deba@2051
   856
      }
deba@2051
   857
deba@2051
   858
      Value bdistMax = 0;
deba@2051
   859
      while (!_heap->empty()) {
deba@2051
   860
        Node anode = _heap->top();
deba@2051
   861
        Value avalue = _heap->prio();
deba@2051
   862
        _heap->pop();
deba@2051
   863
        for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2051
   864
          if (jt == anode_matching[anode]) continue;
deba@2051
   865
          Node bnode = graph->bNode(jt);
deba@2058
   866
          Value bvalue = avalue  - (*weight)[jt] +
deba@2058
   867
            anode_potential[anode] + bnode_potential[bnode];
deba@2550
   868
          if (bvalue > bdistMax) {
deba@2550
   869
            bdistMax = bvalue;
deba@2550
   870
          }
deba@2051
   871
          if (bpred[bnode] == INVALID || bvalue < bdist[bnode]) {
deba@2051
   872
            bdist[bnode] = bvalue;
deba@2051
   873
            bpred[bnode] = jt;
deba@2550
   874
          } else continue;
deba@2051
   875
          if (bnode_matching[bnode] != INVALID) {
deba@2051
   876
            Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2051
   877
            switch (_heap->state(newanode)) {
deba@2051
   878
            case Heap::PRE_HEAP:
deba@2051
   879
              _heap->push(newanode, bvalue);
deba@2051
   880
              break;
deba@2051
   881
            case Heap::IN_HEAP:
deba@2051
   882
              if (bvalue < (*_heap)[newanode]) {
deba@2051
   883
                _heap->decrease(newanode, bvalue);
deba@2051
   884
              }
deba@2051
   885
              break;
deba@2051
   886
            case Heap::POST_HEAP:
deba@2051
   887
              break;
deba@2051
   888
            }
deba@2051
   889
          } else {
deba@2051
   890
            if (bestNode == INVALID || 
deba@2058
   891
                bnode_potential[bnode] - bvalue > bestValue) {
deba@2058
   892
              bestValue = bnode_potential[bnode] - bvalue;
deba@2051
   893
              bestNode = bnode;
deba@2051
   894
            }
deba@2051
   895
          }
deba@2051
   896
        }
deba@2051
   897
      }
deba@2051
   898
deba@2051
   899
      if (bestNode == INVALID || (!decrease && bestValue < 0)) {
deba@2051
   900
        return false;
deba@2051
   901
      }
deba@2051
   902
deba@2051
   903
      matching_value += bestValue;
deba@2051
   904
      ++matching_size;
deba@2051
   905
deba@2051
   906
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   907
        if (bpred[it] != INVALID) {
deba@2058
   908
          bnode_potential[it] -= bdist[it];
deba@2051
   909
        } else {
deba@2058
   910
          bnode_potential[it] -= bdistMax;
deba@2051
   911
        }
deba@2051
   912
      }
deba@2051
   913
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   914
        if (anode_matching[it] != INVALID) {
deba@2051
   915
          Node bnode = graph->bNode(anode_matching[it]);
deba@2051
   916
          if (bpred[bnode] != INVALID) {
deba@2051
   917
            anode_potential[it] += bdist[bnode];
deba@2051
   918
          } else {
deba@2051
   919
            anode_potential[it] += bdistMax;
deba@2051
   920
          }
deba@2051
   921
        }
deba@2051
   922
      }
deba@2051
   923
deba@2051
   924
      while (bestNode != INVALID) {
deba@2051
   925
        UEdge uedge = bpred[bestNode];
deba@2051
   926
        Node anode = graph->aNode(uedge);
deba@2051
   927
        
deba@2051
   928
        bnode_matching[bestNode] = uedge;
deba@2051
   929
        if (anode_matching[anode] != INVALID) {
deba@2051
   930
          bestNode = graph->bNode(anode_matching[anode]);
deba@2051
   931
        } else {
deba@2051
   932
          bestNode = INVALID;
deba@2051
   933
        }
deba@2051
   934
        anode_matching[anode] = uedge;
deba@2051
   935
      }
deba@2051
   936
deba@2051
   937
deba@2051
   938
      return true;
deba@2051
   939
    }
deba@2051
   940
deba@2051
   941
    /// \brief Starts the algorithm.
deba@2051
   942
    ///
deba@2051
   943
    /// Starts the algorithm. It runs augmenting phases until the
deba@2051
   944
    /// optimal solution reached.
deba@2051
   945
    ///
deba@2051
   946
    /// \param maxCardinality If the given value is true it will
deba@2051
   947
    /// calculate the maximum cardinality maximum matching instead of
deba@2051
   948
    /// the maximum matching.
deba@2051
   949
    void start(bool maxCardinality = false) {
deba@2051
   950
      while (augment(maxCardinality)) {}
deba@2051
   951
    }
deba@2051
   952
deba@2051
   953
    /// \brief Runs the algorithm.
deba@2051
   954
    ///
deba@2051
   955
    /// It just initalize the algorithm and then start it.
deba@2051
   956
    ///
deba@2051
   957
    /// \param maxCardinality If the given value is true it will
deba@2051
   958
    /// calculate the maximum cardinality maximum matching instead of
deba@2051
   959
    /// the maximum matching.
deba@2051
   960
    void run(bool maxCardinality = false) {
deba@2051
   961
      init();
deba@2051
   962
      start(maxCardinality);
deba@2051
   963
    }
deba@2051
   964
deba@2051
   965
    /// @}
deba@2051
   966
deba@2051
   967
    /// \name Query Functions
deba@2051
   968
    /// The result of the %Matching algorithm can be obtained using these
deba@2051
   969
    /// functions.\n
deba@2051
   970
    /// Before the use of these functions,
deba@2051
   971
    /// either run() or start() must be called.
deba@2051
   972
    
deba@2051
   973
    ///@{
deba@2051
   974
deba@2051
   975
    /// \brief Gives back the potential in the NodeMap
deba@2051
   976
    ///
deba@2058
   977
    /// Gives back the potential in the NodeMap. The matching is optimal
deba@2058
   978
    /// with the current number of edges if \f$ \pi(a) + \pi(b) - w(ab) = 0 \f$
deba@2058
   979
    /// for each matching edges and \f$ \pi(a) + \pi(b) - w(ab) \ge 0 \f$
deba@2058
   980
    /// for each edges. 
deba@2051
   981
    template <typename PotentialMap>
deba@2386
   982
    void potential(PotentialMap& pt) const {
deba@2051
   983
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2463
   984
        pt.set(it, anode_potential[it]);
deba@2051
   985
      }
deba@2051
   986
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2463
   987
        pt.set(it, bnode_potential[it]);
deba@2051
   988
      }
deba@2051
   989
    }
deba@2051
   990
deba@2051
   991
    /// \brief Set true all matching uedge in the map.
deba@2051
   992
    /// 
deba@2051
   993
    /// Set true all matching uedge in the map. It does not change the
deba@2051
   994
    /// value mapped to the other uedges.
deba@2051
   995
    /// \return The number of the matching edges.
deba@2051
   996
    template <typename MatchingMap>
deba@2386
   997
    int quickMatching(MatchingMap& mm) const {
deba@2051
   998
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   999
        if (anode_matching[it] != INVALID) {
deba@2463
  1000
          mm.set(anode_matching[it], true);
deba@2051
  1001
        }
deba@2051
  1002
      }
deba@2051
  1003
      return matching_size;
deba@2051
  1004
    }
deba@2051
  1005
deba@2051
  1006
    /// \brief Set true all matching uedge in the map and the others to false.
deba@2051
  1007
    /// 
deba@2051
  1008
    /// Set true all matching uedge in the map and the others to false.
deba@2051
  1009
    /// \return The number of the matching edges.
deba@2051
  1010
    template <typename MatchingMap>
deba@2386
  1011
    int matching(MatchingMap& mm) const {
deba@2051
  1012
      for (UEdgeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1013
        mm.set(it, it == anode_matching[graph->aNode(it)]);
deba@2463
  1014
      }
deba@2463
  1015
      return matching_size;
deba@2463
  1016
    }
deba@2463
  1017
deba@2463
  1018
    ///Gives back the matching in an ANodeMap.
deba@2463
  1019
deba@2463
  1020
    ///Gives back the matching in an ANodeMap. The parameter should
deba@2463
  1021
    ///be a write ANodeMap of UEdge values.
deba@2463
  1022
    ///\return The number of the matching edges.
deba@2463
  1023
    template<class MatchingMap>
deba@2463
  1024
    int aMatching(MatchingMap& mm) const {
deba@2463
  1025
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1026
        mm.set(it, anode_matching[it]);
deba@2463
  1027
      }
deba@2463
  1028
      return matching_size;
deba@2463
  1029
    }
deba@2463
  1030
deba@2463
  1031
    ///Gives back the matching in a BNodeMap.
deba@2463
  1032
deba@2463
  1033
    ///Gives back the matching in a BNodeMap. The parameter should
deba@2463
  1034
    ///be a write BNodeMap of UEdge values.
deba@2463
  1035
    ///\return The number of the matching edges.
deba@2463
  1036
    template<class MatchingMap>
deba@2463
  1037
    int bMatching(MatchingMap& mm) const {
deba@2463
  1038
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1039
        mm.set(it, bnode_matching[it]);
deba@2051
  1040
      }
deba@2051
  1041
      return matching_size;
deba@2051
  1042
    }
deba@2051
  1043
deba@2051
  1044
deba@2051
  1045
    /// \brief Return true if the given uedge is in the matching.
deba@2051
  1046
    /// 
deba@2051
  1047
    /// It returns true if the given uedge is in the matching.
deba@2058
  1048
    bool matchingEdge(const UEdge& edge) const {
deba@2051
  1049
      return anode_matching[graph->aNode(edge)] == edge;
deba@2051
  1050
    }
deba@2051
  1051
deba@2051
  1052
    /// \brief Returns the matching edge from the node.
deba@2051
  1053
    /// 
deba@2051
  1054
    /// Returns the matching edge from the node. If there is not such
deba@2051
  1055
    /// edge it gives back \c INVALID.
deba@2058
  1056
    UEdge matchingEdge(const Node& node) const {
deba@2051
  1057
      if (graph->aNode(node)) {
deba@2051
  1058
        return anode_matching[node];
deba@2051
  1059
      } else {
deba@2051
  1060
        return bnode_matching[node];
deba@2051
  1061
      }
deba@2051
  1062
    }
deba@2051
  1063
deba@2051
  1064
    /// \brief Gives back the sum of weights of the matching edges.
deba@2051
  1065
    ///
deba@2051
  1066
    /// Gives back the sum of weights of the matching edges.
deba@2051
  1067
    Value matchingValue() const {
deba@2051
  1068
      return matching_value;
deba@2051
  1069
    }
deba@2051
  1070
deba@2051
  1071
    /// \brief Gives back the number of the matching edges.
deba@2051
  1072
    ///
deba@2051
  1073
    /// Gives back the number of the matching edges.
deba@2051
  1074
    int matchingSize() const {
deba@2051
  1075
      return matching_size;
deba@2051
  1076
    }
deba@2051
  1077
deba@2051
  1078
    /// @}
deba@2051
  1079
deba@2051
  1080
  private:
deba@2051
  1081
deba@2051
  1082
    void initStructures() {
deba@2051
  1083
      if (!_heap_cross_ref) {
deba@2051
  1084
	local_heap_cross_ref = true;
deba@2051
  1085
	_heap_cross_ref = Traits::createHeapCrossRef(*graph);
deba@2051
  1086
      }
deba@2051
  1087
      if (!_heap) {
deba@2051
  1088
	local_heap = true;
deba@2051
  1089
	_heap = Traits::createHeap(*_heap_cross_ref);
deba@2051
  1090
      }
deba@2051
  1091
    }
deba@2051
  1092
deba@2051
  1093
    void destroyStructures() {
deba@2051
  1094
      if (local_heap_cross_ref) delete _heap_cross_ref;
deba@2051
  1095
      if (local_heap) delete _heap;
deba@2051
  1096
    }
deba@2051
  1097
deba@2051
  1098
deba@2051
  1099
  private:
deba@2051
  1100
    
deba@2051
  1101
    const BpUGraph *graph;
deba@2051
  1102
    const WeightMap* weight;
deba@2051
  1103
deba@2051
  1104
    ANodeMatchingMap anode_matching;
deba@2051
  1105
    BNodeMatchingMap bnode_matching;
deba@2051
  1106
deba@2051
  1107
    ANodePotentialMap anode_potential;
deba@2051
  1108
    BNodePotentialMap bnode_potential;
deba@2051
  1109
deba@2051
  1110
    Value matching_value;
deba@2051
  1111
    int matching_size;
deba@2051
  1112
deba@2051
  1113
    HeapCrossRef *_heap_cross_ref;
deba@2051
  1114
    bool local_heap_cross_ref;
deba@2051
  1115
deba@2051
  1116
    Heap *_heap;
deba@2051
  1117
    bool local_heap;
deba@2051
  1118
  
deba@2051
  1119
  };
deba@2051
  1120
deba@2058
  1121
  /// \ingroup matching
deba@2058
  1122
  ///
deba@2058
  1123
  /// \brief Maximum weighted bipartite matching
deba@2058
  1124
  ///
deba@2058
  1125
  /// This function calculates the maximum weighted matching
deba@2058
  1126
  /// in a bipartite graph. It gives back the matching in an undirected
deba@2058
  1127
  /// edge map.
deba@2058
  1128
  ///
deba@2058
  1129
  /// \param graph The bipartite graph.
deba@2058
  1130
  /// \param weight The undirected edge map which contains the weights.
deba@2058
  1131
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1132
  /// the matching.
deba@2058
  1133
  /// \return The value of the matching.
deba@2058
  1134
  template <typename BpUGraph, typename WeightMap, typename MatchingMap>
deba@2058
  1135
  typename WeightMap::Value 
deba@2058
  1136
  maxWeightedBipartiteMatching(const BpUGraph& graph, const WeightMap& weight,
deba@2058
  1137
                               MatchingMap& matching) {
deba@2058
  1138
    MaxWeightedBipartiteMatching<BpUGraph, WeightMap> 
deba@2058
  1139
      bpmatching(graph, weight);
deba@2058
  1140
    bpmatching.run();
deba@2058
  1141
    bpmatching.matching(matching);
deba@2058
  1142
    return bpmatching.matchingValue();
deba@2058
  1143
  }
deba@2058
  1144
deba@2058
  1145
  /// \ingroup matching
deba@2058
  1146
  ///
deba@2058
  1147
  /// \brief Maximum weighted maximum cardinality bipartite matching
deba@2058
  1148
  ///
deba@2058
  1149
  /// This function calculates the maximum weighted of the maximum cardinality
deba@2058
  1150
  /// matchings of a bipartite graph. It gives back the matching in an 
deba@2058
  1151
  /// undirected edge map.
deba@2058
  1152
  ///
deba@2058
  1153
  /// \param graph The bipartite graph.
deba@2058
  1154
  /// \param weight The undirected edge map which contains the weights.
deba@2058
  1155
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1156
  /// the matching.
deba@2058
  1157
  /// \return The value of the matching.
deba@2058
  1158
  template <typename BpUGraph, typename WeightMap, typename MatchingMap>
deba@2058
  1159
  typename WeightMap::Value 
deba@2058
  1160
  maxWeightedMaxBipartiteMatching(const BpUGraph& graph, 
deba@2058
  1161
                                  const WeightMap& weight,
deba@2058
  1162
                                  MatchingMap& matching) {
deba@2058
  1163
    MaxWeightedBipartiteMatching<BpUGraph, WeightMap> 
deba@2058
  1164
      bpmatching(graph, weight);
deba@2058
  1165
    bpmatching.run(true);
deba@2058
  1166
    bpmatching.matching(matching);
deba@2058
  1167
    return bpmatching.matchingValue();
deba@2058
  1168
  }
deba@2058
  1169
deba@2051
  1170
  /// \brief Default traits class for minimum cost bipartite matching
deba@2051
  1171
  /// algoritms.
deba@2051
  1172
  ///
deba@2051
  1173
  /// Default traits class for minimum cost bipartite matching
deba@2051
  1174
  /// algoritms.  
deba@2051
  1175
  ///
deba@2051
  1176
  /// \param _BpUGraph The bipartite undirected graph
deba@2051
  1177
  /// type.  
deba@2051
  1178
  ///
deba@2051
  1179
  /// \param _CostMap Type of cost map.
deba@2051
  1180
  template <typename _BpUGraph, typename _CostMap>
deba@2051
  1181
  struct MinCostMaxBipartiteMatchingDefaultTraits {
deba@2051
  1182
    /// \brief The type of the cost of the undirected edges.
deba@2051
  1183
    typedef typename _CostMap::Value Value;
deba@2051
  1184
deba@2051
  1185
    /// The undirected bipartite graph type the algorithm runs on. 
deba@2051
  1186
    typedef _BpUGraph BpUGraph;
deba@2051
  1187
deba@2051
  1188
    /// The map of the edges costs
deba@2051
  1189
    typedef _CostMap CostMap;
deba@2051
  1190
deba@2051
  1191
    /// \brief The cross reference type used by heap.
deba@2051
  1192
    ///
deba@2051
  1193
    /// The cross reference type used by heap.
deba@2051
  1194
    /// Usually it is \c Graph::NodeMap<int>.
deba@2051
  1195
    typedef typename BpUGraph::template NodeMap<int> HeapCrossRef;
deba@2051
  1196
deba@2051
  1197
    /// \brief Instantiates a HeapCrossRef.
deba@2051
  1198
    ///
deba@2051
  1199
    /// This function instantiates a \ref HeapCrossRef. 
deba@2051
  1200
    /// \param graph is the graph, to which we would like to define the 
deba@2051
  1201
    /// HeapCrossRef.
deba@2051
  1202
    static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
  1203
      return new HeapCrossRef(graph);
deba@2051
  1204
    }
deba@2051
  1205
    
deba@2051
  1206
    /// \brief The heap type used by costed matching algorithms.
deba@2051
  1207
    ///
deba@2051
  1208
    /// The heap type used by costed matching algorithms. It should
deba@2051
  1209
    /// minimize the priorities and the heap's key type is the graph's
deba@2051
  1210
    /// anode graph's node.
deba@2051
  1211
    ///
deba@2051
  1212
    /// \sa BinHeap
deba@2269
  1213
    typedef BinHeap<Value, HeapCrossRef> Heap;
deba@2051
  1214
    
deba@2051
  1215
    /// \brief Instantiates a Heap.
deba@2051
  1216
    ///
deba@2051
  1217
    /// This function instantiates a \ref Heap. 
deba@2051
  1218
    /// \param crossref The cross reference of the heap.
deba@2051
  1219
    static Heap *createHeap(HeapCrossRef& crossref) {
deba@2051
  1220
      return new Heap(crossref);
deba@2051
  1221
    }
deba@2051
  1222
deba@2051
  1223
  };
deba@2051
  1224
deba@2051
  1225
deba@2051
  1226
  /// \ingroup matching
deba@2051
  1227
  ///
deba@2051
  1228
  /// \brief Bipartite Min Cost Matching algorithm
deba@2051
  1229
  ///
deba@2051
  1230
  /// This class implements the bipartite Min Cost Matching algorithm.
deba@2051
  1231
  /// It uses the successive shortest path algorithm to calculate the
deba@2051
  1232
  /// minimum cost maximum matching in the bipartite graph. The time
deba@2051
  1233
  /// complexity of the algorithm is \f$ O(ne\log(n)) \f$ with the
deba@2051
  1234
  /// default binary heap implementation but this can be improved to
deba@2051
  1235
  /// \f$ O(n^2\log(n)+ne) \f$ if we use fibonacci heaps.
deba@2051
  1236
  ///
deba@2051
  1237
  /// The algorithm also provides a potential function on the nodes
deba@2051
  1238
  /// which a dual solution of the matching algorithm and it can be
deba@2051
  1239
  /// used to proof the optimality of the given pimal solution.
deba@2051
  1240
#ifdef DOXYGEN
deba@2051
  1241
  template <typename _BpUGraph, typename _CostMap, typename _Traits>
deba@2051
  1242
#else
deba@2051
  1243
  template <typename _BpUGraph, 
deba@2051
  1244
            typename _CostMap = typename _BpUGraph::template UEdgeMap<int>,
deba@2550
  1245
            typename _Traits = 
deba@2550
  1246
	    MinCostMaxBipartiteMatchingDefaultTraits<_BpUGraph, _CostMap> >
deba@2051
  1247
#endif
deba@2051
  1248
  class MinCostMaxBipartiteMatching {
deba@2051
  1249
  public:
deba@2051
  1250
deba@2051
  1251
    typedef _Traits Traits;
deba@2051
  1252
    typedef typename Traits::BpUGraph BpUGraph;
deba@2051
  1253
    typedef typename Traits::CostMap CostMap;
deba@2051
  1254
    typedef typename Traits::Value Value;
deba@2051
  1255
deba@2051
  1256
  protected:
deba@2051
  1257
deba@2051
  1258
    typedef typename Traits::HeapCrossRef HeapCrossRef;
deba@2051
  1259
    typedef typename Traits::Heap Heap; 
deba@2051
  1260
deba@2051
  1261
    
deba@2051
  1262
    typedef typename BpUGraph::Node Node;
deba@2051
  1263
    typedef typename BpUGraph::ANodeIt ANodeIt;
deba@2051
  1264
    typedef typename BpUGraph::BNodeIt BNodeIt;
deba@2051
  1265
    typedef typename BpUGraph::UEdge UEdge;
deba@2051
  1266
    typedef typename BpUGraph::UEdgeIt UEdgeIt;
deba@2051
  1267
    typedef typename BpUGraph::IncEdgeIt IncEdgeIt;
deba@2051
  1268
deba@2051
  1269
    typedef typename BpUGraph::template ANodeMap<UEdge> ANodeMatchingMap;
deba@2051
  1270
    typedef typename BpUGraph::template BNodeMap<UEdge> BNodeMatchingMap;
deba@2051
  1271
deba@2051
  1272
    typedef typename BpUGraph::template ANodeMap<Value> ANodePotentialMap;
deba@2051
  1273
    typedef typename BpUGraph::template BNodeMap<Value> BNodePotentialMap;
deba@2051
  1274
deba@2051
  1275
deba@2051
  1276
  public:
deba@2051
  1277
deba@2051
  1278
    /// \brief \ref Exception for uninitialized parameters.
deba@2051
  1279
    ///
deba@2051
  1280
    /// This error represents problems in the initialization
deba@2051
  1281
    /// of the parameters of the algorithms.
deba@2051
  1282
    class UninitializedParameter : public lemon::UninitializedParameter {
deba@2051
  1283
    public:
alpar@2151
  1284
      virtual const char* what() const throw() {
deba@2051
  1285
	return "lemon::MinCostMaxBipartiteMatching::UninitializedParameter";
deba@2051
  1286
      }
deba@2051
  1287
    };
deba@2051
  1288
deba@2051
  1289
    ///\name Named template parameters
deba@2051
  1290
deba@2051
  1291
    ///@{
deba@2051
  1292
deba@2051
  1293
    template <class H, class CR>
deba@2051
  1294
    struct DefHeapTraits : public Traits {
deba@2051
  1295
      typedef CR HeapCrossRef;
deba@2051
  1296
      typedef H Heap;
deba@2051
  1297
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &) {
deba@2051
  1298
	throw UninitializedParameter();
deba@2051
  1299
      }
deba@2051
  1300
      static Heap *createHeap(HeapCrossRef &) {
deba@2051
  1301
	throw UninitializedParameter();
deba@2051
  1302
      }
deba@2051
  1303
    };
deba@2051
  1304
deba@2051
  1305
    /// \brief \ref named-templ-param "Named parameter" for setting heap 
deba@2051
  1306
    /// and cross reference type
deba@2051
  1307
    ///
deba@2051
  1308
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
  1309
    /// reference type
deba@2051
  1310
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
  1311
    struct DefHeap
deba@2051
  1312
      : public MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1313
                                            DefHeapTraits<H, CR> > { 
deba@2051
  1314
      typedef MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1315
                                           DefHeapTraits<H, CR> > Create;
deba@2051
  1316
    };
deba@2051
  1317
deba@2051
  1318
    template <class H, class CR>
deba@2051
  1319
    struct DefStandardHeapTraits : public Traits {
deba@2051
  1320
      typedef CR HeapCrossRef;
deba@2051
  1321
      typedef H Heap;
deba@2051
  1322
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
  1323
	return new HeapCrossRef(graph);
deba@2051
  1324
      }
deba@2051
  1325
      static Heap *createHeap(HeapCrossRef &crossref) {
deba@2051
  1326
	return new Heap(crossref);
deba@2051
  1327
      }
deba@2051
  1328
    };
deba@2051
  1329
deba@2051
  1330
    /// \brief \ref named-templ-param "Named parameter" for setting heap and 
deba@2051
  1331
    /// cross reference type with automatic allocation
deba@2051
  1332
    ///
deba@2051
  1333
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
  1334
    /// reference type. It can allocate the heap and the cross reference 
deba@2051
  1335
    /// object if the cross reference's constructor waits for the graph as 
deba@2051
  1336
    /// parameter and the heap's constructor waits for the cross reference.
deba@2051
  1337
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
  1338
    struct DefStandardHeap
deba@2051
  1339
      : public MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1340
                                            DefStandardHeapTraits<H, CR> > { 
deba@2051
  1341
      typedef MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1342
                                           DefStandardHeapTraits<H, CR> > 
deba@2051
  1343
      Create;
deba@2051
  1344
    };
deba@2051
  1345
deba@2051
  1346
    ///@}
deba@2051
  1347
deba@2051
  1348
deba@2051
  1349
    /// \brief Constructor.
deba@2051
  1350
    ///
deba@2051
  1351
    /// Constructor of the algorithm. 
deba@2051
  1352
    MinCostMaxBipartiteMatching(const BpUGraph& _graph, 
deba@2051
  1353
                                 const CostMap& _cost) 
deba@2051
  1354
      : graph(&_graph), cost(&_cost),
deba@2051
  1355
        anode_matching(_graph), bnode_matching(_graph),
deba@2051
  1356
        anode_potential(_graph), bnode_potential(_graph),
deba@2051
  1357
        _heap_cross_ref(0), local_heap_cross_ref(false),
deba@2051
  1358
        _heap(0), local_heap(0) {}
deba@2051
  1359
deba@2051
  1360
    /// \brief Destructor.
deba@2051
  1361
    ///
deba@2051
  1362
    /// Destructor of the algorithm.
deba@2051
  1363
    ~MinCostMaxBipartiteMatching() {
deba@2051
  1364
      destroyStructures();
deba@2051
  1365
    }
deba@2051
  1366
deba@2051
  1367
    /// \brief Sets the heap and the cross reference used by algorithm.
deba@2051
  1368
    ///
deba@2051
  1369
    /// Sets the heap and the cross reference used by algorithm.
deba@2051
  1370
    /// If you don't use this function before calling \ref run(),
deba@2051
  1371
    /// it will allocate one. The destuctor deallocates this
deba@2051
  1372
    /// automatically allocated map, of course.
deba@2051
  1373
    /// \return \c (*this)
deba@2386
  1374
    MinCostMaxBipartiteMatching& heap(Heap& hp, HeapCrossRef &cr) {
deba@2051
  1375
      if(local_heap_cross_ref) {
deba@2051
  1376
	delete _heap_cross_ref;
deba@2051
  1377
	local_heap_cross_ref = false;
deba@2051
  1378
      }
deba@2386
  1379
      _heap_cross_ref = &cr;
deba@2051
  1380
      if(local_heap) {
deba@2051
  1381
	delete _heap;
deba@2051
  1382
	local_heap = false;
deba@2051
  1383
      }
deba@2386
  1384
      _heap = &hp;
deba@2051
  1385
      return *this;
deba@2051
  1386
    }
deba@2051
  1387
deba@2051
  1388
    /// \name Execution control
deba@2051
  1389
    /// The simplest way to execute the algorithm is to use
deba@2051
  1390
    /// one of the member functions called \c run().
deba@2051
  1391
    /// \n
deba@2051
  1392
    /// If you need more control on the execution,
deba@2051
  1393
    /// first you must call \ref init() or one alternative for it.
deba@2051
  1394
    /// Finally \ref start() will perform the matching computation or
deba@2051
  1395
    /// with step-by-step execution you can augment the solution.
deba@2051
  1396
deba@2051
  1397
    /// @{
deba@2051
  1398
deba@2051
  1399
    /// \brief Initalize the data structures.
deba@2051
  1400
    ///
deba@2051
  1401
    /// It initalizes the data structures and creates an empty matching.
deba@2051
  1402
    void init() {
deba@2051
  1403
      initStructures();
deba@2051
  1404
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1405
        anode_matching[it] = INVALID;
deba@2051
  1406
        anode_potential[it] = 0;
deba@2051
  1407
      }
deba@2051
  1408
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1409
        bnode_matching[it] = INVALID;
deba@2051
  1410
        bnode_potential[it] = 0;
deba@2051
  1411
      }
deba@2051
  1412
      matching_cost = 0;
deba@2051
  1413
      matching_size = 0;
deba@2051
  1414
    }
deba@2051
  1415
deba@2051
  1416
deba@2051
  1417
    /// \brief An augmenting phase of the costed matching algorithm
deba@2051
  1418
    ///
deba@2051
  1419
    /// It runs an augmenting phase of the matching algorithm. The
deba@2051
  1420
    /// phase finds the best augmenting path and augments only on this
deba@2051
  1421
    /// paths.
deba@2051
  1422
    ///
deba@2051
  1423
    /// The algorithm consists at most 
deba@2051
  1424
    /// of \f$ O(n) \f$ phase and one phase is \f$ O(n\log(n)+e) \f$ 
deba@2051
  1425
    /// long with Fibonacci heap or \f$ O((n+e)\log(n)) \f$ long 
deba@2051
  1426
    /// with binary heap.
deba@2051
  1427
    bool augment() {
deba@2051
  1428
deba@2051
  1429
      typename BpUGraph::template BNodeMap<Value> bdist(*graph);
deba@2051
  1430
      typename BpUGraph::template BNodeMap<UEdge> bpred(*graph, INVALID);
deba@2051
  1431
deba@2051
  1432
      Node bestNode = INVALID;
deba@2051
  1433
      Value bestValue = 0;
deba@2051
  1434
deba@2051
  1435
      _heap->clear();
deba@2051
  1436
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1437
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
deba@2051
  1438
      }
deba@2051
  1439
deba@2051
  1440
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1441
        if (anode_matching[it] == INVALID) {
deba@2051
  1442
          _heap->push(it, 0);
deba@2051
  1443
        }
deba@2051
  1444
      }
deba@2136
  1445
      Value bdistMax = 0;
deba@2051
  1446
deba@2051
  1447
      while (!_heap->empty()) {
deba@2051
  1448
        Node anode = _heap->top();
deba@2051
  1449
        Value avalue = _heap->prio();
deba@2051
  1450
        _heap->pop();
deba@2051
  1451
        for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2051
  1452
          if (jt == anode_matching[anode]) continue;
deba@2051
  1453
          Node bnode = graph->bNode(jt);
deba@2051
  1454
          Value bvalue = avalue + (*cost)[jt] + 
deba@2051
  1455
            anode_potential[anode] - bnode_potential[bnode];
deba@2550
  1456
          if (bvalue > bdistMax) {
deba@2550
  1457
            bdistMax = bvalue;
deba@2550
  1458
          }
deba@2051
  1459
          if (bpred[bnode] == INVALID || bvalue < bdist[bnode]) {
deba@2051
  1460
            bdist[bnode] = bvalue;
deba@2051
  1461
            bpred[bnode] = jt;
deba@2550
  1462
          } else continue;
deba@2051
  1463
          if (bnode_matching[bnode] != INVALID) {
deba@2051
  1464
            Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2051
  1465
            switch (_heap->state(newanode)) {
deba@2051
  1466
            case Heap::PRE_HEAP:
deba@2051
  1467
              _heap->push(newanode, bvalue);
deba@2051
  1468
              break;
deba@2051
  1469
            case Heap::IN_HEAP:
deba@2051
  1470
              if (bvalue < (*_heap)[newanode]) {
deba@2051
  1471
                _heap->decrease(newanode, bvalue);
deba@2051
  1472
              }
deba@2051
  1473
              break;
deba@2051
  1474
            case Heap::POST_HEAP:
deba@2051
  1475
              break;
deba@2051
  1476
            }
deba@2051
  1477
          } else {
deba@2051
  1478
            if (bestNode == INVALID || 
deba@2051
  1479
                bvalue + bnode_potential[bnode] < bestValue) {
deba@2051
  1480
              bestValue = bvalue + bnode_potential[bnode];
deba@2051
  1481
              bestNode = bnode;
deba@2051
  1482
            }
deba@2051
  1483
          }
deba@2051
  1484
        }
deba@2051
  1485
      }
deba@2051
  1486
deba@2051
  1487
      if (bestNode == INVALID) {
deba@2051
  1488
        return false;
deba@2051
  1489
      }
deba@2051
  1490
deba@2051
  1491
      matching_cost += bestValue;
deba@2051
  1492
      ++matching_size;
deba@2051
  1493
deba@2051
  1494
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1495
        if (bpred[it] != INVALID) {
deba@2051
  1496
          bnode_potential[it] += bdist[it];
deba@2136
  1497
        } else {
deba@2136
  1498
          bnode_potential[it] += bdistMax;
deba@2051
  1499
        }
deba@2051
  1500
      }
deba@2051
  1501
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1502
        if (anode_matching[it] != INVALID) {
deba@2051
  1503
          Node bnode = graph->bNode(anode_matching[it]);
deba@2051
  1504
          if (bpred[bnode] != INVALID) {
deba@2051
  1505
            anode_potential[it] += bdist[bnode];
deba@2136
  1506
          } else {
deba@2136
  1507
            anode_potential[it] += bdistMax;
deba@2051
  1508
          }
deba@2051
  1509
        }
deba@2051
  1510
      }
deba@2051
  1511
deba@2051
  1512
      while (bestNode != INVALID) {
deba@2051
  1513
        UEdge uedge = bpred[bestNode];
deba@2051
  1514
        Node anode = graph->aNode(uedge);
deba@2051
  1515
        
deba@2051
  1516
        bnode_matching[bestNode] = uedge;
deba@2051
  1517
        if (anode_matching[anode] != INVALID) {
deba@2051
  1518
          bestNode = graph->bNode(anode_matching[anode]);
deba@2051
  1519
        } else {
deba@2051
  1520
          bestNode = INVALID;
deba@2051
  1521
        }
deba@2051
  1522
        anode_matching[anode] = uedge;
deba@2051
  1523
      }
deba@2051
  1524
deba@2051
  1525
deba@2051
  1526
      return true;
deba@2051
  1527
    }
deba@2051
  1528
deba@2051
  1529
    /// \brief Starts the algorithm.
deba@2051
  1530
    ///
deba@2051
  1531
    /// Starts the algorithm. It runs augmenting phases until the
deba@2051
  1532
    /// optimal solution reached.
deba@2051
  1533
    void start() {
deba@2051
  1534
      while (augment()) {}
deba@2051
  1535
    }
deba@2051
  1536
deba@2051
  1537
    /// \brief Runs the algorithm.
deba@2051
  1538
    ///
deba@2051
  1539
    /// It just initalize the algorithm and then start it.
deba@2051
  1540
    void run() {
deba@2051
  1541
      init();
deba@2051
  1542
      start();
deba@2051
  1543
    }
deba@2051
  1544
deba@2051
  1545
    /// @}
deba@2051
  1546
deba@2051
  1547
    /// \name Query Functions
deba@2051
  1548
    /// The result of the %Matching algorithm can be obtained using these
deba@2051
  1549
    /// functions.\n
deba@2051
  1550
    /// Before the use of these functions,
deba@2051
  1551
    /// either run() or start() must be called.
deba@2051
  1552
    
deba@2051
  1553
    ///@{
deba@2051
  1554
deba@2051
  1555
    /// \brief Gives back the potential in the NodeMap
deba@2051
  1556
    ///
deba@2463
  1557
    /// Gives back the potential in the NodeMap. The matching is optimal
deba@2463
  1558
    /// with the current number of edges if \f$ \pi(a) + \pi(b) - w(ab) = 0 \f$
deba@2463
  1559
    /// for each matching edges and \f$ \pi(a) + \pi(b) - w(ab) \ge 0 \f$
deba@2463
  1560
    /// for each edges. 
deba@2051
  1561
    template <typename PotentialMap>
deba@2386
  1562
    void potential(PotentialMap& pt) const {
deba@2051
  1563
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1564
        pt.set(it, anode_potential[it]);
deba@2051
  1565
      }
deba@2051
  1566
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1567
        pt.set(it, bnode_potential[it]);
deba@2051
  1568
      }
deba@2051
  1569
    }
deba@2051
  1570
deba@2051
  1571
    /// \brief Set true all matching uedge in the map.
deba@2051
  1572
    /// 
deba@2051
  1573
    /// Set true all matching uedge in the map. It does not change the
deba@2051
  1574
    /// value mapped to the other uedges.
deba@2051
  1575
    /// \return The number of the matching edges.
deba@2051
  1576
    template <typename MatchingMap>
deba@2386
  1577
    int quickMatching(MatchingMap& mm) const {
deba@2051
  1578
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1579
        if (anode_matching[it] != INVALID) {
deba@2463
  1580
          mm.set(anode_matching[it], true);
deba@2051
  1581
        }
deba@2051
  1582
      }
deba@2051
  1583
      return matching_size;
deba@2051
  1584
    }
deba@2051
  1585
deba@2051
  1586
    /// \brief Set true all matching uedge in the map and the others to false.
deba@2051
  1587
    /// 
deba@2051
  1588
    /// Set true all matching uedge in the map and the others to false.
deba@2051
  1589
    /// \return The number of the matching edges.
deba@2051
  1590
    template <typename MatchingMap>
deba@2386
  1591
    int matching(MatchingMap& mm) const {
deba@2051
  1592
      for (UEdgeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1593
        mm.set(it, it == anode_matching[graph->aNode(it)]);
deba@2051
  1594
      }
deba@2051
  1595
      return matching_size;
deba@2051
  1596
    }
deba@2051
  1597
deba@2463
  1598
    /// \brief Gives back the matching in an ANodeMap.
deba@2463
  1599
    ///
deba@2463
  1600
    /// Gives back the matching in an ANodeMap. The parameter should
deba@2463
  1601
    /// be a write ANodeMap of UEdge values.
deba@2463
  1602
    /// \return The number of the matching edges.
deba@2463
  1603
    template<class MatchingMap>
deba@2463
  1604
    int aMatching(MatchingMap& mm) const {
deba@2463
  1605
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1606
        mm.set(it, anode_matching[it]);
deba@2463
  1607
      }
deba@2463
  1608
      return matching_size;
deba@2463
  1609
    }
deba@2463
  1610
deba@2463
  1611
    /// \brief Gives back the matching in a BNodeMap.
deba@2463
  1612
    ///
deba@2463
  1613
    /// Gives back the matching in a BNodeMap. The parameter should
deba@2463
  1614
    /// be a write BNodeMap of UEdge values.
deba@2463
  1615
    /// \return The number of the matching edges.
deba@2463
  1616
    template<class MatchingMap>
deba@2463
  1617
    int bMatching(MatchingMap& mm) const {
deba@2463
  1618
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2463
  1619
        mm.set(it, bnode_matching[it]);
deba@2463
  1620
      }
deba@2463
  1621
      return matching_size;
deba@2463
  1622
    }
deba@2051
  1623
deba@2051
  1624
    /// \brief Return true if the given uedge is in the matching.
deba@2051
  1625
    /// 
deba@2051
  1626
    /// It returns true if the given uedge is in the matching.
deba@2058
  1627
    bool matchingEdge(const UEdge& edge) const {
deba@2051
  1628
      return anode_matching[graph->aNode(edge)] == edge;
deba@2051
  1629
    }
deba@2051
  1630
deba@2051
  1631
    /// \brief Returns the matching edge from the node.
deba@2051
  1632
    /// 
deba@2051
  1633
    /// Returns the matching edge from the node. If there is not such
deba@2051
  1634
    /// edge it gives back \c INVALID.
deba@2058
  1635
    UEdge matchingEdge(const Node& node) const {
deba@2051
  1636
      if (graph->aNode(node)) {
deba@2051
  1637
        return anode_matching[node];
deba@2051
  1638
      } else {
deba@2051
  1639
        return bnode_matching[node];
deba@2051
  1640
      }
deba@2051
  1641
    }
deba@2051
  1642
deba@2051
  1643
    /// \brief Gives back the sum of costs of the matching edges.
deba@2051
  1644
    ///
deba@2051
  1645
    /// Gives back the sum of costs of the matching edges.
deba@2051
  1646
    Value matchingCost() const {
deba@2051
  1647
      return matching_cost;
deba@2051
  1648
    }
deba@2051
  1649
deba@2051
  1650
    /// \brief Gives back the number of the matching edges.
deba@2051
  1651
    ///
deba@2051
  1652
    /// Gives back the number of the matching edges.
deba@2051
  1653
    int matchingSize() const {
deba@2051
  1654
      return matching_size;
deba@2051
  1655
    }
deba@2051
  1656
deba@2051
  1657
    /// @}
deba@2051
  1658
deba@2051
  1659
  private:
deba@2051
  1660
deba@2051
  1661
    void initStructures() {
deba@2051
  1662
      if (!_heap_cross_ref) {
deba@2051
  1663
	local_heap_cross_ref = true;
deba@2051
  1664
	_heap_cross_ref = Traits::createHeapCrossRef(*graph);
deba@2051
  1665
      }
deba@2051
  1666
      if (!_heap) {
deba@2051
  1667
	local_heap = true;
deba@2051
  1668
	_heap = Traits::createHeap(*_heap_cross_ref);
deba@2051
  1669
      }
deba@2051
  1670
    }
deba@2051
  1671
deba@2051
  1672
    void destroyStructures() {
deba@2051
  1673
      if (local_heap_cross_ref) delete _heap_cross_ref;
deba@2051
  1674
      if (local_heap) delete _heap;
deba@2051
  1675
    }
deba@2051
  1676
deba@2051
  1677
deba@2051
  1678
  private:
deba@2051
  1679
    
deba@2051
  1680
    const BpUGraph *graph;
deba@2051
  1681
    const CostMap* cost;
deba@2051
  1682
deba@2051
  1683
    ANodeMatchingMap anode_matching;
deba@2051
  1684
    BNodeMatchingMap bnode_matching;
deba@2051
  1685
deba@2051
  1686
    ANodePotentialMap anode_potential;
deba@2051
  1687
    BNodePotentialMap bnode_potential;
deba@2051
  1688
deba@2051
  1689
    Value matching_cost;
deba@2051
  1690
    int matching_size;
deba@2051
  1691
deba@2051
  1692
    HeapCrossRef *_heap_cross_ref;
deba@2051
  1693
    bool local_heap_cross_ref;
deba@2051
  1694
deba@2051
  1695
    Heap *_heap;
deba@2051
  1696
    bool local_heap;
deba@2040
  1697
  
deba@2040
  1698
  };
deba@2040
  1699
deba@2058
  1700
  /// \ingroup matching
deba@2058
  1701
  ///
deba@2058
  1702
  /// \brief Minimum cost maximum cardinality bipartite matching
deba@2058
  1703
  ///
deba@2463
  1704
  /// This function calculates the maximum cardinality matching with
deba@2463
  1705
  /// minimum cost of a bipartite graph. It gives back the matching in
deba@2463
  1706
  /// an undirected edge map.
deba@2058
  1707
  ///
deba@2058
  1708
  /// \param graph The bipartite graph.
deba@2058
  1709
  /// \param cost The undirected edge map which contains the costs.
deba@2058
  1710
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1711
  /// the matching.
deba@2058
  1712
  /// \return The cost of the matching.
deba@2058
  1713
  template <typename BpUGraph, typename CostMap, typename MatchingMap>
deba@2058
  1714
  typename CostMap::Value 
deba@2058
  1715
  minCostMaxBipartiteMatching(const BpUGraph& graph, 
deba@2058
  1716
                              const CostMap& cost,
deba@2058
  1717
                              MatchingMap& matching) {
deba@2058
  1718
    MinCostMaxBipartiteMatching<BpUGraph, CostMap> 
deba@2058
  1719
      bpmatching(graph, cost);
deba@2058
  1720
    bpmatching.run();
deba@2058
  1721
    bpmatching.matching(matching);
deba@2058
  1722
    return bpmatching.matchingCost();
deba@2058
  1723
  }
deba@2058
  1724
deba@2040
  1725
}
deba@2040
  1726
deba@2040
  1727
#endif