lemon/bipartite_matching.h
author deba
Sat, 11 Aug 2007 16:34:41 +0000
changeset 2462 7a096a6bf53a
parent 2391 14a343be7a5a
child 2463 19651a04d056
permissions -rw-r--r--
Common interface for bipartite matchings
Some useful query function for push-relabel based matching

The naming should be rethink for these classes
for example: pr-ap prefix for push-relabel and augmenting path
algorithms
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@2462
   362
          mm[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@2462
   375
        mm[it] = it == anode_matching[graph->aNode(it)];
deba@2462
   376
      }
deba@2462
   377
      return matching_size;
deba@2462
   378
    }
deba@2462
   379
deba@2462
   380
deba@2462
   381
    /// \brief Return true if the given uedge is in the matching.
deba@2462
   382
    /// 
deba@2462
   383
    /// It returns true if the given uedge is in the matching.
deba@2462
   384
    bool matchingEdge(const UEdge& edge) const {
deba@2462
   385
      return anode_matching[graph->aNode(edge)] == edge;
deba@2462
   386
    }
deba@2462
   387
deba@2462
   388
    /// \brief Returns the matching edge from the node.
deba@2462
   389
    /// 
deba@2462
   390
    /// Returns the matching edge from the node. If there is not such
deba@2462
   391
    /// edge it gives back \c INVALID.
deba@2462
   392
    UEdge matchingEdge(const Node& node) const {
deba@2462
   393
      if (graph->aNode(node)) {
deba@2462
   394
        return anode_matching[node];
deba@2462
   395
      } else {
deba@2462
   396
        return bnode_matching[node];
deba@2462
   397
      }
deba@2462
   398
    }
deba@2462
   399
deba@2462
   400
    /// \brief Gives back the number of the matching edges.
deba@2462
   401
    ///
deba@2462
   402
    /// Gives back the number of the matching edges.
deba@2462
   403
    int matchingSize() const {
deba@2462
   404
      return matching_size;
deba@2462
   405
    }
deba@2462
   406
deba@2462
   407
    /// \brief Returns a minimum covering of the nodes.
deba@2040
   408
    ///
deba@2040
   409
    /// The minimum covering set problem is the dual solution of the
deba@2462
   410
    /// maximum bipartite matching. It provides a solution for this
deba@2040
   411
    /// problem what is proof of the optimality of the matching.
deba@2040
   412
    /// \return The size of the cover set.
deba@2040
   413
    template <typename CoverMap>
deba@2058
   414
    int coverSet(CoverMap& covering) const {
deba@2040
   415
deba@2040
   416
      typename Graph::template ANodeMap<bool> areached(*graph, false);
deba@2040
   417
      typename Graph::template BNodeMap<bool> breached(*graph, false);
deba@2040
   418
      
deba@2040
   419
      std::vector<Node> queue;
deba@2040
   420
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2040
   421
        if (anode_matching[it] == INVALID) {
deba@2040
   422
          queue.push_back(it);
deba@2040
   423
        }
deba@2040
   424
      }
deba@2040
   425
deba@2040
   426
      while (!queue.empty()) {
deba@2040
   427
        std::vector<Node> newqueue;
deba@2386
   428
        for (int i = 0; i < int(queue.size()); ++i) {
deba@2040
   429
          Node anode = queue[i];
deba@2040
   430
          for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2040
   431
            Node bnode = graph->bNode(jt);
deba@2040
   432
            if (breached[bnode]) continue;
deba@2040
   433
            breached[bnode] = true;
deba@2040
   434
            if (bnode_matching[bnode] != INVALID) {
deba@2040
   435
              Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2040
   436
              if (!areached[newanode]) {
deba@2040
   437
                areached[newanode] = true;
deba@2040
   438
                newqueue.push_back(newanode);
deba@2040
   439
              }
deba@2040
   440
            }
deba@2040
   441
          }
deba@2040
   442
        }
deba@2040
   443
        queue.swap(newqueue);
deba@2040
   444
      }
deba@2040
   445
deba@2040
   446
      int size = 0;
deba@2040
   447
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2040
   448
        covering[it] = !areached[it] && anode_matching[it] != INVALID;
deba@2040
   449
        if (!areached[it] && anode_matching[it] != INVALID) {
deba@2040
   450
          ++size;
deba@2040
   451
        }
deba@2040
   452
      }
deba@2040
   453
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2040
   454
        covering[it] = breached[it];
deba@2040
   455
        if (breached[it]) {
deba@2040
   456
          ++size;
deba@2040
   457
        }
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@2462
   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@2462
   471
      typename Graph::template ANodeMap<bool> areached(*graph, false);
deba@2462
   472
      typename Graph::template BNodeMap<bool> breached(*graph, false);
deba@2462
   473
      
deba@2462
   474
      std::vector<Node> queue;
deba@2040
   475
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2462
   476
        if (anode_matching[it] == INVALID) {
deba@2462
   477
          queue.push_back(it);
deba@2040
   478
        }
deba@2040
   479
      }
deba@2040
   480
deba@2462
   481
      while (!queue.empty()) {
deba@2462
   482
        std::vector<Node> newqueue;
deba@2462
   483
        for (int i = 0; i < int(queue.size()); ++i) {
deba@2462
   484
          Node anode = queue[i];
deba@2462
   485
          for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2462
   486
            Node bnode = graph->bNode(jt);
deba@2462
   487
            if (breached[bnode]) continue;
deba@2462
   488
            breached[bnode] = true;
deba@2462
   489
            if (bnode_matching[bnode] != INVALID) {
deba@2462
   490
              Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2462
   491
              if (!areached[newanode]) {
deba@2462
   492
                areached[newanode] = true;
deba@2462
   493
                newqueue.push_back(newanode);
deba@2462
   494
              }
deba@2462
   495
            }
deba@2462
   496
          }
deba@2462
   497
        }
deba@2462
   498
        queue.swap(newqueue);
deba@2040
   499
      }
deba@2040
   500
deba@2462
   501
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2462
   502
        barrier[it] = areached[it] || anode_matching[it] == INVALID;
deba@2040
   503
      }
deba@2040
   504
    }
deba@2040
   505
deba@2462
   506
    /// \brief Gives back a barrier on the B-nodes
deba@2462
   507
    
deba@2462
   508
    /// The barrier is s subset of the nodes on the same side of the
deba@2462
   509
    /// graph, which size minus its neighbours is exactly the
deba@2462
   510
    /// unmatched nodes on the B-side.  
deba@2462
   511
    /// \retval barrier A WriteMap on the BNodes with bool value.
deba@2462
   512
    template <typename BarrierMap>
deba@2462
   513
    void bBarrier(BarrierMap& barrier) const {
deba@2462
   514
deba@2462
   515
      typename Graph::template ANodeMap<bool> areached(*graph, false);
deba@2462
   516
      typename Graph::template BNodeMap<bool> breached(*graph, false);
deba@2462
   517
      
deba@2462
   518
      std::vector<Node> queue;
deba@2462
   519
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2462
   520
        if (anode_matching[it] == INVALID) {
deba@2462
   521
          queue.push_back(it);
deba@2462
   522
        }
deba@2462
   523
      }
deba@2462
   524
deba@2462
   525
      while (!queue.empty()) {
deba@2462
   526
        std::vector<Node> newqueue;
deba@2462
   527
        for (int i = 0; i < int(queue.size()); ++i) {
deba@2462
   528
          Node anode = queue[i];
deba@2462
   529
          for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2462
   530
            Node bnode = graph->bNode(jt);
deba@2462
   531
            if (breached[bnode]) continue;
deba@2462
   532
            breached[bnode] = true;
deba@2462
   533
            if (bnode_matching[bnode] != INVALID) {
deba@2462
   534
              Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2462
   535
              if (!areached[newanode]) {
deba@2462
   536
                areached[newanode] = true;
deba@2462
   537
                newqueue.push_back(newanode);
deba@2462
   538
              }
deba@2462
   539
            }
deba@2462
   540
          }
deba@2462
   541
        }
deba@2462
   542
        queue.swap(newqueue);
deba@2462
   543
      }
deba@2462
   544
deba@2462
   545
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2462
   546
        barrier[it] = !breached[it];
deba@2462
   547
      }
deba@2040
   548
    }
deba@2040
   549
deba@2040
   550
    /// @}
deba@2040
   551
deba@2040
   552
  private:
deba@2040
   553
deba@2040
   554
    ANodeMatchingMap anode_matching;
deba@2040
   555
    BNodeMatchingMap bnode_matching;
deba@2040
   556
    const Graph *graph;
deba@2040
   557
deba@2051
   558
    int matching_size;
