lemon/bipartite_matching.h
author deba
Tue, 21 Aug 2007 13:22:21 +0000
changeset 2463 19651a04d056
parent 2462 7a096a6bf53a
child 2466 feb7974cf4ec
permissions -rw-r--r--
Query functions: aMatching and bMatching
Modified algorithm function interfaces
ANodeMap<UEdge> matching map
BNodeMap<bool> barrier map

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