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