deba@2051
   559
  
deba@2051
   560
  };
deba@2051
   561
deba@2058
   562
  /// \ingroup matching
deba@2058
   563
  ///
deba@2058
   564
  /// \brief Maximum cardinality bipartite matching
deba@2058
   565
  ///
deba@2058
   566
  /// This function calculates the maximum cardinality matching
deba@2058
   567
  /// in a bipartite graph. It gives back the matching in an undirected
deba@2058
   568
  /// edge map.
deba@2058
   569
  ///
deba@2058
   570
  /// \param graph The bipartite graph.
deba@2058
   571
  /// \retval matching The undirected edge map which will be set to 
deba@2058
   572
  /// the matching.
deba@2058
   573
  /// \return The size of the matching.
deba@2058
   574
  template <typename BpUGraph, typename MatchingMap>
deba@2058
   575
  int maxBipartiteMatching(const BpUGraph& graph, MatchingMap& matching) {
deba@2058
   576
    MaxBipartiteMatching<BpUGraph> bpmatching(graph);
deba@2058
   577
    bpmatching.run();
deba@2058
   578
    bpmatching.matching(matching);
deba@2058
   579
    return bpmatching.matchingSize();
deba@2058
   580
  }
deba@2058
   581
deba@2051
   582
  /// \brief Default traits class for weighted bipartite matching algoritms.
deba@2051
   583
  ///
deba@2051
   584
  /// Default traits class for weighted bipartite matching algoritms.
deba@2051
   585
  /// \param _BpUGraph The bipartite undirected graph type.
deba@2051
   586
  /// \param _WeightMap Type of weight map.
deba@2051
   587
  template <typename _BpUGraph, typename _WeightMap>
deba@2051
   588
  struct WeightedBipartiteMatchingDefaultTraits {
deba@2051
   589
    /// \brief The type of the weight of the undirected edges.
deba@2051
   590
    typedef typename _WeightMap::Value Value;
deba@2051
   591
deba@2051
   592
    /// The undirected bipartite graph type the algorithm runs on. 
deba@2051
   593
    typedef _BpUGraph BpUGraph;
deba@2051
   594
deba@2051
   595
    /// The map of the edges weights
deba@2051
   596
    typedef _WeightMap WeightMap;
deba@2051
   597
deba@2051
   598
    /// \brief The cross reference type used by heap.
deba@2051
   599
    ///
deba@2051
   600
    /// The cross reference type used by heap.
deba@2051
   601
    /// Usually it is \c Graph::NodeMap<int>.
deba@2051
   602
    typedef typename BpUGraph::template NodeMap<int> HeapCrossRef;
deba@2051
   603
deba@2051
   604
    /// \brief Instantiates a HeapCrossRef.
deba@2051
   605
    ///
deba@2051
   606
    /// This function instantiates a \ref HeapCrossRef. 
deba@2051
   607
    /// \param graph is the graph, to which we would like to define the 
deba@2051
   608
    /// HeapCrossRef.
deba@2051
   609
    static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
   610
      return new HeapCrossRef(graph);
deba@2051
   611
    }
deba@2051
   612
    
deba@2051
   613
    /// \brief The heap type used by weighted matching algorithms.
deba@2051
   614
    ///
deba@2051
   615
    /// The heap type used by weighted matching algorithms. It should
deba@2051
   616
    /// minimize the priorities and the heap's key type is the graph's
deba@2051
   617
    /// anode graph's node.
deba@2051
   618
    ///
deba@2051
   619
    /// \sa BinHeap
mqrelly@2263
   620
    typedef BinHeap<Value, HeapCrossRef> Heap;
deba@2051
   621
    
deba@2051
   622
    /// \brief Instantiates a Heap.
deba@2051
   623
    ///
deba@2051
   624
    /// This function instantiates a \ref Heap. 
deba@2051
   625
    /// \param crossref The cross reference of the heap.
deba@2051
   626
    static Heap *createHeap(HeapCrossRef& crossref) {
deba@2051
   627
      return new Heap(crossref);
deba@2051
   628
    }
deba@2051
   629
deba@2051
   630
  };
deba@2051
   631
deba@2051
   632
deba@2051
   633
  /// \ingroup matching
deba@2051
   634
  ///
deba@2051
   635
  /// \brief Bipartite Max Weighted Matching algorithm
deba@2051
   636
  ///
deba@2051
   637
  /// This class implements the bipartite Max Weighted Matching
deba@2051
   638
  /// algorithm.  It uses the successive shortest path algorithm to
deba@2051
   639
  /// calculate the maximum weighted matching in the bipartite
deba@2051
   640
  /// graph. The algorithm can be used also to calculate the maximum
deba@2051
   641
  /// cardinality maximum weighted matching. The time complexity
deba@2051
   642
  /// of the algorithm is \f$ O(ne\log(n)) \f$ with the default binary
deba@2051
   643
  /// heap implementation but this can be improved to 
deba@2051
   644
  /// \f$ O(n^2\log(n)+ne) \f$ if we use fibonacci heaps.
deba@2051
   645
  ///
deba@2051
   646
  /// The algorithm also provides a potential function on the nodes
deba@2051
   647
  /// which a dual solution of the matching algorithm and it can be
deba@2051
   648
  /// used to proof the optimality of the given pimal solution.
deba@2051
   649
#ifdef DOXYGEN
deba@2051
   650
  template <typename _BpUGraph, typename _WeightMap, typename _Traits>
deba@2051
   651
#else
deba@2051
   652
  template <typename _BpUGraph, 
deba@2051
   653
            typename _WeightMap = typename _BpUGraph::template UEdgeMap<int>,
deba@2051
   654
            typename _Traits = WeightedBipartiteMatchingDefaultTraits<_BpUGraph, _WeightMap> >
deba@2051
   655
#endif
deba@2051
   656
  class MaxWeightedBipartiteMatching {
deba@2051
   657
  public:
deba@2051
   658
deba@2051
   659
    typedef _Traits Traits;
deba@2051
   660
    typedef typename Traits::BpUGraph BpUGraph;
deba@2051
   661
    typedef typename Traits::WeightMap WeightMap;
deba@2051
   662
    typedef typename Traits::Value Value;
deba@2051
   663
deba@2051
   664
  protected:
deba@2051
   665
deba@2051
   666
    typedef typename Traits::HeapCrossRef HeapCrossRef;
deba@2051
   667
    typedef typename Traits::Heap Heap; 
deba@2051
   668
deba@2051
   669
    
deba@2051
   670
    typedef typename BpUGraph::Node Node;
deba@2051
   671
    typedef typename BpUGraph::ANodeIt ANodeIt;
deba@2051
   672
    typedef typename BpUGraph::BNodeIt BNodeIt;
deba@2051
   673
    typedef typename BpUGraph::UEdge UEdge;
deba@2051
   674
    typedef typename BpUGraph::UEdgeIt UEdgeIt;
deba@2051
   675
    typedef typename BpUGraph::IncEdgeIt IncEdgeIt;
deba@2051
   676
deba@2051
   677
    typedef typename BpUGraph::template ANodeMap<UEdge> ANodeMatchingMap;
deba@2051
   678
    typedef typename BpUGraph::template BNodeMap<UEdge> BNodeMatchingMap;
deba@2051
   679
deba@2051
   680
    typedef typename BpUGraph::template ANodeMap<Value> ANodePotentialMap;
deba@2051
   681
    typedef typename BpUGraph::template BNodeMap<Value> BNodePotentialMap;
deba@2051
   682
deba@2051
   683
deba@2051
   684
  public:
deba@2051
   685
deba@2051
   686
    /// \brief \ref Exception for uninitialized parameters.
deba@2051
   687
    ///
deba@2051
   688
    /// This error represents problems in the initialization
deba@2051
   689
    /// of the parameters of the algorithms.
deba@2051
   690
    class UninitializedParameter : public lemon::UninitializedParameter {
deba@2051
   691
    public:
alpar@2151
   692
      virtual const char* what() const throw() {
deba@2051
   693
	return "lemon::MaxWeightedBipartiteMatching::UninitializedParameter";
deba@2051
   694
      }
deba@2051
   695
    };
deba@2051
   696
deba@2051
   697
    ///\name Named template parameters
deba@2051
   698
deba@2051
   699
    ///@{
deba@2051
   700
deba@2051
   701
    template <class H, class CR>
deba@2051
   702
    struct DefHeapTraits : public Traits {
deba@2051
   703
      typedef CR HeapCrossRef;
deba@2051
   704
      typedef H Heap;
deba@2051
   705
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &) {
deba@2051
   706
	throw UninitializedParameter();
deba@2051
   707
      }
deba@2051
   708
      static Heap *createHeap(HeapCrossRef &) {
deba@2051
   709
	throw UninitializedParameter();
deba@2051
   710
      }
deba@2051
   711
    };
deba@2051
   712
deba@2051
   713
    /// \brief \ref named-templ-param "Named parameter" for setting heap 
deba@2051
   714
    /// and cross reference type
deba@2051
   715
    ///
deba@2051
   716
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
   717
    /// reference type
deba@2051
   718
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
   719
    struct DefHeap
deba@2051
   720
      : public MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   721
                                            DefHeapTraits<H, CR> > { 
deba@2051
   722
      typedef MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   723
                                           DefHeapTraits<H, CR> > Create;
deba@2051
   724
    };
deba@2051
   725
deba@2051
   726
    template <class H, class CR>
deba@2051
   727
    struct DefStandardHeapTraits : public Traits {
deba@2051
   728
      typedef CR HeapCrossRef;
deba@2051
   729
      typedef H Heap;
deba@2051
   730
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
   731
	return new HeapCrossRef(graph);
deba@2051
   732
      }
deba@2051
   733
      static Heap *createHeap(HeapCrossRef &crossref) {
deba@2051
   734
	return new Heap(crossref);
deba@2051
   735
      }
deba@2051
   736
    };
deba@2051
   737
deba@2051
   738
    /// \brief \ref named-templ-param "Named parameter" for setting heap and 
deba@2051
   739
    /// cross reference type with automatic allocation
deba@2051
   740
    ///
deba@2051
   741
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
   742
    /// reference type. It can allocate the heap and the cross reference 
deba@2051
   743
    /// object if the cross reference's constructor waits for the graph as 
deba@2051
   744
    /// parameter and the heap's constructor waits for the cross reference.
deba@2051
   745
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
   746
    struct DefStandardHeap
deba@2051
   747
      : public MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   748
                                            DefStandardHeapTraits<H, CR> > { 
deba@2051
   749
      typedef MaxWeightedBipartiteMatching<BpUGraph, WeightMap, 
deba@2051
   750
                                           DefStandardHeapTraits<H, CR> > 
deba@2051
   751
      Create;
deba@2051
   752
    };
deba@2051
   753
deba@2051
   754
    ///@}
deba@2051
   755
deba@2051
   756
deba@2051
   757
    /// \brief Constructor.
deba@2051
   758
    ///
deba@2051
   759
    /// Constructor of the algorithm. 
deba@2051
   760
    MaxWeightedBipartiteMatching(const BpUGraph& _graph, 
deba@2051
   761
                                 const WeightMap& _weight) 
deba@2051
   762
      : graph(&_graph), weight(&_weight),
deba@2051
   763
        anode_matching(_graph), bnode_matching(_graph),
deba@2051
   764
        anode_potential(_graph), bnode_potential(_graph),
deba@2051
   765
        _heap_cross_ref(0), local_heap_cross_ref(false),
deba@2051
   766
        _heap(0), local_heap(0) {}
deba@2051
   767
deba@2051
   768
    /// \brief Destructor.
deba@2051
   769
    ///
deba@2051
   770
    /// Destructor of the algorithm.
deba@2051
   771
    ~MaxWeightedBipartiteMatching() {
deba@2051
   772
      destroyStructures();
deba@2051
   773
    }
deba@2051
   774
deba@2051
   775
    /// \brief Sets the heap and the cross reference used by algorithm.
deba@2051
   776
    ///
deba@2051
   777
    /// Sets the heap and the cross reference used by algorithm.
deba@2051
   778
    /// If you don't use this function before calling \ref run(),
deba@2051
   779
    /// it will allocate one. The destuctor deallocates this
deba@2051
   780
    /// automatically allocated map, of course.
deba@2051
   781
    /// \return \c (*this)
deba@2386
   782
    MaxWeightedBipartiteMatching& heap(Heap& hp, HeapCrossRef &cr) {
deba@2051
   783
      if(local_heap_cross_ref) {
deba@2051
   784
	delete _heap_cross_ref;
deba@2051
   785
	local_heap_cross_ref = false;
deba@2051
   786
      }
deba@2386
   787
      _heap_cross_ref = &cr;
deba@2051
   788
      if(local_heap) {
deba@2051
   789
	delete _heap;
deba@2051
   790
	local_heap = false;
deba@2051
   791
      }
deba@2386
   792
      _heap = &hp;
deba@2051
   793
      return *this;
deba@2051
   794
    }
deba@2051
   795
deba@2051
   796
    /// \name Execution control
deba@2051
   797
    /// The simplest way to execute the algorithm is to use
deba@2051
   798
    /// one of the member functions called \c run().
deba@2051
   799
    /// \n
deba@2051
   800
    /// If you need more control on the execution,
deba@2051
   801
    /// first you must call \ref init() or one alternative for it.
deba@2051
   802
    /// Finally \ref start() will perform the matching computation or
deba@2051
   803
    /// with step-by-step execution you can augment the solution.
deba@2051
   804
deba@2051
   805
    /// @{
deba@2051
   806
deba@2051
   807
    /// \brief Initalize the data structures.
deba@2051
   808
    ///
deba@2051
   809
    /// It initalizes the data structures and creates an empty matching.
deba@2051
   810
    void init() {
deba@2051
   811
      initStructures();
deba@2051
   812
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   813
        anode_matching[it] = INVALID;
deba@2051
   814
        anode_potential[it] = 0;
deba@2051
   815
      }
deba@2051
   816
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   817
        bnode_matching[it] = INVALID;
deba@2051
   818
        bnode_potential[it] = 0;
deba@2051
   819
        for (IncEdgeIt jt(*graph, it); jt != INVALID; ++jt) {
deba@2058
   820
          if ((*weight)[jt] > bnode_potential[it]) {
deba@2058
   821
            bnode_potential[it] = (*weight)[jt];
deba@2051
   822
          }
deba@2051
   823
        }
deba@2051
   824
      }
deba@2051
   825
      matching_value = 0;
deba@2051
   826
      matching_size = 0;
deba@2051
   827
    }
deba@2051
   828
deba@2051
   829
deba@2051
   830
    /// \brief An augmenting phase of the weighted matching algorithm
deba@2051
   831
    ///
deba@2051
   832
    /// It runs an augmenting phase of the weighted matching 
alpar@2352
   833
    /// algorithm. This phase finds the best augmenting path and 
deba@2051
   834
    /// augments only on this paths. 
deba@2051
   835
    ///
deba@2051
   836
    /// The algorithm consists at most 
deba@2051
   837
    /// of \f$ O(n) \f$ phase and one phase is \f$ O(n\log(n)+e) \f$ 
deba@2051
   838
    /// long with Fibonacci heap or \f$ O((n+e)\log(n)) \f$ long 
deba@2051
   839
    /// with binary heap.
deba@2051
   840
    /// \param decrease If the given parameter true the matching value
deba@2051
   841
    /// can be decreased in the augmenting phase. If we would like
deba@2051
   842
    /// to calculate the maximum cardinality maximum weighted matching
deba@2051
   843
    /// then we should let the algorithm to decrease the matching
deba@2051
   844
    /// value in order to increase the number of the matching edges.
deba@2051
   845
    bool augment(bool decrease = false) {
deba@2051
   846
deba@2051
   847
      typename BpUGraph::template BNodeMap<Value> bdist(*graph);
deba@2051
   848
      typename BpUGraph::template BNodeMap<UEdge> bpred(*graph, INVALID);
deba@2051
   849
deba@2051
   850
      Node bestNode = INVALID;
deba@2051
   851
      Value bestValue = 0;
deba@2051
   852
deba@2051
   853
      _heap->clear();
deba@2051
   854
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   855
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
deba@2051
   856
      }
deba@2051
   857
deba@2051
   858
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   859
        if (anode_matching[it] == INVALID) {
deba@2051
   860
          _heap->push(it, 0);
deba@2051
   861
        }
deba@2051
   862
      }
deba@2051
   863
deba@2051
   864
      Value bdistMax = 0;
deba@2051
   865
      while (!_heap->empty()) {
deba@2051
   866
        Node anode = _heap->top();
deba@2051
   867
        Value avalue = _heap->prio();
deba@2051
   868
        _heap->pop();
deba@2051
   869
        for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2051
   870
          if (jt == anode_matching[anode]) continue;
deba@2051
   871
          Node bnode = graph->bNode(jt);
deba@2058
   872
          Value bvalue = avalue  - (*weight)[jt] +
deba@2058
   873
            anode_potential[anode] + bnode_potential[bnode];
deba@2051
   874
          if (bpred[bnode] == INVALID || bvalue < bdist[bnode]) {
deba@2051
   875
            bdist[bnode] = bvalue;
deba@2051
   876
            bpred[bnode] = jt;
deba@2051
   877
          }
deba@2051
   878
          if (bvalue > bdistMax) {
deba@2051
   879
            bdistMax = bvalue;
deba@2051
   880
          }
deba@2051
   881
          if (bnode_matching[bnode] != INVALID) {
deba@2051
   882
            Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2051
   883
            switch (_heap->state(newanode)) {
deba@2051
   884
            case Heap::PRE_HEAP:
deba@2051
   885
              _heap->push(newanode, bvalue);
deba@2051
   886
              break;
deba@2051
   887
            case Heap::IN_HEAP:
deba@2051
   888
              if (bvalue < (*_heap)[newanode]) {
deba@2051
   889
                _heap->decrease(newanode, bvalue);
deba@2051
   890
              }
deba@2051
   891
              break;
deba@2051
   892
            case Heap::POST_HEAP:
deba@2051
   893
              break;
deba@2051
   894
            }
deba@2051
   895
          } else {
deba@2051
   896
            if (bestNode == INVALID || 
deba@2058
   897
                bnode_potential[bnode] - bvalue > bestValue) {
deba@2058
   898
              bestValue = bnode_potential[bnode] - bvalue;
deba@2051
   899
              bestNode = bnode;
deba@2051
   900
            }
deba@2051
   901
          }
deba@2051
   902
        }
deba@2051
   903
      }
deba@2051
   904
deba@2051
   905
      if (bestNode == INVALID || (!decrease && bestValue < 0)) {
deba@2051
   906
        return false;
deba@2051
   907
      }
deba@2051
   908
deba@2051
   909
      matching_value += bestValue;
deba@2051
   910
      ++matching_size;
deba@2051
   911
deba@2051
   912
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   913
        if (bpred[it] != INVALID) {
deba@2058
   914
          bnode_potential[it] -= bdist[it];
deba@2051
   915
        } else {
deba@2058
   916
          bnode_potential[it] -= bdistMax;
deba@2051
   917
        }
deba@2051
   918
      }
deba@2051
   919
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
   920
        if (anode_matching[it] != INVALID) {
deba@2051
   921
          Node bnode = graph->bNode(anode_matching[it]);
deba@2051
   922
          if (bpred[bnode] != INVALID) {
deba@2051
   923
            anode_potential[it] += bdist[bnode];
deba@2051
   924
          } else {
deba@2051
   925
            anode_potential[it] += bdistMax;
deba@2051
   926
          }
deba@2051
   927
        }
deba@2051
   928
      }
deba@2051
   929
deba@2051
   930
      while (bestNode != INVALID) {
deba@2051
   931
        UEdge uedge = bpred[bestNode];
deba@2051
   932
        Node anode = graph->aNode(uedge);
deba@2051
   933
        
deba@2051
   934
        bnode_matching[bestNode] = uedge;
deba@2051
   935
        if (anode_matching[anode] != INVALID) {
deba@2051
   936
          bestNode = graph->bNode(anode_matching[anode]);
deba@2051
   937
        } else {
deba@2051
   938
          bestNode = INVALID;
deba@2051
   939
        }
deba@2051
   940
        anode_matching[anode] = uedge;
deba@2051
   941
      }
deba@2051
   942
deba@2051
   943
deba@2051
   944
      return true;
deba@2051
   945
    }
deba@2051
   946
deba@2051
   947
    /// \brief Starts the algorithm.
deba@2051
   948
    ///
deba@2051
   949
    /// Starts the algorithm. It runs augmenting phases until the
deba@2051
   950
    /// optimal solution reached.
deba@2051
   951
    ///
deba@2051
   952
    /// \param maxCardinality If the given value is true it will
deba@2051
   953
    /// calculate the maximum cardinality maximum matching instead of
deba@2051
   954
    /// the maximum matching.
deba@2051
   955
    void start(bool maxCardinality = false) {
deba@2051
   956
      while (augment(maxCardinality)) {}
deba@2051
   957
    }
deba@2051
   958
deba@2051
   959
    /// \brief Runs the algorithm.
deba@2051
   960
    ///
deba@2051
   961
    /// It just initalize the algorithm and then start it.
deba@2051
   962
    ///
deba@2051
   963
    /// \param maxCardinality If the given value is true it will
deba@2051
   964
    /// calculate the maximum cardinality maximum matching instead of
deba@2051
   965
    /// the maximum matching.
deba@2051
   966
    void run(bool maxCardinality = false) {
deba@2051
   967
      init();
deba@2051
   968
      start(maxCardinality);
deba@2051
   969
    }
deba@2051
   970
deba@2051
   971
    /// @}
deba@2051
   972
deba@2051
   973
    /// \name Query Functions
deba@2051
   974
    /// The result of the %Matching algorithm can be obtained using these
deba@2051
   975
    /// functions.\n
deba@2051
   976
    /// Before the use of these functions,
deba@2051
   977
    /// either run() or start() must be called.
deba@2051
   978
    
deba@2051
   979
    ///@{
deba@2051
   980
deba@2051
   981
    /// \brief Gives back the potential in the NodeMap
deba@2051
   982
    ///
deba@2058
   983
    /// Gives back the potential in the NodeMap. The matching is optimal
deba@2058
   984
    /// with the current number of edges if \f$ \pi(a) + \pi(b) - w(ab) = 0 \f$
deba@2058
   985
    /// for each matching edges and \f$ \pi(a) + \pi(b) - w(ab) \ge 0 \f$
deba@2058
   986
    /// for each edges. 
deba@2051
   987
    template <typename PotentialMap>
deba@2386
   988
    void potential(PotentialMap& pt) const {
deba@2051
   989
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2386
   990
        pt[it] = anode_potential[it];
deba@2051
   991
      }
deba@2051
   992
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2386
   993
        pt[it] = bnode_potential[it];
deba@2051
   994
      }
deba@2051
   995
    }
deba@2051
   996
deba@2051
   997
    /// \brief Set true all matching uedge in the map.
deba@2051
   998
    /// 
deba@2051
   999
    /// Set true all matching uedge in the map. It does not change the
deba@2051
  1000
    /// value mapped to the other uedges.
deba@2051
  1001
    /// \return The number of the matching edges.
deba@2051
  1002
    template <typename MatchingMap>
deba@2386
  1003
    int quickMatching(MatchingMap& mm) const {
deba@2051
  1004
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1005
        if (anode_matching[it] != INVALID) {
deba@2386
  1006
          mm[anode_matching[it]] = true;
deba@2051
  1007
        }
deba@2051
  1008
      }
deba@2051
  1009
      return matching_size;
deba@2051
  1010
    }
deba@2051
  1011
deba@2051
  1012
    /// \brief Set true all matching uedge in the map and the others to false.
deba@2051
  1013
    /// 
deba@2051
  1014
    /// Set true all matching uedge in the map and the others to false.
deba@2051
  1015
    /// \return The number of the matching edges.
deba@2051
  1016
    template <typename MatchingMap>
deba@2386
  1017
    int matching(MatchingMap& mm) const {
deba@2051
  1018
      for (UEdgeIt it(*graph); it != INVALID; ++it) {
deba@2386
  1019
        mm[it] = it == anode_matching[graph->aNode(it)];
deba@2051
  1020
      }
deba@2051
  1021
      return matching_size;
deba@2051
  1022
    }
deba@2051
  1023
deba@2051
  1024
deba@2051
  1025
    /// \brief Return true if the given uedge is in the matching.
deba@2051
  1026
    /// 
deba@2051
  1027
    /// It returns true if the given uedge is in the matching.
deba@2058
  1028
    bool matchingEdge(const UEdge& edge) const {
deba@2051
  1029
      return anode_matching[graph->aNode(edge)] == edge;
deba@2051
  1030
    }
deba@2051
  1031
deba@2051
  1032
    /// \brief Returns the matching edge from the node.
deba@2051
  1033
    /// 
deba@2051
  1034
    /// Returns the matching edge from the node. If there is not such
deba@2051
  1035
    /// edge it gives back \c INVALID.
deba@2058
  1036
    UEdge matchingEdge(const Node& node) const {
deba@2051
  1037
      if (graph->aNode(node)) {
deba@2051
  1038
        return anode_matching[node];
deba@2051
  1039
      } else {
deba@2051
  1040
        return bnode_matching[node];
deba@2051
  1041
      }
deba@2051
  1042
    }
deba@2051
  1043
deba@2051
  1044
    /// \brief Gives back the sum of weights of the matching edges.
deba@2051
  1045
    ///
deba@2051
  1046
    /// Gives back the sum of weights of the matching edges.
deba@2051
  1047
    Value matchingValue() const {
deba@2051
  1048
      return matching_value;
deba@2051
  1049
    }
deba@2051
  1050
deba@2051
  1051
    /// \brief Gives back the number of the matching edges.
deba@2051
  1052
    ///
deba@2051
  1053
    /// Gives back the number of the matching edges.
deba@2051
  1054
    int matchingSize() const {
deba@2051
  1055
      return matching_size;
deba@2051
  1056
    }
deba@2051
  1057
deba@2051
  1058
    /// @}
deba@2051
  1059
deba@2051
  1060
  private:
deba@2051
  1061
deba@2051
  1062
    void initStructures() {
deba@2051
  1063
      if (!_heap_cross_ref) {
deba@2051
  1064
	local_heap_cross_ref = true;
deba@2051
  1065
	_heap_cross_ref = Traits::createHeapCrossRef(*graph);
deba@2051
  1066
      }
deba@2051
  1067
      if (!_heap) {
deba@2051
  1068
	local_heap = true;
deba@2051
  1069
	_heap = Traits::createHeap(*_heap_cross_ref);
deba@2051
  1070
      }
deba@2051
  1071
    }
deba@2051
  1072
deba@2051
  1073
    void destroyStructures() {
deba@2051
  1074
      if (local_heap_cross_ref) delete _heap_cross_ref;
deba@2051
  1075
      if (local_heap) delete _heap;
deba@2051
  1076
    }
deba@2051
  1077
deba@2051
  1078
deba@2051
  1079
  private:
deba@2051
  1080
    
deba@2051
  1081
    const BpUGraph *graph;
deba@2051
  1082
    const WeightMap* weight;
deba@2051
  1083
deba@2051
  1084
    ANodeMatchingMap anode_matching;
deba@2051
  1085
    BNodeMatchingMap bnode_matching;
deba@2051
  1086
deba@2051
  1087
    ANodePotentialMap anode_potential;
deba@2051
  1088
    BNodePotentialMap bnode_potential;
deba@2051
  1089
deba@2051
  1090
    Value matching_value;
deba@2051
  1091
    int matching_size;
deba@2051
  1092
deba@2051
  1093
    HeapCrossRef *_heap_cross_ref;
deba@2051
  1094
    bool local_heap_cross_ref;
deba@2051
  1095
deba@2051
  1096
    Heap *_heap;
deba@2051
  1097
    bool local_heap;
deba@2051
  1098
  
deba@2051
  1099
  };
deba@2051
  1100
deba@2058
  1101
  /// \ingroup matching
deba@2058
  1102
  ///
deba@2058
  1103
  /// \brief Maximum weighted bipartite matching
deba@2058
  1104
  ///
deba@2058
  1105
  /// This function calculates the maximum weighted matching
deba@2058
  1106
  /// in a bipartite graph. It gives back the matching in an undirected
deba@2058
  1107
  /// edge map.
deba@2058
  1108
  ///
deba@2058
  1109
  /// \param graph The bipartite graph.
deba@2058
  1110
  /// \param weight The undirected edge map which contains the weights.
deba@2058
  1111
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1112
  /// the matching.
deba@2058
  1113
  /// \return The value of the matching.
deba@2058
  1114
  template <typename BpUGraph, typename WeightMap, typename MatchingMap>
deba@2058
  1115
  typename WeightMap::Value 
deba@2058
  1116
  maxWeightedBipartiteMatching(const BpUGraph& graph, const WeightMap& weight,
deba@2058
  1117
                               MatchingMap& matching) {
deba@2058
  1118
    MaxWeightedBipartiteMatching<BpUGraph, WeightMap> 
deba@2058
  1119
      bpmatching(graph, weight);
deba@2058
  1120
    bpmatching.run();
deba@2058
  1121
    bpmatching.matching(matching);
deba@2058
  1122
    return bpmatching.matchingValue();
deba@2058
  1123
  }
deba@2058
  1124
deba@2058
  1125
  /// \ingroup matching
deba@2058
  1126
  ///
deba@2058
  1127
  /// \brief Maximum weighted maximum cardinality bipartite matching
deba@2058
  1128
  ///
deba@2058
  1129
  /// This function calculates the maximum weighted of the maximum cardinality
deba@2058
  1130
  /// matchings of a bipartite graph. It gives back the matching in an 
deba@2058
  1131
  /// undirected edge map.
deba@2058
  1132
  ///
deba@2058
  1133
  /// \param graph The bipartite graph.
deba@2058
  1134
  /// \param weight The undirected edge map which contains the weights.
deba@2058
  1135
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1136
  /// the matching.
deba@2058
  1137
  /// \return The value of the matching.
deba@2058
  1138
  template <typename BpUGraph, typename WeightMap, typename MatchingMap>
deba@2058
  1139
  typename WeightMap::Value 
deba@2058
  1140
  maxWeightedMaxBipartiteMatching(const BpUGraph& graph, 
deba@2058
  1141
                                  const WeightMap& weight,
deba@2058
  1142
                                  MatchingMap& matching) {
deba@2058
  1143
    MaxWeightedBipartiteMatching<BpUGraph, WeightMap> 
deba@2058
  1144
      bpmatching(graph, weight);
deba@2058
  1145
    bpmatching.run(true);
deba@2058
  1146
    bpmatching.matching(matching);
deba@2058
  1147
    return bpmatching.matchingValue();
deba@2058
  1148
  }
deba@2058
  1149
deba@2051
  1150
  /// \brief Default traits class for minimum cost bipartite matching
deba@2051
  1151
  /// algoritms.
deba@2051
  1152
  ///
deba@2051
  1153
  /// Default traits class for minimum cost bipartite matching
deba@2051
  1154
  /// algoritms.  
deba@2051
  1155
  ///
deba@2051
  1156
  /// \param _BpUGraph The bipartite undirected graph
deba@2051
  1157
  /// type.  
deba@2051
  1158
  ///
deba@2051
  1159
  /// \param _CostMap Type of cost map.
deba@2051
  1160
  template <typename _BpUGraph, typename _CostMap>
deba@2051
  1161
  struct MinCostMaxBipartiteMatchingDefaultTraits {
deba@2051
  1162
    /// \brief The type of the cost of the undirected edges.
deba@2051
  1163
    typedef typename _CostMap::Value Value;
deba@2051
  1164
deba@2051
  1165
    /// The undirected bipartite graph type the algorithm runs on. 
deba@2051
  1166
    typedef _BpUGraph BpUGraph;
deba@2051
  1167
deba@2051
  1168
    /// The map of the edges costs
deba@2051
  1169
    typedef _CostMap CostMap;
deba@2051
  1170
deba@2051
  1171
    /// \brief The cross reference type used by heap.
deba@2051
  1172
    ///
deba@2051
  1173
    /// The cross reference type used by heap.
deba@2051
  1174
    /// Usually it is \c Graph::NodeMap<int>.
deba@2051
  1175
    typedef typename BpUGraph::template NodeMap<int> HeapCrossRef;
deba@2051
  1176
deba@2051
  1177
    /// \brief Instantiates a HeapCrossRef.
deba@2051
  1178
    ///
deba@2051
  1179
    /// This function instantiates a \ref HeapCrossRef. 
deba@2051
  1180
    /// \param graph is the graph, to which we would like to define the 
deba@2051
  1181
    /// HeapCrossRef.
deba@2051
  1182
    static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
  1183
      return new HeapCrossRef(graph);
deba@2051
  1184
    }
deba@2051
  1185
    
deba@2051
  1186
    /// \brief The heap type used by costed matching algorithms.
deba@2051
  1187
    ///
deba@2051
  1188
    /// The heap type used by costed matching algorithms. It should
deba@2051
  1189
    /// minimize the priorities and the heap's key type is the graph's
deba@2051
  1190
    /// anode graph's node.
deba@2051
  1191
    ///
deba@2051
  1192
    /// \sa BinHeap
deba@2269
  1193
    typedef BinHeap<Value, HeapCrossRef> Heap;
deba@2051
  1194
    
deba@2051
  1195
    /// \brief Instantiates a Heap.
deba@2051
  1196
    ///
deba@2051
  1197
    /// This function instantiates a \ref Heap. 
deba@2051
  1198
    /// \param crossref The cross reference of the heap.
deba@2051
  1199
    static Heap *createHeap(HeapCrossRef& crossref) {
deba@2051
  1200
      return new Heap(crossref);
deba@2051
  1201
    }
deba@2051
  1202
deba@2051
  1203
  };
deba@2051
  1204
deba@2051
  1205
deba@2051
  1206
  /// \ingroup matching
deba@2051
  1207
  ///
deba@2051
  1208
  /// \brief Bipartite Min Cost Matching algorithm
deba@2051
  1209
  ///
deba@2051
  1210
  /// This class implements the bipartite Min Cost Matching algorithm.
deba@2051
  1211
  /// It uses the successive shortest path algorithm to calculate the
deba@2051
  1212
  /// minimum cost maximum matching in the bipartite graph. The time
deba@2051
  1213
  /// complexity of the algorithm is \f$ O(ne\log(n)) \f$ with the
deba@2051
  1214
  /// default binary heap implementation but this can be improved to
deba@2051
  1215
  /// \f$ O(n^2\log(n)+ne) \f$ if we use fibonacci heaps.
deba@2051
  1216
  ///
deba@2051
  1217
  /// The algorithm also provides a potential function on the nodes
deba@2051
  1218
  /// which a dual solution of the matching algorithm and it can be
deba@2051
  1219
  /// used to proof the optimality of the given pimal solution.
deba@2051
  1220
#ifdef DOXYGEN
deba@2051
  1221
  template <typename _BpUGraph, typename _CostMap, typename _Traits>
deba@2051
  1222
#else
deba@2051
  1223
  template <typename _BpUGraph, 
deba@2051
  1224
            typename _CostMap = typename _BpUGraph::template UEdgeMap<int>,
deba@2051
  1225
            typename _Traits = MinCostMaxBipartiteMatchingDefaultTraits<_BpUGraph, _CostMap> >
deba@2051
  1226
#endif
deba@2051
  1227
  class MinCostMaxBipartiteMatching {
deba@2051
  1228
  public:
deba@2051
  1229
deba@2051
  1230
    typedef _Traits Traits;
deba@2051
  1231
    typedef typename Traits::BpUGraph BpUGraph;
deba@2051
  1232
    typedef typename Traits::CostMap CostMap;
deba@2051
  1233
    typedef typename Traits::Value Value;
deba@2051
  1234
deba@2051
  1235
  protected:
deba@2051
  1236
deba@2051
  1237
    typedef typename Traits::HeapCrossRef HeapCrossRef;
deba@2051
  1238
    typedef typename Traits::Heap Heap; 
deba@2051
  1239
deba@2051
  1240
    
deba@2051
  1241
    typedef typename BpUGraph::Node Node;
deba@2051
  1242
    typedef typename BpUGraph::ANodeIt ANodeIt;
deba@2051
  1243
    typedef typename BpUGraph::BNodeIt BNodeIt;
deba@2051
  1244
    typedef typename BpUGraph::UEdge UEdge;
deba@2051
  1245
    typedef typename BpUGraph::UEdgeIt UEdgeIt;
deba@2051
  1246
    typedef typename BpUGraph::IncEdgeIt IncEdgeIt;
deba@2051
  1247
deba@2051
  1248
    typedef typename BpUGraph::template ANodeMap<UEdge> ANodeMatchingMap;
deba@2051
  1249
    typedef typename BpUGraph::template BNodeMap<UEdge> BNodeMatchingMap;
deba@2051
  1250
deba@2051
  1251
    typedef typename BpUGraph::template ANodeMap<Value> ANodePotentialMap;
deba@2051
  1252
    typedef typename BpUGraph::template BNodeMap<Value> BNodePotentialMap;
deba@2051
  1253
deba@2051
  1254
deba@2051
  1255
  public:
deba@2051
  1256
deba@2051
  1257
    /// \brief \ref Exception for uninitialized parameters.
deba@2051
  1258
    ///
deba@2051
  1259
    /// This error represents problems in the initialization
deba@2051
  1260
    /// of the parameters of the algorithms.
deba@2051
  1261
    class UninitializedParameter : public lemon::UninitializedParameter {
deba@2051
  1262
    public:
alpar@2151
  1263
      virtual const char* what() const throw() {
deba@2051
  1264
	return "lemon::MinCostMaxBipartiteMatching::UninitializedParameter";
deba@2051
  1265
      }
deba@2051
  1266
    };
deba@2051
  1267
deba@2051
  1268
    ///\name Named template parameters
deba@2051
  1269
deba@2051
  1270
    ///@{
deba@2051
  1271
deba@2051
  1272
    template <class H, class CR>
deba@2051
  1273
    struct DefHeapTraits : public Traits {
deba@2051
  1274
      typedef CR HeapCrossRef;
deba@2051
  1275
      typedef H Heap;
deba@2051
  1276
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &) {
deba@2051
  1277
	throw UninitializedParameter();
deba@2051
  1278
      }
deba@2051
  1279
      static Heap *createHeap(HeapCrossRef &) {
deba@2051
  1280
	throw UninitializedParameter();
deba@2051
  1281
      }
deba@2051
  1282
    };
deba@2051
  1283
deba@2051
  1284
    /// \brief \ref named-templ-param "Named parameter" for setting heap 
deba@2051
  1285
    /// and cross reference type
deba@2051
  1286
    ///
deba@2051
  1287
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
  1288
    /// reference type
deba@2051
  1289
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
  1290
    struct DefHeap
deba@2051
  1291
      : public MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1292
                                            DefHeapTraits<H, CR> > { 
deba@2051
  1293
      typedef MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1294
                                           DefHeapTraits<H, CR> > Create;
deba@2051
  1295
    };
deba@2051
  1296
deba@2051
  1297
    template <class H, class CR>
deba@2051
  1298
    struct DefStandardHeapTraits : public Traits {
deba@2051
  1299
      typedef CR HeapCrossRef;
deba@2051
  1300
      typedef H Heap;
deba@2051
  1301
      static HeapCrossRef *createHeapCrossRef(const BpUGraph &graph) {
deba@2051
  1302
	return new HeapCrossRef(graph);
deba@2051
  1303
      }
deba@2051
  1304
      static Heap *createHeap(HeapCrossRef &crossref) {
deba@2051
  1305
	return new Heap(crossref);
deba@2051
  1306
      }
deba@2051
  1307
    };
deba@2051
  1308
deba@2051
  1309
    /// \brief \ref named-templ-param "Named parameter" for setting heap and 
deba@2051
  1310
    /// cross reference type with automatic allocation
deba@2051
  1311
    ///
deba@2051
  1312
    /// \ref named-templ-param "Named parameter" for setting heap and cross 
deba@2051
  1313
    /// reference type. It can allocate the heap and the cross reference 
deba@2051
  1314
    /// object if the cross reference's constructor waits for the graph as 
deba@2051
  1315
    /// parameter and the heap's constructor waits for the cross reference.
deba@2051
  1316
    template <class H, class CR = typename BpUGraph::template NodeMap<int> >
deba@2051
  1317
    struct DefStandardHeap
deba@2051
  1318
      : public MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1319
                                            DefStandardHeapTraits<H, CR> > { 
deba@2051
  1320
      typedef MinCostMaxBipartiteMatching<BpUGraph, CostMap, 
deba@2051
  1321
                                           DefStandardHeapTraits<H, CR> > 
deba@2051
  1322
      Create;
deba@2051
  1323
    };
deba@2051
  1324
deba@2051
  1325
    ///@}
deba@2051
  1326
deba@2051
  1327
deba@2051
  1328
    /// \brief Constructor.
deba@2051
  1329
    ///
deba@2051
  1330
    /// Constructor of the algorithm. 
deba@2051
  1331
    MinCostMaxBipartiteMatching(const BpUGraph& _graph, 
deba@2051
  1332
                                 const CostMap& _cost) 
deba@2051
  1333
      : graph(&_graph), cost(&_cost),
deba@2051
  1334
        anode_matching(_graph), bnode_matching(_graph),
deba@2051
  1335
        anode_potential(_graph), bnode_potential(_graph),
deba@2051
  1336
        _heap_cross_ref(0), local_heap_cross_ref(false),
deba@2051
  1337
        _heap(0), local_heap(0) {}
deba@2051
  1338
deba@2051
  1339
    /// \brief Destructor.
deba@2051
  1340
    ///
deba@2051
  1341
    /// Destructor of the algorithm.
deba@2051
  1342
    ~MinCostMaxBipartiteMatching() {
deba@2051
  1343
      destroyStructures();
deba@2051
  1344
    }
deba@2051
  1345
deba@2051
  1346
    /// \brief Sets the heap and the cross reference used by algorithm.
deba@2051
  1347
    ///
deba@2051
  1348
    /// Sets the heap and the cross reference used by algorithm.
deba@2051
  1349
    /// If you don't use this function before calling \ref run(),
deba@2051
  1350
    /// it will allocate one. The destuctor deallocates this
deba@2051
  1351
    /// automatically allocated map, of course.
deba@2051
  1352
    /// \return \c (*this)
deba@2386
  1353
    MinCostMaxBipartiteMatching& heap(Heap& hp, HeapCrossRef &cr) {
deba@2051
  1354
      if(local_heap_cross_ref) {
deba@2051
  1355
	delete _heap_cross_ref;
deba@2051
  1356
	local_heap_cross_ref = false;
deba@2051
  1357
      }
deba@2386
  1358
      _heap_cross_ref = &cr;
deba@2051
  1359
      if(local_heap) {
deba@2051
  1360
	delete _heap;
deba@2051
  1361
	local_heap = false;
deba@2051
  1362
      }
deba@2386
  1363
      _heap = &hp;
deba@2051
  1364
      return *this;
deba@2051
  1365
    }
deba@2051
  1366
deba@2051
  1367
    /// \name Execution control
deba@2051
  1368
    /// The simplest way to execute the algorithm is to use
deba@2051
  1369
    /// one of the member functions called \c run().
deba@2051
  1370
    /// \n
deba@2051
  1371
    /// If you need more control on the execution,
deba@2051
  1372
    /// first you must call \ref init() or one alternative for it.
deba@2051
  1373
    /// Finally \ref start() will perform the matching computation or
deba@2051
  1374
    /// with step-by-step execution you can augment the solution.
deba@2051
  1375
deba@2051
  1376
    /// @{
deba@2051
  1377
deba@2051
  1378
    /// \brief Initalize the data structures.
deba@2051
  1379
    ///
deba@2051
  1380
    /// It initalizes the data structures and creates an empty matching.
deba@2051
  1381
    void init() {
deba@2051
  1382
      initStructures();
deba@2051
  1383
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1384
        anode_matching[it] = INVALID;
deba@2051
  1385
        anode_potential[it] = 0;
deba@2051
  1386
      }
deba@2051
  1387
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1388
        bnode_matching[it] = INVALID;
deba@2051
  1389
        bnode_potential[it] = 0;
deba@2051
  1390
      }
deba@2051
  1391
      matching_cost = 0;
deba@2051
  1392
      matching_size = 0;
deba@2051
  1393
    }
deba@2051
  1394
deba@2051
  1395
deba@2051
  1396
    /// \brief An augmenting phase of the costed matching algorithm
deba@2051
  1397
    ///
deba@2051
  1398
    /// It runs an augmenting phase of the matching algorithm. The
deba@2051
  1399
    /// phase finds the best augmenting path and augments only on this
deba@2051
  1400
    /// paths.
deba@2051
  1401
    ///
deba@2051
  1402
    /// The algorithm consists at most 
deba@2051
  1403
    /// of \f$ O(n) \f$ phase and one phase is \f$ O(n\log(n)+e) \f$ 
deba@2051
  1404
    /// long with Fibonacci heap or \f$ O((n+e)\log(n)) \f$ long 
deba@2051
  1405
    /// with binary heap.
deba@2051
  1406
    bool augment() {
deba@2051
  1407
deba@2051
  1408
      typename BpUGraph::template BNodeMap<Value> bdist(*graph);
deba@2051
  1409
      typename BpUGraph::template BNodeMap<UEdge> bpred(*graph, INVALID);
deba@2051
  1410
deba@2051
  1411
      Node bestNode = INVALID;
deba@2051
  1412
      Value bestValue = 0;
deba@2051
  1413
deba@2051
  1414
      _heap->clear();
deba@2051
  1415
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1416
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
deba@2051
  1417
      }
deba@2051
  1418
deba@2051
  1419
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1420
        if (anode_matching[it] == INVALID) {
deba@2051
  1421
          _heap->push(it, 0);
deba@2051
  1422
        }
deba@2051
  1423
      }
deba@2136
  1424
      Value bdistMax = 0;
deba@2051
  1425
deba@2051
  1426
      while (!_heap->empty()) {
deba@2051
  1427
        Node anode = _heap->top();
deba@2051
  1428
        Value avalue = _heap->prio();
deba@2051
  1429
        _heap->pop();
deba@2051
  1430
        for (IncEdgeIt jt(*graph, anode); jt != INVALID; ++jt) {
deba@2051
  1431
          if (jt == anode_matching[anode]) continue;
deba@2051
  1432
          Node bnode = graph->bNode(jt);
deba@2051
  1433
          Value bvalue = avalue + (*cost)[jt] + 
deba@2051
  1434
            anode_potential[anode] - bnode_potential[bnode];
deba@2051
  1435
          if (bpred[bnode] == INVALID || bvalue < bdist[bnode]) {
deba@2051
  1436
            bdist[bnode] = bvalue;
deba@2051
  1437
            bpred[bnode] = jt;
deba@2051
  1438
          }
deba@2136
  1439
          if (bvalue > bdistMax) {
deba@2136
  1440
            bdistMax = bvalue;
deba@2136
  1441
          }
deba@2051
  1442
          if (bnode_matching[bnode] != INVALID) {
deba@2051
  1443
            Node newanode = graph->aNode(bnode_matching[bnode]);
deba@2051
  1444
            switch (_heap->state(newanode)) {
deba@2051
  1445
            case Heap::PRE_HEAP:
deba@2051
  1446
              _heap->push(newanode, bvalue);
deba@2051
  1447
              break;
deba@2051
  1448
            case Heap::IN_HEAP:
deba@2051
  1449
              if (bvalue < (*_heap)[newanode]) {
deba@2051
  1450
                _heap->decrease(newanode, bvalue);
deba@2051
  1451
              }
deba@2051
  1452
              break;
deba@2051
  1453
            case Heap::POST_HEAP:
deba@2051
  1454
              break;
deba@2051
  1455
            }
deba@2051
  1456
          } else {
deba@2051
  1457
            if (bestNode == INVALID || 
deba@2051
  1458
                bvalue + bnode_potential[bnode] < bestValue) {
deba@2051
  1459
              bestValue = bvalue + bnode_potential[bnode];
deba@2051
  1460
              bestNode = bnode;
deba@2051
  1461
            }
deba@2051
  1462
          }
deba@2051
  1463
        }
deba@2051
  1464
      }
deba@2051
  1465
deba@2051
  1466
      if (bestNode == INVALID) {
deba@2051
  1467
        return false;
deba@2051
  1468
      }
deba@2051
  1469
deba@2051
  1470
      matching_cost += bestValue;
deba@2051
  1471
      ++matching_size;
deba@2051
  1472
deba@2051
  1473
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1474
        if (bpred[it] != INVALID) {
deba@2051
  1475
          bnode_potential[it] += bdist[it];
deba@2136
  1476
        } else {
deba@2136
  1477
          bnode_potential[it] += bdistMax;
deba@2051
  1478
        }
deba@2051
  1479
      }
deba@2051
  1480
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1481
        if (anode_matching[it] != INVALID) {
deba@2051
  1482
          Node bnode = graph->bNode(anode_matching[it]);
deba@2051
  1483
          if (bpred[bnode] != INVALID) {
deba@2051
  1484
            anode_potential[it] += bdist[bnode];
deba@2136
  1485
          } else {
deba@2136
  1486
            anode_potential[it] += bdistMax;
deba@2051
  1487
          }
deba@2051
  1488
        }
deba@2051
  1489
      }
deba@2051
  1490
deba@2051
  1491
      while (bestNode != INVALID) {
deba@2051
  1492
        UEdge uedge = bpred[bestNode];
deba@2051
  1493
        Node anode = graph->aNode(uedge);
deba@2051
  1494
        
deba@2051
  1495
        bnode_matching[bestNode] = uedge;
deba@2051
  1496
        if (anode_matching[anode] != INVALID) {
deba@2051
  1497
          bestNode = graph->bNode(anode_matching[anode]);
deba@2051
  1498
        } else {
deba@2051
  1499
          bestNode = INVALID;
deba@2051
  1500
        }
deba@2051
  1501
        anode_matching[anode] = uedge;
deba@2051
  1502
      }
deba@2051
  1503
deba@2051
  1504
deba@2051
  1505
      return true;
deba@2051
  1506
    }
deba@2051
  1507
deba@2051
  1508
    /// \brief Starts the algorithm.
deba@2051
  1509
    ///
deba@2051
  1510
    /// Starts the algorithm. It runs augmenting phases until the
deba@2051
  1511
    /// optimal solution reached.
deba@2051
  1512
    void start() {
deba@2051
  1513
      while (augment()) {}
deba@2051
  1514
    }
deba@2051
  1515
deba@2051
  1516
    /// \brief Runs the algorithm.
deba@2051
  1517
    ///
deba@2051
  1518
    /// It just initalize the algorithm and then start it.
deba@2051
  1519
    void run() {
deba@2051
  1520
      init();
deba@2051
  1521
      start();
deba@2051
  1522
    }
deba@2051
  1523
deba@2051
  1524
    /// @}
deba@2051
  1525
deba@2051
  1526
    /// \name Query Functions
deba@2051
  1527
    /// The result of the %Matching algorithm can be obtained using these
deba@2051
  1528
    /// functions.\n
deba@2051
  1529
    /// Before the use of these functions,
deba@2051
  1530
    /// either run() or start() must be called.
deba@2051
  1531
    
deba@2051
  1532
    ///@{
deba@2051
  1533
deba@2051
  1534
    /// \brief Gives back the potential in the NodeMap
deba@2051
  1535
    ///
deba@2058
  1536
    /// Gives back the potential in the NodeMap. The potential is optimal with 
deba@2058
  1537
    /// the current number of edges if \f$ \pi(a) - \pi(b) + w(ab) = 0 \f$ for
deba@2051
  1538
    /// each matching edges and \f$ \pi(a) - \pi(b) + w(ab) \ge 0 \f$
deba@2051
  1539
    /// for each edges.
deba@2051
  1540
    template <typename PotentialMap>
deba@2386
  1541
    void potential(PotentialMap& pt) const {
deba@2051
  1542
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2386
  1543
        pt[it] = anode_potential[it];
deba@2051
  1544
      }
deba@2051
  1545
      for (BNodeIt it(*graph); it != INVALID; ++it) {
deba@2386
  1546
        pt[it] = bnode_potential[it];
deba@2051
  1547
      }
deba@2051
  1548
    }
deba@2051
  1549
deba@2051
  1550
    /// \brief Set true all matching uedge in the map.
deba@2051
  1551
    /// 
deba@2051
  1552
    /// Set true all matching uedge in the map. It does not change the
deba@2051
  1553
    /// value mapped to the other uedges.
deba@2051
  1554
    /// \return The number of the matching edges.
deba@2051
  1555
    template <typename MatchingMap>
deba@2386
  1556
    int quickMatching(MatchingMap& mm) const {
deba@2051
  1557
      for (ANodeIt it(*graph); it != INVALID; ++it) {
deba@2051
  1558
        if (anode_matching[it] != INVALID) {
deba@2386
  1559
          mm[anode_matching[it]] = true;
deba@2051
  1560
        }
deba@2051
  1561
      }
deba@2051
  1562
      return matching_size;
deba@2051
  1563
    }
deba@2051
  1564
deba@2051
  1565
    /// \brief Set true all matching uedge in the map and the others to false.
deba@2051
  1566
    /// 
deba@2051
  1567
    /// Set true all matching uedge in the map and the others to false.
deba@2051
  1568
    /// \return The number of the matching edges.
deba@2051
  1569
    template <typename MatchingMap>
deba@2386
  1570
    int matching(MatchingMap& mm) const {
deba@2051
  1571
      for (UEdgeIt it(*graph); it != INVALID; ++it) {
deba@2386
  1572
        mm[it] = it == anode_matching[graph->aNode(it)];
deba@2051
  1573
      }
deba@2051
  1574
      return matching_size;
deba@2051
  1575
    }
deba@2051
  1576
deba@2051
  1577
deba@2051
  1578
    /// \brief Return true if the given uedge is in the matching.
deba@2051
  1579
    /// 
deba@2051
  1580
    /// It returns true if the given uedge is in the matching.
deba@2058
  1581
    bool matchingEdge(const UEdge& edge) const {
deba@2051
  1582
      return anode_matching[graph->aNode(edge)] == edge;
deba@2051
  1583
    }
deba@2051
  1584
deba@2051
  1585
    /// \brief Returns the matching edge from the node.
deba@2051
  1586
    /// 
deba@2051
  1587
    /// Returns the matching edge from the node. If there is not such
deba@2051
  1588
    /// edge it gives back \c INVALID.
deba@2058
  1589
    UEdge matchingEdge(const Node& node) const {
deba@2051
  1590
      if (graph->aNode(node)) {
deba@2051
  1591
        return anode_matching[node];
deba@2051
  1592
      } else {
deba@2051
  1593
        return bnode_matching[node];
deba@2051
  1594
      }
deba@2051
  1595
    }
deba@2051
  1596
deba@2051
  1597
    /// \brief Gives back the sum of costs of the matching edges.
deba@2051
  1598
    ///
deba@2051
  1599
    /// Gives back the sum of costs of the matching edges.
deba@2051
  1600
    Value matchingCost() const {
deba@2051
  1601
      return matching_cost;
deba@2051
  1602
    }
deba@2051
  1603
deba@2051
  1604
    /// \brief Gives back the number of the matching edges.
deba@2051
  1605
    ///
deba@2051
  1606
    /// Gives back the number of the matching edges.
deba@2051
  1607
    int matchingSize() const {
deba@2051
  1608
      return matching_size;
deba@2051
  1609
    }
deba@2051
  1610
deba@2051
  1611
    /// @}
deba@2051
  1612
deba@2051
  1613
  private:
deba@2051
  1614
deba@2051
  1615
    void initStructures() {
deba@2051
  1616
      if (!_heap_cross_ref) {
deba@2051
  1617
	local_heap_cross_ref = true;
deba@2051
  1618
	_heap_cross_ref = Traits::createHeapCrossRef(*graph);
deba@2051
  1619
      }
deba@2051
  1620
      if (!_heap) {
deba@2051
  1621
	local_heap = true;
deba@2051
  1622
	_heap = Traits::createHeap(*_heap_cross_ref);
deba@2051
  1623
      }
deba@2051
  1624
    }
deba@2051
  1625
deba@2051
  1626
    void destroyStructures() {
deba@2051
  1627
      if (local_heap_cross_ref) delete _heap_cross_ref;
deba@2051
  1628
      if (local_heap) delete _heap;
deba@2051
  1629
    }
deba@2051
  1630
deba@2051
  1631
deba@2051
  1632
  private:
deba@2051
  1633
    
deba@2051
  1634
    const BpUGraph *graph;
deba@2051
  1635
    const CostMap* cost;
deba@2051
  1636
deba@2051
  1637
    ANodeMatchingMap anode_matching;
deba@2051
  1638
    BNodeMatchingMap bnode_matching;
deba@2051
  1639
deba@2051
  1640
    ANodePotentialMap anode_potential;
deba@2051
  1641
    BNodePotentialMap bnode_potential;
deba@2051
  1642
deba@2051
  1643
    Value matching_cost;
deba@2051
  1644
    int matching_size;
deba@2051
  1645
deba@2051
  1646
    HeapCrossRef *_heap_cross_ref;
deba@2051
  1647
    bool local_heap_cross_ref;
deba@2051
  1648
deba@2051
  1649
    Heap *_heap;
deba@2051
  1650
    bool local_heap;
deba@2040
  1651
  
deba@2040
  1652
  };
deba@2040
  1653
deba@2058
  1654
  /// \ingroup matching
deba@2058
  1655
  ///
deba@2058
  1656
  /// \brief Minimum cost maximum cardinality bipartite matching
deba@2058
  1657
  ///
deba@2058
  1658
  /// This function calculates the minimum cost matching of the maximum 
deba@2058
  1659
  /// cardinality matchings of a bipartite graph. It gives back the matching 
deba@2058
  1660
  /// in an undirected edge map.
deba@2058
  1661
  ///
deba@2058
  1662
  /// \param graph The bipartite graph.
deba@2058
  1663
  /// \param cost The undirected edge map which contains the costs.
deba@2058
  1664
  /// \retval matching The undirected edge map which will be set to 
deba@2058
  1665
  /// the matching.
deba@2058
  1666
  /// \return The cost of the matching.
deba@2058
  1667
  template <typename BpUGraph, typename CostMap, typename MatchingMap>
deba@2058
  1668
  typename CostMap::Value 
deba@2058
  1669
  minCostMaxBipartiteMatching(const BpUGraph& graph, 
deba@2058
  1670
                              const CostMap& cost,
deba@2058
  1671
                              MatchingMap& matching) {
deba@2058
  1672
    MinCostMaxBipartiteMatching<BpUGraph, CostMap> 
deba@2058
  1673
      bpmatching(graph, cost);
deba@2058
  1674
    bpmatching.run();
deba@2058
  1675
    bpmatching.matching(matching);
deba@2058
  1676
    return bpmatching.matchingCost();
deba@2058
  1677
  }
deba@2058
  1678
deba@2040
  1679
}
deba@2040
  1680
deba@2040
  1681
#endif