lemon/matching.h
author Alpar Juttner <alpar@cs.elte.hu>
Thu, 25 Feb 2021 09:46:12 +0100
changeset 1209 4a170261cc54
parent 1203 8c567e298d7f
permissions -rw-r--r--
Merge #638
deba@326
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
deba@326
     2
 *
deba@326
     3
 * This file is a part of LEMON, a generic C++ optimization library.
deba@326
     4
 *
alpar@1092
     5
 * Copyright (C) 2003-2013
deba@326
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
deba@326
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
deba@326
     8
 *
deba@326
     9
 * Permission to use, modify and distribute this software is granted
deba@326
    10
 * provided that this copyright notice appears in all copies. For
deba@326
    11
 * precise terms see the accompanying LICENSE file.
deba@326
    12
 *
deba@326
    13
 * This software is provided "AS IS" with no warranty of any kind,
deba@326
    14
 * express or implied, and with no claim as to its suitability for any
deba@326
    15
 * purpose.
deba@326
    16
 *
deba@326
    17
 */
deba@326
    18
deba@868
    19
#ifndef LEMON_MATCHING_H
deba@868
    20
#define LEMON_MATCHING_H
deba@326
    21
deba@326
    22
#include <vector>
deba@326
    23
#include <queue>
deba@326
    24
#include <set>
deba@326
    25
#include <limits>
deba@326
    26
deba@326
    27
#include <lemon/core.h>
deba@326
    28
#include <lemon/unionfind.h>
deba@326
    29
#include <lemon/bin_heap.h>
deba@326
    30
#include <lemon/maps.h>
deba@870
    31
#include <lemon/fractional_matching.h>
deba@326
    32
deba@326
    33
///\ingroup matching
deba@326
    34
///\file
deba@327
    35
///\brief Maximum matching algorithms in general graphs.
deba@326
    36
deba@326
    37
namespace lemon {
deba@326
    38
deba@327
    39
  /// \ingroup matching
deba@326
    40
  ///
kpeter@590
    41
  /// \brief Maximum cardinality matching in general graphs
deba@326
    42
  ///
kpeter@590
    43
  /// This class implements Edmonds' alternating forest matching algorithm
kpeter@593
    44
  /// for finding a maximum cardinality matching in a general undirected graph.
deba@868
    45
  /// It can be started from an arbitrary initial matching
kpeter@590
    46
  /// (the default is the empty one).
deba@326
    47
  ///
alpar@330
    48
  /// The dual solution of the problem is a map of the nodes to
kpeter@590
    49
  /// \ref MaxMatching::Status "Status", having values \c EVEN (or \c D),
kpeter@590
    50
  /// \c ODD (or \c A) and \c MATCHED (or \c C) defining the Gallai-Edmonds
kpeter@590
    51
  /// decomposition of the graph. The nodes in \c EVEN/D induce a subgraph
kpeter@590
    52
  /// with factor-critical components, the nodes in \c ODD/A form the
kpeter@590
    53
  /// canonical barrier, and the nodes in \c MATCHED/C induce a graph having
kpeter@590
    54
  /// a perfect matching. The number of the factor-critical components
deba@327
    55
  /// minus the number of barrier nodes is a lower bound on the
alpar@330
    56
  /// unmatched nodes, and the matching is optimal if and only if this bound is
kpeter@593
    57
  /// tight. This decomposition can be obtained using \ref status() or
kpeter@593
    58
  /// \ref statusMap() after running the algorithm.
deba@326
    59
  ///
kpeter@593
    60
  /// \tparam GR The undirected graph type the algorithm runs on.
kpeter@559
    61
  template <typename GR>
deba@326
    62
  class MaxMatching {
deba@327
    63
  public:
deba@327
    64
kpeter@590
    65
    /// The graph type of the algorithm
kpeter@559
    66
    typedef GR Graph;
kpeter@593
    67
    /// The type of the matching map
deba@327
    68
    typedef typename Graph::template NodeMap<typename Graph::Arc>
deba@327
    69
    MatchingMap;
deba@327
    70
kpeter@590
    71
    ///\brief Status constants for Gallai-Edmonds decomposition.
deba@327
    72
    ///
deba@868
    73
    ///These constants are used for indicating the Gallai-Edmonds
kpeter@590
    74
    ///decomposition of a graph. The nodes with status \c EVEN (or \c D)
kpeter@590
    75
    ///induce a subgraph with factor-critical components, the nodes with
kpeter@590
    76
    ///status \c ODD (or \c A) form the canonical barrier, and the nodes
deba@868
    77
    ///with status \c MATCHED (or \c C) induce a subgraph having a
kpeter@590
    78
    ///perfect matching.
deba@327
    79
    enum Status {
kpeter@590
    80
      EVEN = 1,       ///< = 1. (\c D is an alias for \c EVEN.)
kpeter@590
    81
      D = 1,
kpeter@590
    82
      MATCHED = 0,    ///< = 0. (\c C is an alias for \c MATCHED.)
kpeter@590
    83
      C = 0,
kpeter@590
    84
      ODD = -1,       ///< = -1. (\c A is an alias for \c ODD.)
kpeter@590
    85
      A = -1,
kpeter@590
    86
      UNMATCHED = -2  ///< = -2.
deba@327
    87
    };
deba@327
    88
kpeter@593
    89
    /// The type of the status map
deba@327
    90
    typedef typename Graph::template NodeMap<Status> StatusMap;
deba@327
    91
deba@327
    92
  private:
deba@326
    93
deba@326
    94
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
deba@326
    95
deba@327
    96
    typedef UnionFindEnum<IntNodeMap> BlossomSet;
deba@327
    97
    typedef ExtendFindEnum<IntNodeMap> TreeSet;
deba@327
    98
    typedef RangeMap<Node> NodeIntMap;
deba@327
    99
    typedef MatchingMap EarMap;
deba@327
   100
    typedef std::vector<Node> NodeQueue;
deba@327
   101
deba@327
   102
    const Graph& _graph;
deba@327
   103
    MatchingMap* _matching;
deba@327
   104
    StatusMap* _status;
deba@327
   105
deba@327
   106
    EarMap* _ear;
deba@327
   107
deba@327
   108
    IntNodeMap* _blossom_set_index;
deba@327
   109
    BlossomSet* _blossom_set;
deba@327
   110
    NodeIntMap* _blossom_rep;
deba@327
   111
deba@327
   112
    IntNodeMap* _tree_set_index;
deba@327
   113
    TreeSet* _tree_set;
deba@327
   114
deba@327
   115
    NodeQueue _node_queue;
deba@327
   116
    int _process, _postpone, _last;
deba@327
   117
deba@1203
   118
    int _node_num, _unmatched;
deba@327
   119
deba@327
   120
  private:
deba@327
   121
deba@327
   122
    void createStructures() {
deba@327
   123
      _node_num = countNodes(_graph);
deba@327
   124
      if (!_matching) {
deba@327
   125
        _matching = new MatchingMap(_graph);
deba@327
   126
      }
deba@327
   127
      if (!_status) {
deba@327
   128
        _status = new StatusMap(_graph);
deba@327
   129
      }
deba@327
   130
      if (!_ear) {
deba@327
   131
        _ear = new EarMap(_graph);
deba@327
   132
      }
deba@327
   133
      if (!_blossom_set) {
deba@327
   134
        _blossom_set_index = new IntNodeMap(_graph);
deba@327
   135
        _blossom_set = new BlossomSet(*_blossom_set_index);
deba@327
   136
      }
deba@327
   137
      if (!_blossom_rep) {
deba@327
   138
        _blossom_rep = new NodeIntMap(_node_num);
deba@327
   139
      }
deba@327
   140
      if (!_tree_set) {
deba@327
   141
        _tree_set_index = new IntNodeMap(_graph);
deba@327
   142
        _tree_set = new TreeSet(*_tree_set_index);
deba@327
   143
      }
deba@327
   144
      _node_queue.resize(_node_num);
deba@327
   145
    }
deba@327
   146
deba@327
   147
    void destroyStructures() {
deba@327
   148
      if (_matching) {
deba@327
   149
        delete _matching;
deba@327
   150
      }
deba@327
   151
      if (_status) {
deba@327
   152
        delete _status;
deba@327
   153
      }
deba@327
   154
      if (_ear) {
deba@327
   155
        delete _ear;
deba@327
   156
      }
deba@327
   157
      if (_blossom_set) {
deba@327
   158
        delete _blossom_set;
deba@327
   159
        delete _blossom_set_index;
deba@327
   160
      }
deba@327
   161
      if (_blossom_rep) {
deba@327
   162
        delete _blossom_rep;
deba@327
   163
      }
deba@327
   164
      if (_tree_set) {
deba@327
   165
        delete _tree_set_index;
deba@327
   166
        delete _tree_set;
deba@327
   167
      }
deba@327
   168
    }
deba@327
   169
deba@327
   170
    void processDense(const Node& n) {
deba@327
   171
      _process = _postpone = _last = 0;
deba@327
   172
      _node_queue[_last++] = n;
deba@327
   173
deba@327
   174
      while (_process != _last) {
deba@327
   175
        Node u = _node_queue[_process++];
deba@327
   176
        for (OutArcIt a(_graph, u); a != INVALID; ++a) {
deba@327
   177
          Node v = _graph.target(a);
deba@327
   178
          if ((*_status)[v] == MATCHED) {
deba@327
   179
            extendOnArc(a);
deba@327
   180
          } else if ((*_status)[v] == UNMATCHED) {
deba@327
   181
            augmentOnArc(a);
deba@1203
   182
            --_unmatched;
deba@327
   183
            return;
deba@327
   184
          }
deba@327
   185
        }
deba@327
   186
      }
deba@327
   187
deba@327
   188
      while (_postpone != _last) {
deba@327
   189
        Node u = _node_queue[_postpone++];
deba@327
   190
deba@327
   191
        for (OutArcIt a(_graph, u); a != INVALID ; ++a) {
deba@327
   192
          Node v = _graph.target(a);
deba@327
   193
deba@327
   194
          if ((*_status)[v] == EVEN) {
deba@327
   195
            if (_blossom_set->find(u) != _blossom_set->find(v)) {
deba@327
   196
              shrinkOnEdge(a);
deba@327
   197
            }
deba@327
   198
          }
deba@327
   199
deba@327
   200
          while (_process != _last) {
deba@327
   201
            Node w = _node_queue[_process++];
deba@327
   202
            for (OutArcIt b(_graph, w); b != INVALID; ++b) {
deba@327
   203
              Node x = _graph.target(b);
deba@327
   204
              if ((*_status)[x] == MATCHED) {
deba@327
   205
                extendOnArc(b);
deba@327
   206
              } else if ((*_status)[x] == UNMATCHED) {
deba@327
   207
                augmentOnArc(b);
deba@1203
   208
                --_unmatched;
deba@327
   209
                return;
deba@327
   210
              }
deba@327
   211
            }
deba@327
   212
          }
deba@327
   213
        }
deba@327
   214
      }
deba@327
   215
    }
deba@327
   216
deba@327
   217
    void processSparse(const Node& n) {
deba@327
   218
      _process = _last = 0;
deba@327
   219
      _node_queue[_last++] = n;
deba@327
   220
      while (_process != _last) {
deba@327
   221
        Node u = _node_queue[_process++];
deba@327
   222
        for (OutArcIt a(_graph, u); a != INVALID; ++a) {
deba@327
   223
          Node v = _graph.target(a);
deba@327
   224
deba@327
   225
          if ((*_status)[v] == EVEN) {
deba@327
   226
            if (_blossom_set->find(u) != _blossom_set->find(v)) {
deba@327
   227
              shrinkOnEdge(a);
deba@327
   228
            }
deba@327
   229
          } else if ((*_status)[v] == MATCHED) {
deba@327
   230
            extendOnArc(a);
deba@327
   231
          } else if ((*_status)[v] == UNMATCHED) {
deba@327
   232
            augmentOnArc(a);
deba@1203
   233
            --_unmatched;
deba@327
   234
            return;
deba@327
   235
          }
deba@327
   236
        }
deba@327
   237
      }
deba@327
   238
    }
deba@327
   239
deba@327
   240
    void shrinkOnEdge(const Edge& e) {
deba@327
   241
      Node nca = INVALID;
deba@327
   242
deba@327
   243
      {
deba@327
   244
        std::set<Node> left_set, right_set;
deba@327
   245
deba@327
   246
        Node left = (*_blossom_rep)[_blossom_set->find(_graph.u(e))];
deba@327
   247
        left_set.insert(left);
deba@327
   248
deba@327
   249
        Node right = (*_blossom_rep)[_blossom_set->find(_graph.v(e))];
deba@327
   250
        right_set.insert(right);
deba@327
   251
deba@327
   252
        while (true) {
deba@327
   253
          if ((*_matching)[left] == INVALID) break;
deba@327
   254
          left = _graph.target((*_matching)[left]);
deba@327
   255
          left = (*_blossom_rep)[_blossom_set->
deba@327
   256
                                 find(_graph.target((*_ear)[left]))];
deba@327
   257
          if (right_set.find(left) != right_set.end()) {
deba@327
   258
            nca = left;
deba@327
   259
            break;
deba@327
   260
          }
deba@327
   261
          left_set.insert(left);
deba@327
   262
deba@327
   263
          if ((*_matching)[right] == INVALID) break;
deba@327
   264
          right = _graph.target((*_matching)[right]);
deba@327
   265
          right = (*_blossom_rep)[_blossom_set->
deba@327
   266
                                  find(_graph.target((*_ear)[right]))];
deba@327
   267
          if (left_set.find(right) != left_set.end()) {
deba@327
   268
            nca = right;
deba@327
   269
            break;
deba@327
   270
          }
deba@327
   271
          right_set.insert(right);
deba@327
   272
        }
deba@327
   273
deba@327
   274
        if (nca == INVALID) {
deba@327
   275
          if ((*_matching)[left] == INVALID) {
deba@327
   276
            nca = right;
deba@327
   277
            while (left_set.find(nca) == left_set.end()) {
deba@327
   278
              nca = _graph.target((*_matching)[nca]);
deba@327
   279
              nca =(*_blossom_rep)[_blossom_set->
deba@327
   280
                                   find(_graph.target((*_ear)[nca]))];
deba@327
   281
            }
deba@327
   282
          } else {
deba@327
   283
            nca = left;
deba@327
   284
            while (right_set.find(nca) == right_set.end()) {
deba@327
   285
              nca = _graph.target((*_matching)[nca]);
deba@327
   286
              nca = (*_blossom_rep)[_blossom_set->
deba@327
   287
                                   find(_graph.target((*_ear)[nca]))];
deba@327
   288
            }
deba@327
   289
          }
deba@327
   290
        }
deba@327
   291
      }
deba@327
   292
deba@327
   293
      {
deba@327
   294
deba@327
   295
        Node node = _graph.u(e);
deba@327
   296
        Arc arc = _graph.direct(e, true);
deba@327
   297
        Node base = (*_blossom_rep)[_blossom_set->find(node)];
deba@327
   298
deba@327
   299
        while (base != nca) {
kpeter@581
   300
          (*_ear)[node] = arc;
deba@327
   301
deba@327
   302
          Node n = node;
deba@327
   303
          while (n != base) {
deba@327
   304
            n = _graph.target((*_matching)[n]);
deba@327
   305
            Arc a = (*_ear)[n];
deba@327
   306
            n = _graph.target(a);
kpeter@581
   307
            (*_ear)[n] = _graph.oppositeArc(a);
deba@327
   308
          }
deba@327
   309
          node = _graph.target((*_matching)[base]);
deba@327
   310
          _tree_set->erase(base);
deba@327
   311
          _tree_set->erase(node);
deba@327
   312
          _blossom_set->insert(node, _blossom_set->find(base));
kpeter@581
   313
          (*_status)[node] = EVEN;
deba@327
   314
          _node_queue[_last++] = node;
deba@327
   315
          arc = _graph.oppositeArc((*_ear)[node]);
deba@327
   316
          node = _graph.target((*_ear)[node]);
deba@327
   317
          base = (*_blossom_rep)[_blossom_set->find(node)];
deba@327
   318
          _blossom_set->join(_graph.target(arc), base);
deba@327
   319
        }
deba@327
   320
      }
deba@327
   321
kpeter@581
   322
      (*_blossom_rep)[_blossom_set->find(nca)] = nca;
deba@327
   323
deba@327
   324
      {
deba@327
   325
deba@327
   326
        Node node = _graph.v(e);
deba@327
   327
        Arc arc = _graph.direct(e, false);
deba@327
   328
        Node base = (*_blossom_rep)[_blossom_set->find(node)];
deba@327
   329
deba@327
   330
        while (base != nca) {
kpeter@581
   331
          (*_ear)[node] = arc;
deba@327
   332
deba@327
   333
          Node n = node;
deba@327
   334
          while (n != base) {
deba@327
   335
            n = _graph.target((*_matching)[n]);
deba@327
   336
            Arc a = (*_ear)[n];
deba@327
   337
            n = _graph.target(a);
kpeter@581
   338
            (*_ear)[n] = _graph.oppositeArc(a);
deba@327
   339
          }
deba@327
   340
          node = _graph.target((*_matching)[base]);
deba@327
   341
          _tree_set->erase(base);
deba@327
   342
          _tree_set->erase(node);
deba@327
   343
          _blossom_set->insert(node, _blossom_set->find(base));
kpeter@581
   344
          (*_status)[node] = EVEN;
deba@327
   345
          _node_queue[_last++] = node;
deba@327
   346
          arc = _graph.oppositeArc((*_ear)[node]);
deba@327
   347
          node = _graph.target((*_ear)[node]);
deba@327
   348
          base = (*_blossom_rep)[_blossom_set->find(node)];
deba@327
   349
          _blossom_set->join(_graph.target(arc), base);
deba@327
   350
        }
deba@327
   351
      }
deba@327
   352
kpeter@581
   353
      (*_blossom_rep)[_blossom_set->find(nca)] = nca;
deba@327
   354
    }
deba@327
   355
deba@327
   356
    void extendOnArc(const Arc& a) {
deba@327
   357
      Node base = _graph.source(a);
deba@327
   358
      Node odd = _graph.target(a);
deba@327
   359
kpeter@581
   360
      (*_ear)[odd] = _graph.oppositeArc(a);
deba@327
   361
      Node even = _graph.target((*_matching)[odd]);
kpeter@581
   362
      (*_blossom_rep)[_blossom_set->insert(even)] = even;
kpeter@581
   363
      (*_status)[odd] = ODD;
kpeter@581
   364
      (*_status)[even] = EVEN;
deba@327
   365
      int tree = _tree_set->find((*_blossom_rep)[_blossom_set->find(base)]);
deba@327
   366
      _tree_set->insert(odd, tree);
deba@327
   367
      _tree_set->insert(even, tree);
deba@327
   368
      _node_queue[_last++] = even;
deba@327
   369
deba@327
   370
    }
deba@327
   371
deba@327
   372
    void augmentOnArc(const Arc& a) {
deba@327
   373
      Node even = _graph.source(a);
deba@327
   374
      Node odd = _graph.target(a);
deba@327
   375
deba@327
   376
      int tree = _tree_set->find((*_blossom_rep)[_blossom_set->find(even)]);
deba@327
   377
kpeter@581
   378
      (*_matching)[odd] = _graph.oppositeArc(a);
kpeter@581
   379
      (*_status)[odd] = MATCHED;
deba@327
   380
deba@327
   381
      Arc arc = (*_matching)[even];
kpeter@581
   382
      (*_matching)[even] = a;
deba@327
   383
deba@327
   384
      while (arc != INVALID) {
deba@327
   385
        odd = _graph.target(arc);
deba@327
   386
        arc = (*_ear)[odd];
deba@327
   387
        even = _graph.target(arc);
kpeter@581
   388
        (*_matching)[odd] = arc;
deba@327
   389
        arc = (*_matching)[even];
kpeter@581
   390
        (*_matching)[even] = _graph.oppositeArc((*_matching)[odd]);
deba@327
   391
      }
deba@327
   392
deba@327
   393
      for (typename TreeSet::ItemIt it(*_tree_set, tree);
deba@327
   394
           it != INVALID; ++it) {
deba@327
   395
        if ((*_status)[it] == ODD) {
kpeter@581
   396
          (*_status)[it] = MATCHED;
deba@327
   397
        } else {
deba@327
   398
          int blossom = _blossom_set->find(it);
deba@327
   399
          for (typename BlossomSet::ItemIt jt(*_blossom_set, blossom);
deba@327
   400
               jt != INVALID; ++jt) {
kpeter@581
   401
            (*_status)[jt] = MATCHED;
deba@327
   402
          }
deba@327
   403
          _blossom_set->eraseClass(blossom);
deba@327
   404
        }
deba@327
   405
      }
deba@327
   406
      _tree_set->eraseClass(tree);
deba@327
   407
deba@327
   408
    }
deba@326
   409
deba@326
   410
  public:
deba@326
   411
deba@327
   412
    /// \brief Constructor
deba@326
   413
    ///
deba@327
   414
    /// Constructor.
deba@327
   415
    MaxMatching(const Graph& graph)
deba@327
   416
      : _graph(graph), _matching(0), _status(0), _ear(0),
deba@327
   417
        _blossom_set_index(0), _blossom_set(0), _blossom_rep(0),
deba@327
   418
        _tree_set_index(0), _tree_set(0) {}
deba@327
   419
deba@327
   420
    ~MaxMatching() {
deba@327
   421
      destroyStructures();
deba@327
   422
    }
deba@327
   423
kpeter@590
   424
    /// \name Execution Control
alpar@330
   425
    /// The simplest way to execute the algorithm is to use the
kpeter@590
   426
    /// \c run() member function.\n
kpeter@590
   427
    /// If you need better control on the execution, you have to call
kpeter@590
   428
    /// one of the functions \ref init(), \ref greedyInit() or
kpeter@590
   429
    /// \ref matchingInit() first, then you can start the algorithm with
kpeter@590
   430
    /// \ref startSparse() or \ref startDense().
deba@327
   431
deba@327
   432
    ///@{
deba@327
   433
kpeter@590
   434
    /// \brief Set the initial matching to the empty matching.
deba@326
   435
    ///
kpeter@590
   436
    /// This function sets the initial matching to the empty matching.
deba@326
   437
    void init() {
deba@327
   438
      createStructures();
deba@327
   439
      for(NodeIt n(_graph); n != INVALID; ++n) {
kpeter@581
   440
        (*_matching)[n] = INVALID;
kpeter@581
   441
        (*_status)[n] = UNMATCHED;
deba@326
   442
      }
deba@1203
   443
      _unmatched = _node_num;
deba@326
   444
    }
deba@326
   445
kpeter@590
   446
    /// \brief Find an initial matching in a greedy way.
deba@326
   447
    ///
kpeter@590
   448
    /// This function finds an initial matching in a greedy way.
deba@326
   449
    void greedyInit() {
deba@327
   450
      createStructures();
deba@327
   451
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@581
   452
        (*_matching)[n] = INVALID;
kpeter@581
   453
        (*_status)[n] = UNMATCHED;
deba@326
   454
      }
deba@1203
   455
      _unmatched = _node_num;
deba@327
   456
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@327
   457
        if ((*_matching)[n] == INVALID) {
deba@327
   458
          for (OutArcIt a(_graph, n); a != INVALID ; ++a) {
deba@327
   459
            Node v = _graph.target(a);
deba@327
   460
            if ((*_matching)[v] == INVALID && v != n) {
kpeter@581
   461
              (*_matching)[n] = a;
kpeter@581
   462
              (*_status)[n] = MATCHED;
kpeter@581
   463
              (*_matching)[v] = _graph.oppositeArc(a);
kpeter@581
   464
              (*_status)[v] = MATCHED;
deba@1203
   465
              _unmatched -= 2;
deba@326
   466
              break;
deba@326
   467
            }
deba@326
   468
          }
deba@326
   469
        }
deba@326
   470
      }
deba@326
   471
    }
deba@326
   472
deba@327
   473
kpeter@590
   474
    /// \brief Initialize the matching from a map.
deba@326
   475
    ///
kpeter@590
   476
    /// This function initializes the matching from a \c bool valued edge
kpeter@590
   477
    /// map. This map should have the property that there are no two incident
kpeter@590
   478
    /// edges with \c true value, i.e. it really contains a matching.
kpeter@559
   479
    /// \return \c true if the map contains a matching.
deba@327
   480
    template <typename MatchingMap>
deba@327
   481
    bool matchingInit(const MatchingMap& matching) {
deba@327
   482
      createStructures();
deba@327
   483
deba@327
   484
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@581
   485
        (*_matching)[n] = INVALID;
kpeter@581
   486
        (*_status)[n] = UNMATCHED;
deba@326
   487
      }
deba@1203
   488
      _unmatched = _node_num;
deba@327
   489
      for(EdgeIt e(_graph); e!=INVALID; ++e) {
deba@327
   490
        if (matching[e]) {
deba@327
   491
deba@327
   492
          Node u = _graph.u(e);
deba@327
   493
          if ((*_matching)[u] != INVALID) return false;
kpeter@581
   494
          (*_matching)[u] = _graph.direct(e, true);
kpeter@581
   495
          (*_status)[u] = MATCHED;
deba@327
   496
deba@327
   497
          Node v = _graph.v(e);
deba@327
   498
          if ((*_matching)[v] != INVALID) return false;
kpeter@581
   499
          (*_matching)[v] = _graph.direct(e, false);
kpeter@581
   500
          (*_status)[v] = MATCHED;
deba@1203
   501
deba@1203
   502
          _unmatched -= 2;
deba@327
   503
        }
deba@327
   504
      }
deba@327
   505
      return true;
deba@326
   506
    }
deba@326
   507
kpeter@590
   508
    /// \brief Start Edmonds' algorithm
deba@326
   509
    ///
deba@1203
   510
    /// This function runs the original Edmonds' algorithm. If the
deba@1203
   511
    /// \c decomposition parameter is set to false, then the Gallai-Edmonds
deba@1203
   512
    /// decomposition is not computed.
kpeter@590
   513
    ///
kpeter@651
   514
    /// \pre \ref init(), \ref greedyInit() or \ref matchingInit() must be
kpeter@590
   515
    /// called before using this function.
deba@1203
   516
    void startSparse(bool decomposition = true) {
deba@1203
   517
      int _unmatched_limit = decomposition ? 0 : 1;
deba@1203
   518
      for(NodeIt n(_graph); _unmatched > _unmatched_limit; ++n) {
deba@327
   519
        if ((*_status)[n] == UNMATCHED) {
deba@327
   520
          (*_blossom_rep)[_blossom_set->insert(n)] = n;
deba@327
   521
          _tree_set->insert(n);
kpeter@581
   522
          (*_status)[n] = EVEN;
deba@1203
   523
          --_unmatched;
deba@327
   524
          processSparse(n);
deba@326
   525
        }
deba@326
   526
      }
deba@326
   527
    }
deba@326
   528
deba@868
   529
    /// \brief Start Edmonds' algorithm with a heuristic improvement
kpeter@590
   530
    /// for dense graphs
deba@326
   531
    ///
kpeter@590
   532
    /// This function runs Edmonds' algorithm with a heuristic of postponing
deba@1203
   533
    /// shrinks, therefore resulting in a faster algorithm for dense graphs.  If
deba@1203
   534
    /// the \c decomposition parameter is set to false, then the Gallai-Edmonds
deba@1203
   535
    /// decomposition is not computed.
kpeter@590
   536
    ///
kpeter@651
   537
    /// \pre \ref init(), \ref greedyInit() or \ref matchingInit() must be
kpeter@590
   538
    /// called before using this function.
deba@1203
   539
    void startDense(bool decomposition = true) {
deba@1203
   540
      int _unmatched_limit = decomposition ? 0 : 1;
deba@1203
   541
      for(NodeIt n(_graph); _unmatched > _unmatched_limit; ++n) {
deba@327
   542
        if ((*_status)[n] == UNMATCHED) {
deba@327
   543
          (*_blossom_rep)[_blossom_set->insert(n)] = n;
deba@327
   544
          _tree_set->insert(n);
kpeter@581
   545
          (*_status)[n] = EVEN;
deba@1203
   546
          --_unmatched;
deba@327
   547
          processDense(n);
deba@327
   548
        }
deba@327
   549
      }
deba@327
   550
    }
deba@327
   551
deba@327
   552
kpeter@590
   553
    /// \brief Run Edmonds' algorithm
deba@327
   554
    ///
deba@868
   555
    /// This function runs Edmonds' algorithm. An additional heuristic of
deba@1203
   556
    /// postponing shrinks is used for relatively dense graphs (for which
deba@1203
   557
    /// <tt>m>=2*n</tt> holds). If the \c decomposition parameter is set to
deba@1203
   558
    /// false, then the Gallai-Edmonds decomposition is not computed. In some
deba@1203
   559
    /// cases, this can speed up the algorithm significantly, especially when a
deba@1203
   560
    /// maximum matching is computed in a dense graph with odd number of nodes.
deba@1203
   561
    void run(bool decomposition = true) {
deba@327
   562
      if (countEdges(_graph) < 2 * countNodes(_graph)) {
deba@326
   563
        greedyInit();
deba@1203
   564
        startSparse(decomposition);
deba@326
   565
      } else {
deba@326
   566
        init();
deba@1203
   567
        startDense(decomposition);
deba@326
   568
      }
deba@326
   569
    }
deba@326
   570
deba@327
   571
    /// @}
deba@327
   572
kpeter@590
   573
    /// \name Primal Solution
kpeter@590
   574
    /// Functions to get the primal solution, i.e. the maximum matching.
deba@327
   575
deba@327
   576
    /// @{
deba@326
   577
kpeter@590
   578
    /// \brief Return the size (cardinality) of the matching.
deba@326
   579
    ///
deba@868
   580
    /// This function returns the size (cardinality) of the current matching.
kpeter@590
   581
    /// After run() it returns the size of the maximum matching in the graph.
deba@327
   582
    int matchingSize() const {
deba@327
   583
      int size = 0;
deba@327
   584
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@327
   585
        if ((*_matching)[n] != INVALID) {
deba@327
   586
          ++size;
deba@326
   587
        }
deba@326
   588
      }
deba@327
   589
      return size / 2;
deba@326
   590
    }
deba@326
   591
kpeter@590
   592
    /// \brief Return \c true if the given edge is in the matching.
deba@327
   593
    ///
deba@868
   594
    /// This function returns \c true if the given edge is in the current
kpeter@590
   595
    /// matching.
deba@327
   596
    bool matching(const Edge& edge) const {
deba@327
   597
      return edge == (*_matching)[_graph.u(edge)];
deba@327
   598
    }
deba@327
   599
kpeter@590
   600
    /// \brief Return the matching arc (or edge) incident to the given node.
deba@327
   601
    ///
kpeter@590
   602
    /// This function returns the matching arc (or edge) incident to the
deba@868
   603
    /// given node in the current matching or \c INVALID if the node is
kpeter@590
   604
    /// not covered by the matching.
deba@327
   605
    Arc matching(const Node& n) const {
deba@327
   606
      return (*_matching)[n];
deba@327
   607
    }
deba@326
   608
kpeter@593
   609
    /// \brief Return a const reference to the matching map.
kpeter@593
   610
    ///
kpeter@593
   611
    /// This function returns a const reference to a node map that stores
kpeter@593
   612
    /// the matching arc (or edge) incident to each node.
kpeter@593
   613
    const MatchingMap& matchingMap() const {
kpeter@593
   614
      return *_matching;
kpeter@593
   615
    }
kpeter@593
   616
kpeter@590
   617
    /// \brief Return the mate of the given node.
deba@326
   618
    ///
deba@868
   619
    /// This function returns the mate of the given node in the current
kpeter@590
   620
    /// matching or \c INVALID if the node is not covered by the matching.
deba@327
   621
    Node mate(const Node& n) const {
deba@327
   622
      return (*_matching)[n] != INVALID ?
deba@327
   623
        _graph.target((*_matching)[n]) : INVALID;
deba@326
   624
    }
deba@326
   625
deba@327
   626
    /// @}
deba@327
   627
kpeter@590
   628
    /// \name Dual Solution
deba@868
   629
    /// Functions to get the dual solution, i.e. the Gallai-Edmonds
kpeter@590
   630
    /// decomposition.
deba@327
   631
deba@327
   632
    /// @{
deba@326
   633
kpeter@590
   634
    /// \brief Return the status of the given node in the Edmonds-Gallai
deba@326
   635
    /// decomposition.
deba@326
   636
    ///
kpeter@590
   637
    /// This function returns the \ref Status "status" of the given node
kpeter@590
   638
    /// in the Edmonds-Gallai decomposition.
kpeter@593
   639
    Status status(const Node& n) const {
deba@327
   640
      return (*_status)[n];
deba@326
   641
    }
deba@326
   642
kpeter@593
   643
    /// \brief Return a const reference to the status map, which stores
kpeter@593
   644
    /// the Edmonds-Gallai decomposition.
kpeter@593
   645
    ///
kpeter@593
   646
    /// This function returns a const reference to a node map that stores the
kpeter@593
   647
    /// \ref Status "status" of each node in the Edmonds-Gallai decomposition.
kpeter@593
   648
    const StatusMap& statusMap() const {
kpeter@593
   649
      return *_status;
kpeter@593
   650
    }
kpeter@593
   651
kpeter@590
   652
    /// \brief Return \c true if the given node is in the barrier.
deba@326
   653
    ///
kpeter@590
   654
    /// This function returns \c true if the given node is in the barrier.
deba@327
   655
    bool barrier(const Node& n) const {
deba@327
   656
      return (*_status)[n] == ODD;
deba@326
   657
    }
deba@326
   658
deba@327
   659
    /// @}
deba@326
   660
deba@326
   661
  };
deba@326
   662
deba@326
   663
  /// \ingroup matching
deba@326
   664
  ///
deba@326
   665
  /// \brief Weighted matching in general graphs
deba@326
   666
  ///
deba@326
   667
  /// This class provides an efficient implementation of Edmond's
deba@326
   668
  /// maximum weighted matching algorithm. The implementation is based
deba@326
   669
  /// on extensive use of priority queues and provides
kpeter@559
   670
  /// \f$O(nm\log n)\f$ time complexity.
deba@326
   671
  ///
deba@868
   672
  /// The maximum weighted matching problem is to find a subset of the
deba@868
   673
  /// edges in an undirected graph with maximum overall weight for which
kpeter@590
   674
  /// each node has at most one incident edge.
kpeter@590
   675
  /// It can be formulated with the following linear program.
deba@326
   676
  /// \f[ \sum_{e \in \delta(u)}x_e \le 1 \quad \forall u\in V\f]
deba@327
   677
  /** \f[ \sum_{e \in \gamma(B)}x_e \le \frac{\vert B \vert - 1}{2}
deba@327
   678
      \quad \forall B\in\mathcal{O}\f] */
deba@326
   679
  /// \f[x_e \ge 0\quad \forall e\in E\f]
deba@326
   680
  /// \f[\max \sum_{e\in E}x_ew_e\f]
deba@327
   681
  /// where \f$\delta(X)\f$ is the set of edges incident to a node in
deba@327
   682
  /// \f$X\f$, \f$\gamma(X)\f$ is the set of edges with both ends in
deba@327
   683
  /// \f$X\f$ and \f$\mathcal{O}\f$ is the set of odd cardinality
deba@327
   684
  /// subsets of the nodes.
deba@326
   685
  ///
deba@326
   686
  /// The algorithm calculates an optimal matching and a proof of the
deba@326
   687
  /// optimality. The solution of the dual problem can be used to check
deba@327
   688
  /// the result of the algorithm. The dual linear problem is the
kpeter@590
   689
  /// following.
deba@327
   690
  /** \f[ y_u + y_v + \sum_{B \in \mathcal{O}, uv \in \gamma(B)}
deba@327
   691
      z_B \ge w_{uv} \quad \forall uv\in E\f] */
deba@326
   692
  /// \f[y_u \ge 0 \quad \forall u \in V\f]
deba@326
   693
  /// \f[z_B \ge 0 \quad \forall B \in \mathcal{O}\f]
deba@327
   694
  /** \f[\min \sum_{u \in V}y_u + \sum_{B \in \mathcal{O}}
deba@327
   695
      \frac{\vert B \vert - 1}{2}z_B\f] */
deba@326
   696
  ///
deba@868
   697
  /// The algorithm can be executed with the run() function.
kpeter@590
   698
  /// After it the matching (the primal solution) and the dual solution
deba@868
   699
  /// can be obtained using the query functions and the
deba@868
   700
  /// \ref MaxWeightedMatching::BlossomIt "BlossomIt" nested class,
deba@868
   701
  /// which is able to iterate on the nodes of a blossom.
kpeter@590
   702
  /// If the value type is integer, then the dual solution is multiplied
kpeter@590
   703
  /// by \ref MaxWeightedMatching::dualScale "4".
kpeter@590
   704
  ///
kpeter@593
   705
  /// \tparam GR The undirected graph type the algorithm runs on.
deba@868
   706
  /// \tparam WM The type edge weight map. The default type is
kpeter@590
   707
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<int>".
kpeter@590
   708
#ifdef DOXYGEN
kpeter@590
   709
  template <typename GR, typename WM>
kpeter@590
   710
#else
kpeter@559
   711
  template <typename GR,
kpeter@559
   712
            typename WM = typename GR::template EdgeMap<int> >
kpeter@590
   713
#endif
deba@326
   714
  class MaxWeightedMatching {
deba@326
   715
  public:
deba@326
   716
kpeter@590
   717
    /// The graph type of the algorithm
kpeter@559
   718
    typedef GR Graph;
kpeter@590
   719
    /// The type of the edge weight map
kpeter@559
   720
    typedef WM WeightMap;
kpeter@590
   721
    /// The value type of the edge weights
deba@326
   722
    typedef typename WeightMap::Value Value;
deba@326
   723
kpeter@593
   724
    /// The type of the matching map
kpeter@590
   725
    typedef typename Graph::template NodeMap<typename Graph::Arc>
kpeter@590
   726
    MatchingMap;
kpeter@590
   727
deba@326
   728
    /// \brief Scaling factor for dual solution
deba@326
   729
    ///
kpeter@590
   730
    /// Scaling factor for dual solution. It is equal to 4 or 1
deba@326
   731
    /// according to the value type.
deba@326
   732
    static const int dualScale =
deba@326
   733
      std::numeric_limits<Value>::is_integer ? 4 : 1;
deba@326
   734
deba@326
   735
  private:
deba@326
   736
deba@326
   737
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
deba@326
   738
deba@326
   739
    typedef typename Graph::template NodeMap<Value> NodePotential;
deba@326
   740
    typedef std::vector<Node> BlossomNodeList;
deba@326
   741
deba@326
   742
    struct BlossomVariable {
deba@326
   743
      int begin, end;
deba@326
   744
      Value value;
deba@326
   745
deba@1208
   746
      BlossomVariable(int _begin, Value _value)
deba@1208
   747
          : begin(_begin), end(-1), value(_value) {}
deba@326
   748
deba@326
   749
    };
deba@326
   750
deba@326
   751
    typedef std::vector<BlossomVariable> BlossomPotential;
deba@326
   752
deba@326
   753
    const Graph& _graph;
deba@326
   754
    const WeightMap& _weight;
deba@326
   755
deba@326
   756
    MatchingMap* _matching;
deba@326
   757
deba@326
   758
    NodePotential* _node_potential;
deba@326
   759
deba@326
   760
    BlossomPotential _blossom_potential;
deba@326
   761
    BlossomNodeList _blossom_node_list;
deba@326
   762
deba@326
   763
    int _node_num;
deba@326
   764
    int _blossom_num;
deba@326
   765
deba@326
   766
    typedef RangeMap<int> IntIntMap;
deba@326
   767
deba@326
   768
    enum Status {
deba@868
   769
      EVEN = -1, MATCHED = 0, ODD = 1
deba@326
   770
    };
deba@326
   771
deba@327
   772
    typedef HeapUnionFind<Value, IntNodeMap> BlossomSet;
deba@326
   773
    struct BlossomData {
deba@326
   774
      int tree;
deba@326
   775
      Status status;
deba@326
   776
      Arc pred, next;
deba@326
   777
      Value pot, offset;
deba@326
   778
      Node base;
deba@326
   779
    };
deba@326
   780
deba@327
   781
    IntNodeMap *_blossom_index;
deba@326
   782
    BlossomSet *_blossom_set;
deba@326
   783
    RangeMap<BlossomData>* _blossom_data;
deba@326
   784
deba@327
   785
    IntNodeMap *_node_index;
deba@327
   786
    IntArcMap *_node_heap_index;
deba@326
   787
deba@326
   788
    struct NodeData {
deba@326
   789
deba@327
   790
      NodeData(IntArcMap& node_heap_index)
deba@326
   791
        : heap(node_heap_index) {}
deba@326
   792
deba@326
   793
      int blossom;
deba@326
   794
      Value pot;
deba@327
   795
      BinHeap<Value, IntArcMap> heap;
deba@326
   796
      std::map<int, Arc> heap_index;
deba@326
   797
deba@326
   798
      int tree;
deba@326
   799
    };
deba@326
   800
deba@326
   801
    RangeMap<NodeData>* _node_data;
deba@326
   802
deba@326
   803
    typedef ExtendFindEnum<IntIntMap> TreeSet;
deba@326
   804
deba@326
   805
    IntIntMap *_tree_set_index;
deba@326
   806
    TreeSet *_tree_set;
deba@326
   807
deba@327
   808
    IntNodeMap *_delta1_index;
deba@327
   809
    BinHeap<Value, IntNodeMap> *_delta1;
deba@326
   810
deba@326
   811
    IntIntMap *_delta2_index;
deba@326
   812
    BinHeap<Value, IntIntMap> *_delta2;
deba@326
   813
deba@327
   814
    IntEdgeMap *_delta3_index;
deba@327
   815
    BinHeap<Value, IntEdgeMap> *_delta3;
deba@326
   816
deba@326
   817
    IntIntMap *_delta4_index;
deba@326
   818
    BinHeap<Value, IntIntMap> *_delta4;
deba@326
   819
deba@326
   820
    Value _delta_sum;
deba@870
   821
    int _unmatched;
deba@870
   822
deba@870
   823
    typedef MaxWeightedFractionalMatching<Graph, WeightMap> FractionalMatching;
deba@870
   824
    FractionalMatching *_fractional;
deba@326
   825
deba@326
   826
    void createStructures() {
deba@326
   827
      _node_num = countNodes(_graph);
deba@326
   828
      _blossom_num = _node_num * 3 / 2;
deba@326
   829
deba@326
   830
      if (!_matching) {
deba@326
   831
        _matching = new MatchingMap(_graph);
deba@326
   832
      }
deba@867
   833
deba@326
   834
      if (!_node_potential) {
deba@326
   835
        _node_potential = new NodePotential(_graph);
deba@326
   836
      }
deba@867
   837
deba@326
   838
      if (!_blossom_set) {
deba@327
   839
        _blossom_index = new IntNodeMap(_graph);
deba@326
   840
        _blossom_set = new BlossomSet(*_blossom_index);
deba@326
   841
        _blossom_data = new RangeMap<BlossomData>(_blossom_num);
deba@867
   842
      } else if (_blossom_data->size() != _blossom_num) {
deba@867
   843
        delete _blossom_data;
deba@867
   844
        _blossom_data = new RangeMap<BlossomData>(_blossom_num);
deba@326
   845
      }
deba@326
   846
deba@326
   847
      if (!_node_index) {
deba@327
   848
        _node_index = new IntNodeMap(_graph);
deba@327
   849
        _node_heap_index = new IntArcMap(_graph);
deba@326
   850
        _node_data = new RangeMap<NodeData>(_node_num,
deba@867
   851
                                            NodeData(*_node_heap_index));
deba@867
   852
      } else {
deba@867
   853
        delete _node_data;
deba@867
   854
        _node_data = new RangeMap<NodeData>(_node_num,
deba@867
   855
                                            NodeData(*_node_heap_index));
deba@326
   856
      }
deba@326
   857
deba@326
   858
      if (!_tree_set) {
deba@326
   859
        _tree_set_index = new IntIntMap(_blossom_num);
deba@326
   860
        _tree_set = new TreeSet(*_tree_set_index);
deba@867
   861
      } else {
deba@867
   862
        _tree_set_index->resize(_blossom_num);
deba@326
   863
      }
deba@867
   864
deba@326
   865
      if (!_delta1) {
deba@327
   866
        _delta1_index = new IntNodeMap(_graph);
deba@327
   867
        _delta1 = new BinHeap<Value, IntNodeMap>(*_delta1_index);
deba@326
   868
      }
deba@867
   869
deba@326
   870
      if (!_delta2) {
deba@326
   871
        _delta2_index = new IntIntMap(_blossom_num);
deba@326
   872
        _delta2 = new BinHeap<Value, IntIntMap>(*_delta2_index);
deba@867
   873
      } else {
deba@867
   874
        _delta2_index->resize(_blossom_num);
deba@326
   875
      }
deba@867
   876
deba@326
   877
      if (!_delta3) {
deba@327
   878
        _delta3_index = new IntEdgeMap(_graph);
deba@327
   879
        _delta3 = new BinHeap<Value, IntEdgeMap>(*_delta3_index);
deba@326
   880
      }
deba@867
   881
deba@326
   882
      if (!_delta4) {
deba@326
   883
        _delta4_index = new IntIntMap(_blossom_num);
deba@326
   884
        _delta4 = new BinHeap<Value, IntIntMap>(*_delta4_index);
deba@867
   885
      } else {
deba@867
   886
        _delta4_index->resize(_blossom_num);
deba@326
   887
      }
deba@326
   888
    }
deba@326
   889
deba@326
   890
    void destroyStructures() {
deba@326
   891
      if (_matching) {
deba@326
   892
        delete _matching;
deba@326
   893
      }
deba@326
   894
      if (_node_potential) {
deba@326
   895
        delete _node_potential;
deba@326
   896
      }
deba@326
   897
      if (_blossom_set) {
deba@326
   898
        delete _blossom_index;
deba@326
   899
        delete _blossom_set;
deba@326
   900
        delete _blossom_data;
deba@326
   901
      }
deba@326
   902
deba@326
   903
      if (_node_index) {
deba@326
   904
        delete _node_index;
deba@326
   905
        delete _node_heap_index;
deba@326
   906
        delete _node_data;
deba@326
   907
      }
deba@326
   908
deba@326
   909
      if (_tree_set) {
deba@326
   910
        delete _tree_set_index;
deba@326
   911
        delete _tree_set;
deba@326
   912
      }
deba@326
   913
      if (_delta1) {
deba@326
   914
        delete _delta1_index;
deba@326
   915
        delete _delta1;
deba@326
   916
      }
deba@326
   917
      if (_delta2) {
deba@326
   918
        delete _delta2_index;
deba@326
   919
        delete _delta2;
deba@326
   920
      }
deba@326
   921
      if (_delta3) {
deba@326
   922
        delete _delta3_index;
deba@326
   923
        delete _delta3;
deba@326
   924
      }
deba@326
   925
      if (_delta4) {
deba@326
   926
        delete _delta4_index;
deba@326
   927
        delete _delta4;
deba@326
   928
      }
deba@326
   929
    }
deba@326
   930
deba@326
   931
    void matchedToEven(int blossom, int tree) {
deba@326
   932
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
deba@326
   933
        _delta2->erase(blossom);
deba@326
   934
      }
deba@326
   935
deba@326
   936
      if (!_blossom_set->trivial(blossom)) {
deba@326
   937
        (*_blossom_data)[blossom].pot -=
deba@326
   938
          2 * (_delta_sum - (*_blossom_data)[blossom].offset);
deba@326
   939
      }
deba@326
   940
deba@326
   941
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
deba@326
   942
           n != INVALID; ++n) {
deba@326
   943
deba@326
   944
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
deba@326
   945
        int ni = (*_node_index)[n];
deba@326
   946
deba@326
   947
        (*_node_data)[ni].heap.clear();
deba@326
   948
        (*_node_data)[ni].heap_index.clear();
deba@326
   949
deba@326
   950
        (*_node_data)[ni].pot += _delta_sum - (*_blossom_data)[blossom].offset;
deba@326
   951
deba@326
   952
        _delta1->push(n, (*_node_data)[ni].pot);
deba@326
   953
deba@326
   954
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
deba@326
   955
          Node v = _graph.source(e);
deba@326
   956
          int vb = _blossom_set->find(v);
deba@326
   957
          int vi = (*_node_index)[v];
deba@326
   958
deba@326
   959
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
deba@326
   960
            dualScale * _weight[e];
deba@326
   961
deba@326
   962
          if ((*_blossom_data)[vb].status == EVEN) {
deba@326
   963
            if (_delta3->state(e) != _delta3->IN_HEAP && blossom != vb) {
deba@326
   964
              _delta3->push(e, rw / 2);
deba@326
   965
            }
deba@326
   966
          } else {
deba@326
   967
            typename std::map<int, Arc>::iterator it =
deba@326
   968
              (*_node_data)[vi].heap_index.find(tree);
deba@326
   969
deba@326
   970
            if (it != (*_node_data)[vi].heap_index.end()) {
deba@326
   971
              if ((*_node_data)[vi].heap[it->second] > rw) {
deba@326
   972
                (*_node_data)[vi].heap.replace(it->second, e);
deba@326
   973
                (*_node_data)[vi].heap.decrease(e, rw);
deba@326
   974
                it->second = e;
deba@326
   975
              }
deba@326
   976
            } else {
deba@326
   977
              (*_node_data)[vi].heap.push(e, rw);
deba@326
   978
              (*_node_data)[vi].heap_index.insert(std::make_pair(tree, e));
deba@326
   979
            }
deba@326
   980
deba@326
   981
            if ((*_blossom_set)[v] > (*_node_data)[vi].heap.prio()) {
deba@326
   982
              _blossom_set->decrease(v, (*_node_data)[vi].heap.prio());
deba@326
   983
deba@326
   984
              if ((*_blossom_data)[vb].status == MATCHED) {
deba@326
   985
                if (_delta2->state(vb) != _delta2->IN_HEAP) {
deba@326
   986
                  _delta2->push(vb, _blossom_set->classPrio(vb) -
deba@326
   987
                               (*_blossom_data)[vb].offset);
deba@326
   988
                } else if ((*_delta2)[vb] > _blossom_set->classPrio(vb) -
deba@326
   989
                           (*_blossom_data)[vb].offset) {
deba@326
   990
                  _delta2->decrease(vb, _blossom_set->classPrio(vb) -
deba@326
   991
                                   (*_blossom_data)[vb].offset);
deba@326
   992
                }
deba@326
   993
              }
deba@326
   994
            }
deba@326
   995
          }
deba@326
   996
        }
deba@326
   997
      }
deba@326
   998
      (*_blossom_data)[blossom].offset = 0;
deba@326
   999
    }
deba@326
  1000
deba@868
  1001
    void matchedToOdd(int blossom) {
deba@326
  1002
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
deba@326
  1003
        _delta2->erase(blossom);
deba@326
  1004
      }
deba@868
  1005
      (*_blossom_data)[blossom].offset += _delta_sum;
deba@868
  1006
      if (!_blossom_set->trivial(blossom)) {
deba@868
  1007
        _delta4->push(blossom, (*_blossom_data)[blossom].pot / 2 +
deba@868
  1008
                      (*_blossom_data)[blossom].offset);
deba@868
  1009
      }
deba@868
  1010
    }
deba@868
  1011
deba@868
  1012
    void evenToMatched(int blossom, int tree) {
deba@868
  1013
      if (!_blossom_set->trivial(blossom)) {
deba@868
  1014
        (*_blossom_data)[blossom].pot += 2 * _delta_sum;
deba@868
  1015
      }
deba@326
  1016
deba@326
  1017
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
deba@326
  1018
           n != INVALID; ++n) {
deba@326
  1019
        int ni = (*_node_index)[n];
deba@868
  1020
        (*_node_data)[ni].pot -= _delta_sum;
deba@868
  1021
deba@868
  1022
        _delta1->erase(n);
deba@868
  1023
deba@868
  1024
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
deba@868
  1025
          Node v = _graph.source(e);
deba@326
  1026
          int vb = _blossom_set->find(v);
deba@326
  1027
          int vi = (*_node_index)[v];
deba@326
  1028
deba@326
  1029
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
deba@326
  1030
            dualScale * _weight[e];
deba@326
  1031
deba@868
  1032
          if (vb == blossom) {
deba@868
  1033
            if (_delta3->state(e) == _delta3->IN_HEAP) {
deba@868
  1034
              _delta3->erase(e);
deba@868
  1035
            }
deba@868
  1036
          } else if ((*_blossom_data)[vb].status == EVEN) {
deba@868
  1037
deba@868
  1038
            if (_delta3->state(e) == _delta3->IN_HEAP) {
deba@868
  1039
              _delta3->erase(e);
deba@868
  1040
            }
deba@868
  1041
deba@868
  1042
            int vt = _tree_set->find(vb);
deba@868
  1043
deba@868
  1044
            if (vt != tree) {
deba@868
  1045
deba@868
  1046
              Arc r = _graph.oppositeArc(e);
deba@868
  1047
deba@868
  1048
              typename std::map<int, Arc>::iterator it =
deba@868
  1049
                (*_node_data)[ni].heap_index.find(vt);
deba@868
  1050
deba@868
  1051
              if (it != (*_node_data)[ni].heap_index.end()) {
deba@868
  1052
                if ((*_node_data)[ni].heap[it->second] > rw) {
deba@868
  1053
                  (*_node_data)[ni].heap.replace(it->second, r);
deba@868
  1054
                  (*_node_data)[ni].heap.decrease(r, rw);
deba@868
  1055
                  it->second = r;
deba@868
  1056
                }
deba@868
  1057
              } else {
deba@868
  1058
                (*_node_data)[ni].heap.push(r, rw);
deba@868
  1059
                (*_node_data)[ni].heap_index.insert(std::make_pair(vt, r));
deba@868
  1060
              }
deba@868
  1061
deba@868
  1062
              if ((*_blossom_set)[n] > (*_node_data)[ni].heap.prio()) {
deba@868
  1063
                _blossom_set->decrease(n, (*_node_data)[ni].heap.prio());
deba@868
  1064
deba@868
  1065
                if (_delta2->state(blossom) != _delta2->IN_HEAP) {
deba@868
  1066
                  _delta2->push(blossom, _blossom_set->classPrio(blossom) -
deba@868
  1067
                               (*_blossom_data)[blossom].offset);
deba@868
  1068
                } else if ((*_delta2)[blossom] >
deba@868
  1069
                           _blossom_set->classPrio(blossom) -
deba@868
  1070
                           (*_blossom_data)[blossom].offset){
deba@868
  1071
                  _delta2->decrease(blossom, _blossom_set->classPrio(blossom) -
deba@868
  1072
                                   (*_blossom_data)[blossom].offset);
deba@868
  1073
                }
deba@868
  1074
              }
deba@868
  1075
            }
deba@868
  1076
          } else {
deba@868
  1077
deba@868
  1078
            typename std::map<int, Arc>::iterator it =
deba@868
  1079
              (*_node_data)[vi].heap_index.find(tree);
deba@868
  1080
deba@868
  1081
            if (it != (*_node_data)[vi].heap_index.end()) {
deba@868
  1082
              (*_node_data)[vi].heap.erase(it->second);
deba@868
  1083
              (*_node_data)[vi].heap_index.erase(it);
deba@868
  1084
              if ((*_node_data)[vi].heap.empty()) {
deba@868
  1085
                _blossom_set->increase(v, std::numeric_limits<Value>::max());
deba@868
  1086
              } else if ((*_blossom_set)[v] < (*_node_data)[vi].heap.prio()) {
deba@868
  1087
                _blossom_set->increase(v, (*_node_data)[vi].heap.prio());
deba@868
  1088
              }
deba@868
  1089
deba@868
  1090
              if ((*_blossom_data)[vb].status == MATCHED) {
deba@868
  1091
                if (_blossom_set->classPrio(vb) ==
deba@868
  1092
                    std::numeric_limits<Value>::max()) {
deba@868
  1093
                  _delta2->erase(vb);
deba@868
  1094
                } else if ((*_delta2)[vb] < _blossom_set->classPrio(vb) -
deba@868
  1095
                           (*_blossom_data)[vb].offset) {
deba@868
  1096
                  _delta2->increase(vb, _blossom_set->classPrio(vb) -
deba@868
  1097
                                   (*_blossom_data)[vb].offset);
deba@868
  1098
                }
deba@868
  1099
              }
deba@326
  1100
            }
deba@326
  1101
          }
deba@326
  1102
        }
deba@326
  1103
      }
deba@326
  1104
    }
deba@326
  1105
deba@868
  1106
    void oddToMatched(int blossom) {
deba@868
  1107
      (*_blossom_data)[blossom].offset -= _delta_sum;
deba@868
  1108
deba@868
  1109
      if (_blossom_set->classPrio(blossom) !=
deba@868
  1110
          std::numeric_limits<Value>::max()) {
deba@868
  1111
        _delta2->push(blossom, _blossom_set->classPrio(blossom) -
deba@868
  1112
                      (*_blossom_data)[blossom].offset);
deba@868
  1113
      }
deba@868
  1114
deba@868
  1115
      if (!_blossom_set->trivial(blossom)) {
deba@868
  1116
        _delta4->erase(blossom);
deba@868
  1117
      }
deba@868
  1118
    }
deba@868
  1119
deba@868
  1120
    void oddToEven(int blossom, int tree) {
deba@868
  1121
      if (!_blossom_set->trivial(blossom)) {
deba@868
  1122
        _delta4->erase(blossom);
deba@868
  1123
        (*_blossom_data)[blossom].pot -=
deba@868
  1124
          2 * (2 * _delta_sum - (*_blossom_data)[blossom].offset);
deba@868
  1125
      }
deba@868
  1126
deba@326
  1127
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
deba@326
  1128
           n != INVALID; ++n) {
deba@326
  1129
        int ni = (*_node_index)[n];
deba@326
  1130
deba@868
  1131
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
deba@868
  1132
deba@868
  1133
        (*_node_data)[ni].heap.clear();
deba@868
  1134
        (*_node_data)[ni].heap_index.clear();
deba@868
  1135
        (*_node_data)[ni].pot +=
deba@868
  1136
          2 * _delta_sum - (*_blossom_data)[blossom].offset;
deba@868
  1137
deba@868
  1138
        _delta1->push(n, (*_node_data)[ni].pot);
deba@868
  1139
deba@326
  1140
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
deba@326
  1141
          Node v = _graph.source(e);
deba@326
  1142
          int vb = _blossom_set->find(v);
deba@326
  1143
          int vi = (*_node_index)[v];
deba@326
  1144
deba@326
  1145
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
deba@326
  1146
            dualScale * _weight[e];
deba@326
  1147
deba@868
  1148
          if ((*_blossom_data)[vb].status == EVEN) {
deba@868
  1149
            if (_delta3->state(e) != _delta3->IN_HEAP && blossom != vb) {
deba@868
  1150
              _delta3->push(e, rw / 2);
deba@326
  1151
            }
deba@868
  1152
          } else {
deba@326
  1153
deba@326
  1154
            typename std::map<int, Arc>::iterator it =
deba@868
  1155
              (*_node_data)[vi].heap_index.find(tree);
deba@868
  1156
deba@868
  1157
            if (it != (*_node_data)[vi].heap_index.end()) {
deba@868
  1158
              if ((*_node_data)[vi].heap[it->second] > rw) {
deba@868
  1159
                (*_node_data)[vi].heap.replace(it->second, e);
deba@868
  1160
                (*_node_data)[vi].heap.decrease(e, rw);
deba@868
  1161
                it->second = e;
deba@326
  1162
              }
deba@326
  1163
            } else {
deba@868
  1164
              (*_node_data)[vi].heap.push(e, rw);
deba@868
  1165
              (*_node_data)[vi].heap_index.insert(std::make_pair(tree, e));
deba@326
  1166
            }
deba@326
  1167
deba@868
  1168
            if ((*_blossom_set)[v] > (*_node_data)[vi].heap.prio()) {
deba@868
  1169
              _blossom_set->decrease(v, (*_node_data)[vi].heap.prio());
deba@868
  1170
deba@868
  1171
              if ((*_blossom_data)[vb].status == MATCHED) {
deba@868
  1172
                if (_delta2->state(vb) != _delta2->IN_HEAP) {
deba@868
  1173
                  _delta2->push(vb, _blossom_set->classPrio(vb) -
deba@868
  1174
                               (*_blossom_data)[vb].offset);
deba@868
  1175
                } else if ((*_delta2)[vb] > _blossom_set->classPrio(vb) -
deba@868
  1176
                           (*_blossom_data)[vb].offset) {
deba@868
  1177
                  _delta2->decrease(vb, _blossom_set->classPrio(vb) -
deba@868
  1178
                                   (*_blossom_data)[vb].offset);
deba@868
  1179
                }
deba@326
  1180
              }
deba@326
  1181
            }
deba@326
  1182
          }
deba@326
  1183
        }
deba@326
  1184
      }
deba@868
  1185
      (*_blossom_data)[blossom].offset = 0;
deba@326
  1186
    }
deba@326
  1187
deba@326
  1188
    void alternatePath(int even, int tree) {
deba@326
  1189
      int odd;
deba@326
  1190
deba@326
  1191
      evenToMatched(even, tree);
deba@326
  1192
      (*_blossom_data)[even].status = MATCHED;
deba@326
  1193
deba@326
  1194
      while ((*_blossom_data)[even].pred != INVALID) {
deba@326
  1195
        odd = _blossom_set->find(_graph.target((*_blossom_data)[even].pred));
deba@326
  1196
        (*_blossom_data)[odd].status = MATCHED;
deba@326
  1197
        oddToMatched(odd);
deba@326
  1198
        (*_blossom_data)[odd].next = (*_blossom_data)[odd].pred;
deba@326
  1199
deba@326
  1200
        even = _blossom_set->find(_graph.target((*_blossom_data)[odd].pred));
deba@326
  1201
        (*_blossom_data)[even].status = MATCHED;
deba@326
  1202
        evenToMatched(even, tree);
deba@326
  1203
        (*_blossom_data)[even].next =
deba@326
  1204
          _graph.oppositeArc((*_blossom_data)[odd].pred);
deba@326
  1205
      }
deba@326
  1206
deba@326
  1207
    }
deba@326
  1208
deba@326
  1209
    void destroyTree(int tree) {
deba@326
  1210
      for (TreeSet::ItemIt b(*_tree_set, tree); b != INVALID; ++b) {
deba@326
  1211
        if ((*_blossom_data)[b].status == EVEN) {
deba@326
  1212
          (*_blossom_data)[b].status = MATCHED;
deba@326
  1213
          evenToMatched(b, tree);
deba@326
  1214
        } else if ((*_blossom_data)[b].status == ODD) {
deba@326
  1215
          (*_blossom_data)[b].status = MATCHED;
deba@326
  1216
          oddToMatched(b);
deba@326
  1217
        }
deba@326
  1218
      }
deba@326
  1219
      _tree_set->eraseClass(tree);
deba@326
  1220
    }
deba@326
  1221
deba@326
  1222
deba@326
  1223
    void unmatchNode(const Node& node) {
deba@326
  1224
      int blossom = _blossom_set->find(node);
deba@326
  1225
      int tree = _tree_set->find(blossom);
deba@326
  1226
deba@326
  1227
      alternatePath(blossom, tree);
deba@326
  1228
      destroyTree(tree);
deba@326
  1229
deba@326
  1230
      (*_blossom_data)[blossom].base = node;
deba@868
  1231
      (*_blossom_data)[blossom].next = INVALID;
deba@326
  1232
    }
deba@326
  1233
deba@327
  1234
    void augmentOnEdge(const Edge& edge) {
deba@327
  1235
deba@327
  1236
      int left = _blossom_set->find(_graph.u(edge));
deba@327
  1237
      int right = _blossom_set->find(_graph.v(edge));
deba@326
  1238
deba@868
  1239
      int left_tree = _tree_set->find(left);
deba@868
  1240
      alternatePath(left, left_tree);
deba@868
  1241
      destroyTree(left_tree);
deba@868
  1242
deba@868
  1243
      int right_tree = _tree_set->find(right);
deba@868
  1244
      alternatePath(right, right_tree);
deba@868
  1245
      destroyTree(right_tree);
deba@326
  1246
deba@327
  1247
      (*_blossom_data)[left].next = _graph.direct(edge, true);
deba@327
  1248
      (*_blossom_data)[right].next = _graph.direct(edge, false);
deba@326
  1249
    }
deba@326
  1250
deba@868
  1251
    void augmentOnArc(const Arc& arc) {
deba@868
  1252
deba@868
  1253
      int left = _blossom_set->find(_graph.source(arc));
deba@868
  1254
      int right = _blossom_set->find(_graph.target(arc));
deba@868
  1255
deba@868
  1256
      (*_blossom_data)[left].status = MATCHED;
deba@868
  1257
deba@868
  1258
      int right_tree = _tree_set->find(right);
deba@868
  1259
      alternatePath(right, right_tree);
deba@868
  1260
      destroyTree(right_tree);
deba@868
  1261
deba@868
  1262
      (*_blossom_data)[left].next = arc;
deba@868
  1263
      (*_blossom_data)[right].next = _graph.oppositeArc(arc);
deba@868
  1264
    }
deba@868
  1265
deba@326
  1266
    void extendOnArc(const Arc& arc) {
deba@326
  1267
      int base = _blossom_set->find(_graph.target(arc));
deba@326
  1268
      int tree = _tree_set->find(base);
deba@326
  1269
deba@326
  1270
      int odd = _blossom_set->find(_graph.source(arc));
deba@326
  1271
      _tree_set->insert(odd, tree);
deba@326
  1272
      (*_blossom_data)[odd].status = ODD;
deba@326
  1273
      matchedToOdd(odd);
deba@326
  1274
      (*_blossom_data)[odd].pred = arc;
deba@326
  1275
deba@326
  1276
      int even = _blossom_set->find(_graph.target((*_blossom_data)[odd].next));
deba@326
  1277
      (*_blossom_data)[even].pred = (*_blossom_data)[even].next;
deba@326
  1278
      _tree_set->insert(even, tree);
deba@326
  1279
      (*_blossom_data)[even].status = EVEN;
deba@326
  1280
      matchedToEven(even, tree);
deba@326
  1281
    }
deba@326
  1282
deba@327
  1283
    void shrinkOnEdge(const Edge& edge, int tree) {
deba@326
  1284
      int nca = -1;
deba@326
  1285
      std::vector<int> left_path, right_path;
deba@326
  1286
deba@326
  1287
      {
deba@326
  1288
        std::set<int> left_set, right_set;
deba@326
  1289
        int left = _blossom_set->find(_graph.u(edge));
deba@326
  1290
        left_path.push_back(left);
deba@326
  1291
        left_set.insert(left);
deba@326
  1292
deba@326
  1293
        int right = _blossom_set->find(_graph.v(edge));
deba@326
  1294
        right_path.push_back(right);
deba@326
  1295
        right_set.insert(right);
deba@326
  1296
deba@326
  1297
        while (true) {
deba@326
  1298
deba@326
  1299
          if ((*_blossom_data)[left].pred == INVALID) break;
deba@326
  1300
deba@326
  1301
          left =
deba@326
  1302
            _blossom_set->find(_graph.target((*_blossom_data)[left].pred));
deba@326
  1303
          left_path.push_back(left);
deba@326
  1304
          left =
deba@326
  1305
            _blossom_set->find(_graph.target((*_blossom_data)[left].pred));
deba@326
  1306
          left_path.push_back(left);
deba@326
  1307
deba@326
  1308
          left_set.insert(left);
deba@326
  1309
deba@326
  1310
          if (right_set.find(left) != right_set.end()) {
deba@326
  1311
            nca = left;
deba@326
  1312
            break;
deba@326
  1313
          }
deba@326
  1314
deba@326
  1315
          if ((*_blossom_data)[right].pred == INVALID) break;
deba@326
  1316
deba@326
  1317
          right =
deba@326
  1318
            _blossom_set->find(_graph.target((*_blossom_data)[right].pred));
deba@326
  1319
          right_path.push_back(right);
deba@326
  1320
          right =
deba@326
  1321
            _blossom_set->find(_graph.target((*_blossom_data)[right].pred));
deba@326
  1322
          right_path.push_back(right);
deba@326
  1323
deba@326
  1324
          right_set.insert(right);
deba@326
  1325
deba@326
  1326
          if (left_set.find(right) != left_set.end()) {
deba@326
  1327
            nca = right;
deba@326
  1328
            break;
deba@326
  1329
          }
deba@326
  1330
deba@326
  1331
        }
deba@326
  1332
deba@326
  1333
        if (nca == -1) {
deba@326
  1334
          if ((*_blossom_data)[left].pred == INVALID) {
deba@326
  1335
            nca = right;
deba@326
  1336
            while (left_set.find(nca) == left_set.end()) {
deba@326
  1337
              nca =
deba@326
  1338
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
deba@326
  1339
              right_path.push_back(nca);
deba@326
  1340
              nca =
deba@326
  1341
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
deba@326
  1342
              right_path.push_back(nca);
deba@326
  1343
            }
deba@326
  1344
          } else {
deba@326
  1345
            nca = left;
deba@326
  1346
            while (right_set.find(nca) == right_set.end()) {
deba@326
  1347
              nca =
deba@326
  1348
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
deba@326
  1349
              left_path.push_back(nca);
deba@326
  1350
              nca =
deba@326
  1351
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
deba@326
  1352
              left_path.push_back(nca);
deba@326
  1353
            }
deba@326
  1354
          }
deba@326
  1355
        }
deba@326
  1356
      }
deba@326
  1357
deba@326
  1358
      std::vector<int> subblossoms;
deba@326
  1359
      Arc prev;
deba@326
  1360
deba@326
  1361
      prev = _graph.direct(edge, true);
deba@326
  1362
      for (int i = 0; left_path[i] != nca; i += 2) {
deba@326
  1363
        subblossoms.push_back(left_path[i]);
deba@326
  1364
        (*_blossom_data)[left_path[i]].next = prev;
deba@326
  1365
        _tree_set->erase(left_path[i]);
deba@326
  1366
deba@326
  1367
        subblossoms.push_back(left_path[i + 1]);
deba@326
  1368
        (*_blossom_data)[left_path[i + 1]].status = EVEN;
deba@326
  1369
        oddToEven(left_path[i + 1], tree);
deba@326
  1370
        _tree_set->erase(left_path[i + 1]);
deba@326
  1371
        prev = _graph.oppositeArc((*_blossom_data)[left_path[i + 1]].pred);
deba@326
  1372
      }
deba@326
  1373
deba@326
  1374
      int k = 0;
deba@326
  1375
      while (right_path[k] != nca) ++k;
deba@326
  1376
deba@326
  1377
      subblossoms.push_back(nca);
deba@326
  1378
      (*_blossom_data)[nca].next = prev;
deba@326
  1379
deba@326
  1380
      for (int i = k - 2; i >= 0; i -= 2) {
deba@326
  1381
        subblossoms.push_back(right_path[i + 1]);
deba@326
  1382
        (*_blossom_data)[right_path[i + 1]].status = EVEN;
deba@326
  1383
        oddToEven(right_path[i + 1], tree);
deba@326
  1384
        _tree_set->erase(right_path[i + 1]);
deba@326
  1385
deba@326
  1386
        (*_blossom_data)[right_path[i + 1]].next =
deba@326
  1387
          (*_blossom_data)[right_path[i + 1]].pred;
deba@326
  1388
deba@326
  1389
        subblossoms.push_back(right_path[i]);
deba@326
  1390
        _tree_set->erase(right_path[i]);
deba@326
  1391
      }
deba@326
  1392
deba@326
  1393
      int surface =
deba@326
  1394
        _blossom_set->join(subblossoms.begin(), subblossoms.end());
deba@326
  1395
deba@326
  1396
      for (int i = 0; i < int(subblossoms.size()); ++i) {
deba@326
  1397
        if (!_blossom_set->trivial(subblossoms[i])) {
deba@326
  1398
          (*_blossom_data)[subblossoms[i]].pot += 2 * _delta_sum;
deba@326
  1399
        }
deba@326
  1400
        (*_blossom_data)[subblossoms[i]].status = MATCHED;
deba@326
  1401
      }
deba@326
  1402
deba@326
  1403
      (*_blossom_data)[surface].pot = -2 * _delta_sum;
deba@326
  1404
      (*_blossom_data)[surface].offset = 0;
deba@326
  1405
      (*_blossom_data)[surface].status = EVEN;
deba@326
  1406
      (*_blossom_data)[surface].pred = (*_blossom_data)[nca].pred;
deba@326
  1407
      (*_blossom_data)[surface].next = (*_blossom_data)[nca].pred;
deba@326
  1408
deba@326
  1409
      _tree_set->insert(surface, tree);
deba@326
  1410
      _tree_set->erase(nca);
deba@326
  1411
    }
deba@326
  1412
deba@326
  1413
    void splitBlossom(int blossom) {
deba@326
  1414
      Arc next = (*_blossom_data)[blossom].next;
deba@326
  1415
      Arc pred = (*_blossom_data)[blossom].pred;
deba@326
  1416
deba@326
  1417
      int tree = _tree_set->find(blossom);
deba@326
  1418
deba@326
  1419
      (*_blossom_data)[blossom].status = MATCHED;
deba@326
  1420
      oddToMatched(blossom);
deba@326
  1421
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
deba@326
  1422
        _delta2->erase(blossom);
deba@326
  1423
      }
deba@326
  1424
deba@326
  1425
      std::vector<int> subblossoms;
deba@326
  1426
      _blossom_set->split(blossom, std::back_inserter(subblossoms));
deba@326
  1427
deba@326
  1428
      Value offset = (*_blossom_data)[blossom].offset;
deba@326
  1429
      int b = _blossom_set->find(_graph.source(pred));
deba@326
  1430
      int d = _blossom_set->find(_graph.source(next));
deba@326
  1431
deba@326
  1432
      int ib = -1, id = -1;
deba@326
  1433
      for (int i = 0; i < int(subblossoms.size()); ++i) {
deba@326
  1434
        if (subblossoms[i] == b) ib = i;
deba@326
  1435
        if (subblossoms[i] == d) id = i;
deba@326
  1436
deba@326
  1437
        (*_blossom_data)[subblossoms[i]].offset = offset;
deba@326
  1438
        if (!_blossom_set->trivial(subblossoms[i])) {
deba@326
  1439
          (*_blossom_data)[subblossoms[i]].pot -= 2 * offset;
deba@326
  1440
        }
deba@326
  1441
        if (_blossom_set->classPrio(subblossoms[i]) !=
deba@326
  1442
            std::numeric_limits<Value>::max()) {
deba@326
  1443
          _delta2->push(subblossoms[i],
deba@326
  1444
                        _blossom_set->classPrio(subblossoms[i]) -
deba@326
  1445
                        (*_blossom_data)[subblossoms[i]].offset);
deba@326
  1446
        }
deba@326
  1447
      }
deba@326
  1448
deba@326
  1449
      if (id > ib ? ((id - ib) % 2 == 0) : ((ib - id) % 2 == 1)) {
deba@326
  1450
        for (int i = (id + 1) % subblossoms.size();
deba@326
  1451
             i != ib; i = (i + 2) % subblossoms.size()) {
deba@326
  1452
          int sb = subblossoms[i];
deba@326
  1453
          int tb = subblossoms[(i + 1) % subblossoms.size()];
deba@326
  1454
          (*_blossom_data)[sb].next =
deba@326
  1455
            _graph.oppositeArc((*_blossom_data)[tb].next);
deba@326
  1456
        }
deba@326
  1457
deba@326
  1458
        for (int i = ib; i != id; i = (i + 2) % subblossoms.size()) {
deba@326
  1459
          int sb = subblossoms[i];
deba@326
  1460
          int tb = subblossoms[(i + 1) % subblossoms.size()];
deba@326
  1461
          int ub = subblossoms[(i + 2) % subblossoms.size()];
deba@326
  1462
deba@326
  1463
          (*_blossom_data)[sb].status = ODD;
deba@326
  1464
          matchedToOdd(sb);
deba@326
  1465
          _tree_set->insert(sb, tree);
deba@326
  1466
          (*_blossom_data)[sb].pred = pred;
deba@326
  1467
          (*_blossom_data)[sb].next =
deba@868
  1468
            _graph.oppositeArc((*_blossom_data)[tb].next);
deba@326
  1469
deba@326
  1470
          pred = (*_blossom_data)[ub].next;
deba@326
  1471
deba@326
  1472
          (*_blossom_data)[tb].status = EVEN;
deba@326
  1473
          matchedToEven(tb, tree);
deba@326
  1474
          _tree_set->insert(tb, tree);
deba@326
  1475
          (*_blossom_data)[tb].pred = (*_blossom_data)[tb].next;
deba@326
  1476
        }
deba@326
  1477
deba@326
  1478
        (*_blossom_data)[subblossoms[id]].status = ODD;
deba@326
  1479
        matchedToOdd(subblossoms[id]);
deba@326
  1480
        _tree_set->insert(subblossoms[id], tree);
deba@326
  1481
        (*_blossom_data)[subblossoms[id]].next = next;
deba@326
  1482
        (*_blossom_data)[subblossoms[id]].pred = pred;
deba@326
  1483
deba@326
  1484
      } else {
deba@326
  1485
deba@326
  1486
        for (int i = (ib + 1) % subblossoms.size();
deba@326
  1487
             i != id; i = (i + 2) % subblossoms.size()) {
deba@326
  1488
          int sb = subblossoms[i];
deba@326
  1489
          int tb = subblossoms[(i + 1) % subblossoms.size()];
deba@326
  1490
          (*_blossom_data)[sb].next =
deba@326
  1491
            _graph.oppositeArc((*_blossom_data)[tb].next);
deba@326
  1492
        }
deba@326
  1493
deba@326
  1494
        for (int i = id; i != ib; i = (i + 2) % subblossoms.size()) {
deba@326
  1495
          int sb = subblossoms[i];
deba@326
  1496
          int tb = subblossoms[(i + 1) % subblossoms.size()];
deba@326
  1497
          int ub = subblossoms[(i + 2) % subblossoms.size()];
deba@326
  1498
deba@326
  1499
          (*_blossom_data)[sb].status = ODD;
deba@326
  1500
          matchedToOdd(sb);
deba@326
  1501
          _tree_set->insert(sb, tree);
deba@326
  1502
          (*_blossom_data)[sb].next = next;
deba@326
  1503
          (*_blossom_data)[sb].pred =
deba@326
  1504
            _graph.oppositeArc((*_blossom_data)[tb].next);
deba@326
  1505
deba@326
  1506
          (*_blossom_data)[tb].status = EVEN;
deba@326
  1507
          matchedToEven(tb, tree);
deba@326
  1508
          _tree_set->insert(tb, tree);
deba@326
  1509
          (*_blossom_data)[tb].pred =
deba@326
  1510
            (*_blossom_data)[tb].next =
deba@326
  1511
            _graph.oppositeArc((*_blossom_data)[ub].next);
deba@326
  1512
          next = (*_blossom_data)[ub].next;
deba@326
  1513
        }
deba@326
  1514
deba@326
  1515
        (*_blossom_data)[subblossoms[ib]].status = ODD;
deba@326
  1516
        matchedToOdd(subblossoms[ib]);
deba@326
  1517
        _tree_set->insert(subblossoms[ib], tree);
deba@326
  1518
        (*_blossom_data)[subblossoms[ib]].next = next;
deba@326
  1519
        (*_blossom_data)[subblossoms[ib]].pred = pred;
deba@326
  1520
      }
deba@326
  1521
      _tree_set->erase(blossom);
deba@326
  1522
    }
deba@326
  1523
deba@1208
  1524
    struct ExtractBlossomItem {
deba@1208
  1525
      int blossom;
deba@1208
  1526
      Node base;
deba@1208
  1527
      Arc matching;
deba@1208
  1528
      int close_index;
deba@1208
  1529
      ExtractBlossomItem(int _blossom, Node _base,
deba@1208
  1530
                         Arc _matching, int _close_index)
deba@1208
  1531
          : blossom(_blossom), base(_base), matching(_matching),
deba@1208
  1532
            close_index(_close_index) {}
deba@1208
  1533
    };
deba@1208
  1534
deba@326
  1535
    void extractBlossom(int blossom, const Node& base, const Arc& matching) {
deba@1208
  1536
      std::vector<ExtractBlossomItem> stack;
deba@1208
  1537
      std::vector<int> close_stack;
deba@1208
  1538
      stack.push_back(ExtractBlossomItem(blossom, base, matching, 0));
deba@1208
  1539
      while (!stack.empty()) {
deba@1208
  1540
        if (_blossom_set->trivial(stack.back().blossom)) {
deba@1208
  1541
          int bi = (*_node_index)[stack.back().base];
deba@1208
  1542
          Value pot = (*_node_data)[bi].pot;
deba@1208
  1543
deba@1208
  1544
          (*_matching)[stack.back().base] = stack.back().matching;
deba@1208
  1545
          (*_node_potential)[stack.back().base] = pot;
deba@1208
  1546
          _blossom_node_list.push_back(stack.back().base);
deba@1208
  1547
          while (int(close_stack.size()) > stack.back().close_index) {
deba@1208
  1548
            _blossom_potential[close_stack.back()].end = _blossom_node_list.size();
deba@1208
  1549
            close_stack.pop_back();
deba@1208
  1550
          }
deba@1208
  1551
          stack.pop_back();
deba@1208
  1552
        } else {
deba@1208
  1553
          Value pot = (*_blossom_data)[stack.back().blossom].pot;
deba@1208
  1554
          int bn = _blossom_node_list.size();
deba@1208
  1555
          close_stack.push_back(_blossom_potential.size());
deba@1208
  1556
          _blossom_potential.push_back(BlossomVariable(bn, pot));
deba@1208
  1557
deba@1208
  1558
          std::vector<int> subblossoms;
deba@1208
  1559
          _blossom_set->split(stack.back().blossom, std::back_inserter(subblossoms));
deba@1208
  1560
          int b = _blossom_set->find(stack.back().base);
deba@1208
  1561
          int ib = -1;
deba@1208
  1562
          for (int i = 0; i < int(subblossoms.size()); ++i) {
deba@1208
  1563
            if (subblossoms[i] == b) { ib = i; break; }
deba@1208
  1564
          }
deba@1208
  1565
deba@1208
  1566
          stack.back().blossom = subblossoms[ib];
deba@1208
  1567
          for (int i = 1; i < int(subblossoms.size()); i += 2) {
deba@1208
  1568
            int sb = subblossoms[(ib + i) % subblossoms.size()];
deba@1208
  1569
            int tb = subblossoms[(ib + i + 1) % subblossoms.size()];
deba@1208
  1570
deba@1208
  1571
            Arc m = (*_blossom_data)[tb].next;
deba@1208
  1572
            stack.push_back(ExtractBlossomItem(
deba@1208
  1573
                sb, _graph.target(m), _graph.oppositeArc(m), close_stack.size()));
deba@1208
  1574
            stack.push_back(ExtractBlossomItem(
deba@1208
  1575
                tb, _graph.source(m), m, close_stack.size()));
deba@1208
  1576
          }
deba@326
  1577
        }
deba@326
  1578
      }
deba@326
  1579
    }
deba@326
  1580
deba@326
  1581
    void extractMatching() {
deba@326
  1582
      std::vector<int> blossoms;
deba@326
  1583
      for (typename BlossomSet::ClassIt c(*_blossom_set); c != INVALID; ++c) {
deba@326
  1584
        blossoms.push_back(c);
deba@326
  1585
      }
deba@326
  1586
deba@326
  1587
      for (int i = 0; i < int(blossoms.size()); ++i) {
deba@868
  1588
        if ((*_blossom_data)[blossoms[i]].next != INVALID) {
deba@326
  1589
deba@326
  1590
          Value offset = (*_blossom_data)[blossoms[i]].offset;
deba@326
  1591
          (*_blossom_data)[blossoms[i]].pot += 2 * offset;
deba@326
  1592
          for (typename BlossomSet::ItemIt n(*_blossom_set, blossoms[i]);
deba@326
  1593
               n != INVALID; ++n) {
deba@326
  1594
            (*_node_data)[(*_node_index)[n]].pot -= offset;
deba@326
  1595
          }
deba@326
  1596
deba@326
  1597
          Arc matching = (*_blossom_data)[blossoms[i]].next;
deba@326
  1598
          Node base = _graph.source(matching);
deba@326
  1599
          extractBlossom(blossoms[i], base, matching);
deba@326
  1600
        } else {
deba@326
  1601
          Node base = (*_blossom_data)[blossoms[i]].base;
deba@326
  1602
          extractBlossom(blossoms[i], base, INVALID);
deba@326
  1603
        }
deba@326
  1604
      }
deba@326
  1605
    }
deba@326
  1606
deba@326
  1607
  public:
deba@326
  1608
deba@326
  1609
    /// \brief Constructor
deba@326
  1610
    ///
deba@326
  1611
    /// Constructor.
deba@326
  1612
    MaxWeightedMatching(const Graph& graph, const WeightMap& weight)
deba@326
  1613
      : _graph(graph), _weight(weight), _matching(0),
deba@326
  1614
        _node_potential(0), _blossom_potential(), _blossom_node_list(),
deba@326
  1615
        _node_num(0), _blossom_num(0),
deba@326
  1616
deba@326
  1617
        _blossom_index(0), _blossom_set(0), _blossom_data(0),
deba@326
  1618
        _node_index(0), _node_heap_index(0), _node_data(0),
deba@326
  1619
        _tree_set_index(0), _tree_set(0),
deba@326
  1620
deba@326
  1621
        _delta1_index(0), _delta1(0),
deba@326
  1622
        _delta2_index(0), _delta2(0),
deba@326
  1623
        _delta3_index(0), _delta3(0),
deba@326
  1624
        _delta4_index(0), _delta4(0),
deba@326
  1625
deba@870
  1626
        _delta_sum(), _unmatched(0),
deba@870
  1627
deba@870
  1628
        _fractional(0)
deba@870
  1629
    {}
deba@326
  1630
deba@326
  1631
    ~MaxWeightedMatching() {
deba@326
  1632
      destroyStructures();
deba@870
  1633
      if (_fractional) {
deba@870
  1634
        delete _fractional;
deba@870
  1635
      }
deba@326
  1636
    }
deba@326
  1637
kpeter@590
  1638
    /// \name Execution Control
alpar@330
  1639
    /// The simplest way to execute the algorithm is to use the
kpeter@590
  1640
    /// \ref run() member function.
deba@326
  1641
deba@326
  1642
    ///@{
deba@326
  1643
deba@326
  1644
    /// \brief Initialize the algorithm
deba@326
  1645
    ///
kpeter@590
  1646
    /// This function initializes the algorithm.
deba@326
  1647
    void init() {
deba@326
  1648
      createStructures();
deba@326
  1649
deba@867
  1650
      _blossom_node_list.clear();
deba@867
  1651
      _blossom_potential.clear();
deba@867
  1652
deba@326
  1653
      for (ArcIt e(_graph); e != INVALID; ++e) {
kpeter@581
  1654
        (*_node_heap_index)[e] = BinHeap<Value, IntArcMap>::PRE_HEAP;
deba@326
  1655
      }
deba@326
  1656
      for (NodeIt n(_graph); n != INVALID; ++n) {
kpeter@581
  1657
        (*_delta1_index)[n] = _delta1->PRE_HEAP;
deba@326
  1658
      }
deba@326
  1659
      for (EdgeIt e(_graph); e != INVALID; ++e) {
kpeter@581
  1660
        (*_delta3_index)[e] = _delta3->PRE_HEAP;
deba@326
  1661
      }
deba@326
  1662
      for (int i = 0; i < _blossom_num; ++i) {
kpeter@581
  1663
        (*_delta2_index)[i] = _delta2->PRE_HEAP;
kpeter@581
  1664
        (*_delta4_index)[i] = _delta4->PRE_HEAP;
deba@326
  1665
      }
alpar@877
  1666
deba@870
  1667
      _unmatched = _node_num;
deba@870
  1668
deba@867
  1669
      _delta1->clear();
deba@867
  1670
      _delta2->clear();
deba@867
  1671
      _delta3->clear();
deba@867
  1672
      _delta4->clear();
deba@867
  1673
      _blossom_set->clear();
deba@867
  1674
      _tree_set->clear();
deba@326
  1675
deba@326
  1676
      int index = 0;
deba@326
  1677
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@326
  1678
        Value max = 0;
deba@326
  1679
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
deba@326
  1680
          if (_graph.target(e) == n) continue;
deba@326
  1681
          if ((dualScale * _weight[e]) / 2 > max) {
deba@326
  1682
            max = (dualScale * _weight[e]) / 2;
deba@326
  1683
          }
deba@326
  1684
        }
kpeter@581
  1685
        (*_node_index)[n] = index;
deba@867
  1686
        (*_node_data)[index].heap_index.clear();
deba@867
  1687
        (*_node_data)[index].heap.clear();
deba@326
  1688
        (*_node_data)[index].pot = max;
deba@326
  1689
        _delta1->push(n, max);
deba@326
  1690
        int blossom =
deba@326
  1691
          _blossom_set->insert(n, std::numeric_limits<Value>::max());
deba@326
  1692
deba@326
  1693
        _tree_set->insert(blossom);
deba@326
  1694
deba@326
  1695
        (*_blossom_data)[blossom].status = EVEN;
deba@326
  1696
        (*_blossom_data)[blossom].pred = INVALID;
deba@326
  1697
        (*_blossom_data)[blossom].next = INVALID;
deba@326
  1698
        (*_blossom_data)[blossom].pot = 0;
deba@326
  1699
        (*_blossom_data)[blossom].offset = 0;
deba@326
  1700
        ++index;
deba@326
  1701
      }
deba@326
  1702
      for (EdgeIt e(_graph); e != INVALID; ++e) {
deba@326
  1703
        int si = (*_node_index)[_graph.u(e)];
deba@326
  1704
        int ti = (*_node_index)[_graph.v(e)];
deba@326
  1705
        if (_graph.u(e) != _graph.v(e)) {
deba@326
  1706
          _delta3->push(e, ((*_node_data)[si].pot + (*_node_data)[ti].pot -
deba@326
  1707
                            dualScale * _weight[e]) / 2);
deba@326
  1708
        }
deba@326
  1709
      }
deba@326
  1710
    }
deba@326
  1711
deba@870
  1712
    /// \brief Initialize the algorithm with fractional matching
deba@870
  1713
    ///
deba@870
  1714
    /// This function initializes the algorithm with a fractional
deba@870
  1715
    /// matching. This initialization is also called jumpstart heuristic.
deba@870
  1716
    void fractionalInit() {
deba@870
  1717
      createStructures();
deba@876
  1718
deba@876
  1719
      _blossom_node_list.clear();
deba@876
  1720
      _blossom_potential.clear();
alpar@877
  1721
deba@870
  1722
      if (_fractional == 0) {
deba@870
  1723
        _fractional = new FractionalMatching(_graph, _weight, false);
deba@870
  1724
      }
deba@870
  1725
      _fractional->run();
deba@870
  1726
deba@870
  1727
      for (ArcIt e(_graph); e != INVALID; ++e) {
deba@870
  1728
        (*_node_heap_index)[e] = BinHeap<Value, IntArcMap>::PRE_HEAP;
deba@870
  1729
      }
deba@870
  1730
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@870
  1731
        (*_delta1_index)[n] = _delta1->PRE_HEAP;
deba@870
  1732
      }
deba@870
  1733
      for (EdgeIt e(_graph); e != INVALID; ++e) {
deba@870
  1734
        (*_delta3_index)[e] = _delta3->PRE_HEAP;
deba@870
  1735
      }
deba@870
  1736
      for (int i = 0; i < _blossom_num; ++i) {
deba@870
  1737
        (*_delta2_index)[i] = _delta2->PRE_HEAP;
deba@870
  1738
        (*_delta4_index)[i] = _delta4->PRE_HEAP;
deba@870
  1739
      }
deba@870
  1740
deba@870
  1741
      _unmatched = 0;
deba@870
  1742
deba@876
  1743
      _delta1->clear();
deba@876
  1744
      _delta2->clear();
deba@876
  1745
      _delta3->clear();
deba@876
  1746
      _delta4->clear();
deba@876
  1747
      _blossom_set->clear();
deba@876
  1748
      _tree_set->clear();
deba@876
  1749
deba@870
  1750
      int index = 0;
deba@870
  1751
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@870
  1752
        Value pot = _fractional->nodeValue(n);
deba@870
  1753
        (*_node_index)[n] = index;
deba@870
  1754
        (*_node_data)[index].pot = pot;
deba@876
  1755
        (*_node_data)[index].heap_index.clear();
deba@876
  1756
        (*_node_data)[index].heap.clear();
deba@870
  1757
        int blossom =
deba@870
  1758
          _blossom_set->insert(n, std::numeric_limits<Value>::max());
deba@870
  1759
deba@870
  1760
        (*_blossom_data)[blossom].status = MATCHED;
deba@870
  1761
        (*_blossom_data)[blossom].pred = INVALID;
deba@870
  1762
        (*_blossom_data)[blossom].next = _fractional->matching(n);
deba@870
  1763
        if (_fractional->matching(n) == INVALID) {
deba@870
  1764
          (*_blossom_data)[blossom].base = n;
deba@870
  1765
        }
deba@870
  1766
        (*_blossom_data)[blossom].pot = 0;
deba@870
  1767
        (*_blossom_data)[blossom].offset = 0;
deba@870
  1768
        ++index;
deba@870
  1769
      }
deba@870
  1770
deba@870
  1771
      typename Graph::template NodeMap<bool> processed(_graph, false);
deba@870
  1772
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@870
  1773
        if (processed[n]) continue;
deba@870
  1774
        processed[n] = true;
deba@870
  1775
        if (_fractional->matching(n) == INVALID) continue;
deba@870
  1776
        int num = 1;
deba@870
  1777
        Node v = _graph.target(_fractional->matching(n));
deba@870
  1778
        while (n != v) {
deba@870
  1779
          processed[v] = true;
deba@870
  1780
          v = _graph.target(_fractional->matching(v));
deba@870
  1781
          ++num;
deba@870
  1782
        }
deba@870
  1783
deba@870
  1784
        if (num % 2 == 1) {
deba@870
  1785
          std::vector<int> subblossoms(num);
deba@870
  1786
deba@870
  1787
          subblossoms[--num] = _blossom_set->find(n);
deba@870
  1788
          _delta1->push(n, _fractional->nodeValue(n));
deba@870
  1789
          v = _graph.target(_fractional->matching(n));
deba@870
  1790
          while (n != v) {
deba@870
  1791
            subblossoms[--num] = _blossom_set->find(v);
deba@870
  1792
            _delta1->push(v, _fractional->nodeValue(v));
alpar@877
  1793
            v = _graph.target(_fractional->matching(v));
deba@870
  1794
          }
alpar@877
  1795
alpar@877
  1796
          int surface =
deba@870
  1797
            _blossom_set->join(subblossoms.begin(), subblossoms.end());
deba@870
  1798
          (*_blossom_data)[surface].status = EVEN;
deba@870
  1799
          (*_blossom_data)[surface].pred = INVALID;
deba@870
  1800
          (*_blossom_data)[surface].next = INVALID;
deba@870
  1801
          (*_blossom_data)[surface].pot = 0;
deba@870
  1802
          (*_blossom_data)[surface].offset = 0;
alpar@877
  1803
deba@870
  1804
          _tree_set->insert(surface);
deba@870
  1805
          ++_unmatched;
deba@870
  1806
        }
deba@870
  1807
      }
deba@870
  1808
deba@870
  1809
      for (EdgeIt e(_graph); e != INVALID; ++e) {
deba@870
  1810
        int si = (*_node_index)[_graph.u(e)];
deba@870
  1811
        int sb = _blossom_set->find(_graph.u(e));
deba@870
  1812
        int ti = (*_node_index)[_graph.v(e)];
deba@870
  1813
        int tb = _blossom_set->find(_graph.v(e));
deba@870
  1814
        if ((*_blossom_data)[sb].status == EVEN &&
deba@870
  1815
            (*_blossom_data)[tb].status == EVEN && sb != tb) {
deba@870
  1816
          _delta3->push(e, ((*_node_data)[si].pot + (*_node_data)[ti].pot -
deba@870
  1817
                            dualScale * _weight[e]) / 2);
deba@870
  1818
        }
deba@870
  1819
      }
deba@870
  1820
deba@870
  1821
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@870
  1822
        int nb = _blossom_set->find(n);
deba@870
  1823
        if ((*_blossom_data)[nb].status != MATCHED) continue;
deba@870
  1824
        int ni = (*_node_index)[n];
deba@870
  1825
deba@870
  1826
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
deba@870
  1827
          Node v = _graph.target(e);
deba@870
  1828
          int vb = _blossom_set->find(v);
deba@870
  1829
          int vi = (*_node_index)[v];
deba@870
  1830
deba@870
  1831
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
deba@870
  1832
            dualScale * _weight[e];
deba@870
  1833
deba@870
  1834
          if ((*_blossom_data)[vb].status == EVEN) {
deba@870
  1835
deba@870
  1836
            int vt = _tree_set->find(vb);
deba@870
  1837
deba@870
  1838
            typename std::map<int, Arc>::iterator it =
deba@870
  1839
              (*_node_data)[ni].heap_index.find(vt);
deba@870
  1840
deba@870
  1841
            if (it != (*_node_data)[ni].heap_index.end()) {
deba@870
  1842
              if ((*_node_data)[ni].heap[it->second] > rw) {
deba@870
  1843
                (*_node_data)[ni].heap.replace(it->second, e);
deba@870
  1844
                (*_node_data)[ni].heap.decrease(e, rw);
deba@870
  1845
                it->second = e;
deba@870
  1846
              }
deba@870
  1847
            } else {
deba@870
  1848
              (*_node_data)[ni].heap.push(e, rw);
deba@870
  1849
              (*_node_data)[ni].heap_index.insert(std::make_pair(vt, e));
deba@870
  1850
            }
deba@870
  1851
          }
deba@870
  1852
        }
alpar@877
  1853
deba@870
  1854
        if (!(*_node_data)[ni].heap.empty()) {
deba@870
  1855
          _blossom_set->decrease(n, (*_node_data)[ni].heap.prio());
deba@870
  1856
          _delta2->push(nb, _blossom_set->classPrio(nb));
deba@870
  1857
        }
deba@870
  1858
      }
deba@870
  1859
    }
deba@870
  1860
kpeter@590
  1861
    /// \brief Start the algorithm
deba@326
  1862
    ///
kpeter@590
  1863
    /// This function starts the algorithm.
kpeter@590
  1864
    ///
deba@870
  1865
    /// \pre \ref init() or \ref fractionalInit() must be called
deba@870
  1866
    /// before using this function.
deba@326
  1867
    void start() {
deba@326
  1868
      enum OpType {
deba@326
  1869
        D1, D2, D3, D4
deba@326
  1870
      };
deba@326
  1871
deba@870
  1872
      while (_unmatched > 0) {
deba@326
  1873
        Value d1 = !_delta1->empty() ?
deba@326
  1874
          _delta1->prio() : std::numeric_limits<Value>::max();
deba@326
  1875
deba@326
  1876
        Value d2 = !_delta2->empty() ?
deba@326
  1877
          _delta2->prio() : std::numeric_limits<Value>::max();
deba@326
  1878
deba@326
  1879
        Value d3 = !_delta3->empty() ?
deba@326
  1880
          _delta3->prio() : std::numeric_limits<Value>::max();
deba@326
  1881
deba@326
  1882
        Value d4 = !_delta4->empty() ?
deba@326
  1883
          _delta4->prio() : std::numeric_limits<Value>::max();
deba@326
  1884
deba@868
  1885
        _delta_sum = d3; OpType ot = D3;
deba@868
  1886
        if (d1 < _delta_sum) { _delta_sum = d1; ot = D1; }
deba@326
  1887
        if (d2 < _delta_sum) { _delta_sum = d2; ot = D2; }
deba@326
  1888
        if (d4 < _delta_sum) { _delta_sum = d4; ot = D4; }
deba@326
  1889
deba@326
  1890
        switch (ot) {
deba@326
  1891
        case D1:
deba@326
  1892
          {
deba@326
  1893
            Node n = _delta1->top();
deba@326
  1894
            unmatchNode(n);
deba@870
  1895
            --_unmatched;
deba@326
  1896
          }
deba@326
  1897
          break;
deba@326
  1898
        case D2:
deba@326
  1899
          {
deba@326
  1900
            int blossom = _delta2->top();
deba@326
  1901
            Node n = _blossom_set->classTop(blossom);
deba@868
  1902
            Arc a = (*_node_data)[(*_node_index)[n]].heap.top();
deba@868
  1903
            if ((*_blossom_data)[blossom].next == INVALID) {
deba@868
  1904
              augmentOnArc(a);
deba@870
  1905
              --_unmatched;
deba@868
  1906
            } else {
deba@868
  1907
              extendOnArc(a);
deba@868
  1908
            }
deba@326
  1909
          }
deba@326
  1910
          break;
deba@326
  1911
        case D3:
deba@326
  1912
          {
deba@326
  1913
            Edge e = _delta3->top();
deba@326
  1914
deba@326
  1915
            int left_blossom = _blossom_set->find(_graph.u(e));
deba@326
  1916
            int right_blossom = _blossom_set->find(_graph.v(e));
deba@326
  1917
deba@326
  1918
            if (left_blossom == right_blossom) {
deba@326
  1919
              _delta3->pop();
deba@326
  1920
            } else {
deba@868
  1921
              int left_tree = _tree_set->find(left_blossom);
deba@868
  1922
              int right_tree = _tree_set->find(right_blossom);
deba@326
  1923
deba@326
  1924
              if (left_tree == right_tree) {
deba@327
  1925
                shrinkOnEdge(e, left_tree);
deba@326
  1926
              } else {
deba@327
  1927
                augmentOnEdge(e);
deba@870
  1928
                _unmatched -= 2;
deba@326
  1929
              }
deba@326
  1930
            }
deba@326
  1931
          } break;
deba@326
  1932
        case D4:
deba@326
  1933
          splitBlossom(_delta4->top());
deba@326
  1934
          break;
deba@326
  1935
        }
deba@326
  1936
      }
deba@326
  1937
      extractMatching();
deba@326
  1938
    }
deba@326
  1939
kpeter@590
  1940
    /// \brief Run the algorithm.
deba@326
  1941
    ///
kpeter@590
  1942
    /// This method runs the \c %MaxWeightedMatching algorithm.
deba@326
  1943
    ///
deba@326
  1944
    /// \note mwm.run() is just a shortcut of the following code.
deba@326
  1945
    /// \code
deba@870
  1946
    ///   mwm.fractionalInit();
deba@326
  1947
    ///   mwm.start();
deba@326
  1948
    /// \endcode
deba@326
  1949
    void run() {
deba@870
  1950
      fractionalInit();
deba@326
  1951
      start();
deba@326
  1952
    }
deba@326
  1953
deba@326
  1954
    /// @}
deba@326
  1955
kpeter@590
  1956
    /// \name Primal Solution
deba@868
  1957
    /// Functions to get the primal solution, i.e. the maximum weighted
kpeter@590
  1958
    /// matching.\n
kpeter@590
  1959
    /// Either \ref run() or \ref start() function should be called before
kpeter@590
  1960
    /// using them.
deba@326
  1961
deba@326
  1962
    /// @{
deba@326
  1963
kpeter@590
  1964
    /// \brief Return the weight of the matching.
deba@326
  1965
    ///
kpeter@590
  1966
    /// This function returns the weight of the found matching.
kpeter@590
  1967
    ///
kpeter@590
  1968
    /// \pre Either run() or start() must be called before using this function.
kpeter@593
  1969
    Value matchingWeight() const {
deba@326
  1970
      Value sum = 0;
deba@326
  1971
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@326
  1972
        if ((*_matching)[n] != INVALID) {
deba@326
  1973
          sum += _weight[(*_matching)[n]];
deba@326
  1974
        }
deba@326
  1975
      }
deba@868
  1976
      return sum / 2;
deba@326
  1977
    }
deba@326
  1978
kpeter@590
  1979
    /// \brief Return the size (cardinality) of the matching.
deba@326
  1980
    ///
kpeter@590
  1981
    /// This function returns the size (cardinality) of the found matching.
kpeter@590
  1982
    ///
kpeter@590
  1983
    /// \pre Either run() or start() must be called before using this function.
deba@327
  1984
    int matchingSize() const {
deba@327
  1985
      int num = 0;
deba@327
  1986
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@327
  1987
        if ((*_matching)[n] != INVALID) {
deba@327
  1988
          ++num;
deba@327
  1989
        }
deba@327
  1990
      }
deba@327
  1991
      return num /= 2;
deba@327
  1992
    }
deba@327
  1993
kpeter@590
  1994
    /// \brief Return \c true if the given edge is in the matching.
deba@327
  1995
    ///
deba@868
  1996
    /// This function returns \c true if the given edge is in the found
kpeter@590
  1997
    /// matching.
kpeter@590
  1998
    ///
kpeter@590
  1999
    /// \pre Either run() or start() must be called before using this function.
deba@327
  2000
    bool matching(const Edge& edge) const {
deba@327
  2001
      return edge == (*_matching)[_graph.u(edge)];
deba@326
  2002
    }
deba@326
  2003
kpeter@590
  2004
    /// \brief Return the matching arc (or edge) incident to the given node.
deba@326
  2005
    ///
kpeter@590
  2006
    /// This function returns the matching arc (or edge) incident to the
deba@868
  2007
    /// given node in the found matching or \c INVALID if the node is
kpeter@590
  2008
    /// not covered by the matching.
kpeter@590
  2009
    ///
kpeter@590
  2010
    /// \pre Either run() or start() must be called before using this function.
deba@326
  2011
    Arc matching(const Node& node) const {
deba@326
  2012
      return (*_matching)[node];
deba@326
  2013
    }
deba@326
  2014
kpeter@593
  2015
    /// \brief Return a const reference to the matching map.
kpeter@593
  2016
    ///
kpeter@593
  2017
    /// This function returns a const reference to a node map that stores
kpeter@593
  2018
    /// the matching arc (or edge) incident to each node.
kpeter@593
  2019
    const MatchingMap& matchingMap() const {
kpeter@593
  2020
      return *_matching;
kpeter@593
  2021
    }
kpeter@593
  2022
kpeter@590
  2023
    /// \brief Return the mate of the given node.
deba@326
  2024
    ///
deba@868
  2025
    /// This function returns the mate of the given node in the found
kpeter@590
  2026
    /// matching or \c INVALID if the node is not covered by the matching.
kpeter@590
  2027
    ///
kpeter@590
  2028
    /// \pre Either run() or start() must be called before using this function.
deba@326
  2029
    Node mate(const Node& node) const {
deba@326
  2030
      return (*_matching)[node] != INVALID ?
deba@326
  2031
        _graph.target((*_matching)[node]) : INVALID;
deba@326
  2032
    }
deba@326
  2033
deba@326
  2034
    /// @}
deba@326
  2035
kpeter@590
  2036
    /// \name Dual Solution
kpeter@590
  2037
    /// Functions to get the dual solution.\n
kpeter@590
  2038
    /// Either \ref run() or \ref start() function should be called before
kpeter@590
  2039
    /// using them.
deba@326
  2040
deba@326
  2041
    /// @{
deba@326
  2042
kpeter@590
  2043
    /// \brief Return the value of the dual solution.
deba@326
  2044
    ///
deba@868
  2045
    /// This function returns the value of the dual solution.
deba@868
  2046
    /// It should be equal to the primal value scaled by \ref dualScale
kpeter@590
  2047
    /// "dual scale".
kpeter@590
  2048
    ///
kpeter@590
  2049
    /// \pre Either run() or start() must be called before using this function.
deba@326
  2050
    Value dualValue() const {
deba@326
  2051
      Value sum = 0;
deba@326
  2052
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@326
  2053
        sum += nodeValue(n);
deba@326
  2054
      }
deba@326
  2055
      for (int i = 0; i < blossomNum(); ++i) {
deba@326
  2056
        sum += blossomValue(i) * (blossomSize(i) / 2);
deba@326
  2057
      }
deba@326
  2058
      return sum;
deba@326
  2059
    }
deba@326
  2060
kpeter@590
  2061
    /// \brief Return the dual value (potential) of the given node.
deba@326
  2062
    ///
kpeter@590
  2063
    /// This function returns the dual value (potential) of the given node.
kpeter@590
  2064
    ///
kpeter@590
  2065
    /// \pre Either run() or start() must be called before using this function.
deba@326
  2066
    Value nodeValue(const Node& n) const {
deba@326
  2067
      return (*_node_potential)[n];
deba@326
  2068
    }
deba@326
  2069
kpeter@590
  2070
    /// \brief Return the number of the blossoms in the basis.
deba@326
  2071
    ///
kpeter@590
  2072
    /// This function returns the number of the blossoms in the basis.
kpeter@590
  2073
    ///
kpeter@590
  2074
    /// \pre Either run() or start() must be called before using this function.
deba@326
  2075
    /// \see BlossomIt
deba@326
  2076
    int blossomNum() const {
deba@326
  2077
      return _blossom_potential.size();
deba@326
  2078
    }
deba@326
  2079
kpeter@590
  2080
    /// \brief Return the number of the nodes in the given blossom.
deba@326
  2081
    ///
kpeter@590
  2082
    /// This function returns the number of the nodes in the given blossom.
kpeter@590
  2083
    ///
kpeter@590
  2084
    /// \pre Either run() or start() must be called before using this function.
kpeter@590
  2085
    /// \see BlossomIt
deba@326
  2086
    int blossomSize(int k) const {
deba@326
  2087
      return _blossom_potential[k].end - _blossom_potential[k].begin;
deba@326
  2088
    }
deba@326
  2089
kpeter@590
  2090
    /// \brief Return the dual value (ptential) of the given blossom.
deba@326
  2091
    ///
kpeter@590
  2092
    /// This function returns the dual value (ptential) of the given blossom.
kpeter@590
  2093
    ///
kpeter@590
  2094
    /// \pre Either run() or start() must be called before using this function.
deba@326
  2095
    Value blossomValue(int k) const {
deba@326
  2096
      return _blossom_potential[k].value;
deba@326
  2097
    }
deba@326
  2098
kpeter@590
  2099
    /// \brief Iterator for obtaining the nodes of a blossom.
deba@326
  2100
    ///
deba@868
  2101
    /// This class provides an iterator for obtaining the nodes of the
kpeter@590
  2102
    /// given blossom. It lists a subset of the nodes.
deba@868
  2103
    /// Before using this iterator, you must allocate a
kpeter@590
  2104
    /// MaxWeightedMatching class and execute it.
deba@326
  2105
    class BlossomIt {
deba@326
  2106
    public:
deba@326
  2107
deba@326
  2108
      /// \brief Constructor.
deba@326
  2109
      ///
kpeter@590
  2110
      /// Constructor to get the nodes of the given variable.
kpeter@590
  2111
      ///
deba@868
  2112
      /// \pre Either \ref MaxWeightedMatching::run() "algorithm.run()" or
deba@868
  2113
      /// \ref MaxWeightedMatching::start() "algorithm.start()" must be
kpeter@590
  2114
      /// called before initializing this iterator.
deba@326
  2115
      BlossomIt(const MaxWeightedMatching& algorithm, int variable)
deba@326
  2116
        : _algorithm(&algorithm)
deba@326
  2117
      {
deba@326
  2118
        _index = _algorithm->_blossom_potential[variable].begin;
deba@326
  2119
        _last = _algorithm->_blossom_potential[variable].end;
deba@326
  2120
      }
deba@326
  2121
kpeter@590
  2122
      /// \brief Conversion to \c Node.
deba@326
  2123
      ///
kpeter@590
  2124
      /// Conversion to \c Node.
deba@326
  2125
      operator Node() const {
deba@327
  2126
        return _algorithm->_blossom_node_list[_index];
deba@326
  2127
      }
deba@326
  2128
deba@326
  2129
      /// \brief Increment operator.
deba@326
  2130
      ///
deba@326
  2131
      /// Increment operator.
deba@326
  2132
      BlossomIt& operator++() {
deba@326
  2133
        ++_index;
deba@326
  2134
        return *this;
deba@326
  2135
      }
deba@326
  2136
deba@327
  2137
      /// \brief Validity checking
deba@327
  2138
      ///
deba@327
  2139
      /// Checks whether the iterator is invalid.
deba@327
  2140
      bool operator==(Invalid) const { return _index == _last; }
deba@327
  2141
deba@327
  2142
      /// \brief Validity checking
deba@327
  2143
      ///
deba@327
  2144
      /// Checks whether the iterator is valid.
deba@327
  2145
      bool operator!=(Invalid) const { return _index != _last; }
deba@326
  2146
deba@326
  2147
    private:
deba@326
  2148
      const MaxWeightedMatching* _algorithm;
deba@326
  2149
      int _last;
deba@326
  2150
      int _index;
deba@326
  2151
    };
deba@326
  2152
deba@326
  2153
    /// @}
deba@326
  2154
deba@326
  2155
  };
deba@326
  2156
deba@326
  2157
  /// \ingroup matching
deba@326
  2158
  ///
deba@326
  2159
  /// \brief Weighted perfect matching in general graphs
deba@326
  2160
  ///
deba@326
  2161
  /// This class provides an efficient implementation of Edmond's
deba@327
  2162
  /// maximum weighted perfect matching algorithm. The implementation
deba@326
  2163
  /// is based on extensive use of priority queues and provides
kpeter@559
  2164
  /// \f$O(nm\log n)\f$ time complexity.
deba@326
  2165
  ///
deba@868
  2166
  /// The maximum weighted perfect matching problem is to find a subset of
deba@868
  2167
  /// the edges in an undirected graph with maximum overall weight for which
kpeter@590
  2168
  /// each node has exactly one incident edge.
kpeter@590
  2169
  /// It can be formulated with the following linear program.
deba@326
  2170
  /// \f[ \sum_{e \in \delta(u)}x_e = 1 \quad \forall u\in V\f]
deba@327
  2171
  /** \f[ \sum_{e \in \gamma(B)}x_e \le \frac{\vert B \vert - 1}{2}
deba@327
  2172
      \quad \forall B\in\mathcal{O}\f] */
deba@326
  2173
  /// \f[x_e \ge 0\quad \forall e\in E\f]
deba@326
  2174
  /// \f[\max \sum_{e\in E}x_ew_e\f]
deba@327
  2175
  /// where \f$\delta(X)\f$ is the set of edges incident to a node in
deba@327
  2176
  /// \f$X\f$, \f$\gamma(X)\f$ is the set of edges with both ends in
deba@327
  2177
  /// \f$X\f$ and \f$\mathcal{O}\f$ is the set of odd cardinality
deba@327
  2178
  /// subsets of the nodes.
deba@326
  2179
  ///
deba@326
  2180
  /// The algorithm calculates an optimal matching and a proof of the
deba@326
  2181
  /// optimality. The solution of the dual problem can be used to check
deba@327
  2182
  /// the result of the algorithm. The dual linear problem is the
kpeter@590
  2183
  /// following.
deba@327
  2184
  /** \f[ y_u + y_v + \sum_{B \in \mathcal{O}, uv \in \gamma(B)}z_B \ge
deba@327
  2185
      w_{uv} \quad \forall uv\in E\f] */
deba@326
  2186
  /// \f[z_B \ge 0 \quad \forall B \in \mathcal{O}\f]
deba@327
  2187
  /** \f[\min \sum_{u \in V}y_u + \sum_{B \in \mathcal{O}}
deba@327
  2188
      \frac{\vert B \vert - 1}{2}z_B\f] */
deba@326
  2189
  ///
deba@868
  2190
  /// The algorithm can be executed with the run() function.
kpeter@590
  2191
  /// After it the matching (the primal solution) and the dual solution
deba@868
  2192
  /// can be obtained using the query functions and the
deba@868
  2193
  /// \ref MaxWeightedPerfectMatching::BlossomIt "BlossomIt" nested class,
deba@868
  2194
  /// which is able to iterate on the nodes of a blossom.
kpeter@590
  2195
  /// If the value type is integer, then the dual solution is multiplied
kpeter@590
  2196
  /// by \ref MaxWeightedMatching::dualScale "4".
kpeter@590
  2197
  ///
kpeter@593
  2198
  /// \tparam GR The undirected graph type the algorithm runs on.
deba@868
  2199
  /// \tparam WM The type edge weight map. The default type is
kpeter@590
  2200
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<int>".
kpeter@590
  2201
#ifdef DOXYGEN
kpeter@590
  2202
  template <typename GR, typename WM>
kpeter@590
  2203
#else
kpeter@559
  2204
  template <typename GR,
kpeter@559
  2205
            typename WM = typename GR::template EdgeMap<int> >
kpeter@590
  2206
#endif
deba@326
  2207
  class MaxWeightedPerfectMatching {
deba@326
  2208
  public:
deba@326
  2209
kpeter@590
  2210
    /// The graph type of the algorithm
kpeter@559
  2211
    typedef GR Graph;
kpeter@590
  2212
    /// The type of the edge weight map
kpeter@559
  2213
    typedef WM WeightMap;
kpeter@590
  2214
    /// The value type of the edge weights
deba@326
  2215
    typedef typename WeightMap::Value Value;
deba@326
  2216
deba@326
  2217
    /// \brief Scaling factor for dual solution
deba@326
  2218
    ///
deba@326
  2219
    /// Scaling factor for dual solution, it is equal to 4 or 1
deba@326
  2220
    /// according to the value type.
deba@326
  2221
    static const int dualScale =
deba@326
  2222
      std::numeric_limits<Value>::is_integer ? 4 : 1;
deba@326
  2223
kpeter@593
  2224
    /// The type of the matching map
deba@326
  2225
    typedef typename Graph::template NodeMap<typename Graph::Arc>
deba@326
  2226
    MatchingMap;
deba@326
  2227
deba@326
  2228
  private:
deba@326
  2229
deba@326
  2230
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
deba@326
  2231
deba@326
  2232
    typedef typename Graph::template NodeMap<Value> NodePotential;
deba@326
  2233
    typedef std::vector<Node> BlossomNodeList;
deba@326
  2234
deba@326
  2235
    struct BlossomVariable {
deba@326
  2236
      int begin, end;
deba@326
  2237
      Value value;
deba@326
  2238
deba@1208
  2239
      BlossomVariable(int _begin, Value _value)
deba@1208
  2240
        : begin(_begin), value(_value) {}
deba@326
  2241
deba@326
  2242
    };
deba@326
  2243
deba@326
  2244
    typedef std::vector<BlossomVariable> BlossomPotential;
deba@326
  2245
deba@326
  2246
    const Graph& _graph;
deba@326
  2247
    const WeightMap& _weight;
deba@326
  2248
deba@326
  2249
    MatchingMap* _matching;
deba@326
  2250
deba@326
  2251
    NodePotential* _node_potential;
deba@326
  2252
deba@326
  2253
    BlossomPotential _blossom_potential;
deba@326
  2254
    BlossomNodeList _blossom_node_list;
deba@326
  2255
deba@326
  2256
    int _node_num;
deba@326
  2257
    int _blossom_num;
deba@326
  2258
deba@326
  2259
    typedef RangeMap<int> IntIntMap;
deba@326
  2260
deba@326
  2261
    enum Status {
deba@326
  2262
      EVEN = -1, MATCHED = 0, ODD = 1
deba@326
  2263
    };
deba@326
  2264
deba@327
  2265
    typedef HeapUnionFind<Value, IntNodeMap> BlossomSet;
deba@326
  2266
    struct BlossomData {
deba@326
  2267
      int tree;
deba@326
  2268
      Status status;
deba@326
  2269
      Arc pred, next;
deba@326
  2270
      Value pot, offset;
deba@326
  2271
    };
deba@326
  2272
deba@327
  2273
    IntNodeMap *_blossom_index;
deba@326
  2274
    BlossomSet *_blossom_set;
deba@326
  2275
    RangeMap<BlossomData>* _blossom_data;
deba@326
  2276
deba@327
  2277
    IntNodeMap *_node_index;
deba@327
  2278
    IntArcMap *_node_heap_index;
deba@326
  2279
deba@326
  2280
    struct NodeData {
deba@326
  2281
deba@327
  2282
      NodeData(IntArcMap& node_heap_index)
deba@326
  2283
        : heap(node_heap_index) {}
deba@326
  2284
deba@326
  2285
      int blossom;
deba@326
  2286
      Value pot;
deba@327
  2287
      BinHeap<Value, IntArcMap> heap;
deba@326
  2288
      std::map<int, Arc> heap_index;
deba@326
  2289
deba@326
  2290
      int tree;
deba@326
  2291
    };
deba@326
  2292
deba@326
  2293
    RangeMap<NodeData>* _node_data;
deba@326
  2294
deba@326
  2295
    typedef ExtendFindEnum<IntIntMap> TreeSet;
deba@326
  2296
deba@326
  2297
    IntIntMap *_tree_set_index;
deba@326
  2298
    TreeSet *_tree_set;
deba@326
  2299
deba@326
  2300
    IntIntMap *_delta2_index;
deba@326
  2301
    BinHeap<Value, IntIntMap> *_delta2;
deba@326
  2302
deba@327
  2303
    IntEdgeMap *_delta3_index;
deba@327
  2304
    BinHeap<Value, IntEdgeMap> *_delta3;
deba@326
  2305
deba@326
  2306
    IntIntMap *_delta4_index;
deba@326
  2307
    BinHeap<Value, IntIntMap> *_delta4;
deba@326
  2308
deba@326
  2309
    Value _delta_sum;
deba@870
  2310
    int _unmatched;
deba@870
  2311
alpar@877
  2312
    typedef MaxWeightedPerfectFractionalMatching<Graph, WeightMap>
deba@870
  2313
    FractionalMatching;
deba@870
  2314
    FractionalMatching *_fractional;
deba@326
  2315
deba@326
  2316
    void createStructures() {
deba@326
  2317
      _node_num = countNodes(_graph);
deba@326
  2318
      _blossom_num = _node_num * 3 / 2;
deba@326
  2319
deba@326
  2320
      if (!_matching) {
deba@326
  2321
        _matching = new MatchingMap(_graph);
deba@326
  2322
      }
deba@867
  2323
deba@326
  2324
      if (!_node_potential) {
deba@326
  2325
        _node_potential = new NodePotential(_graph);
deba@326
  2326
      }
deba@867
  2327
deba@326
  2328
      if (!_blossom_set) {
deba@327
  2329
        _blossom_index = new IntNodeMap(_graph);
deba@326
  2330
        _blossom_set = new BlossomSet(*_blossom_index);
deba@326
  2331
        _blossom_data = new RangeMap<BlossomData>(_blossom_num);
deba@867
  2332
      } else if (_blossom_data->size() != _blossom_num) {
deba@867
  2333
        delete _blossom_data;
deba@867
  2334
        _blossom_data = new RangeMap<BlossomData>(_blossom_num);
deba@326
  2335
      }
deba@326
  2336
deba@326
  2337
      if (!_node_index) {
deba@327
  2338
        _node_index = new IntNodeMap(_graph);
deba@327
  2339
        _node_heap_index = new IntArcMap(_graph);
deba@326
  2340
        _node_data = new RangeMap<NodeData>(_node_num,
deba@327
  2341
                                            NodeData(*_node_heap_index));
deba@867
  2342
      } else if (_node_data->size() != _node_num) {
deba@867
  2343
        delete _node_data;
deba@867
  2344
        _node_data = new RangeMap<NodeData>(_node_num,
deba@867
  2345
                                            NodeData(*_node_heap_index));
deba@326
  2346
      }
deba@326
  2347
deba@326
  2348
      if (!_tree_set) {
deba@326
  2349
        _tree_set_index = new IntIntMap(_blossom_num);
deba@326
  2350
        _tree_set = new TreeSet(*_tree_set_index);
deba@867
  2351
      } else {
deba@867
  2352
        _tree_set_index->resize(_blossom_num);
deba@326
  2353
      }
deba@867
  2354
deba@326
  2355
      if (!_delta2) {
deba@326
  2356
        _delta2_index = new IntIntMap(_blossom_num);
deba@326
  2357
        _delta2 = new BinHeap<Value, IntIntMap>(*_delta2_index);
deba@867
  2358
      } else {
deba@867
  2359
        _delta2_index->resize(_blossom_num);
deba@326
  2360
      }
deba@867
  2361
deba@326
  2362
      if (!_delta3) {
deba@327
  2363
        _delta3_index = new IntEdgeMap(_graph);
deba@327
  2364
        _delta3 = new BinHeap<Value, IntEdgeMap>(*_delta3_index);
deba@326
  2365
      }
deba@867
  2366
deba@326
  2367
      if (!_delta4) {
deba@326
  2368
        _delta4_index = new IntIntMap(_blossom_num);
deba@326
  2369
        _delta4 = new BinHeap<Value, IntIntMap>(*_delta4_index);
deba@867
  2370
      } else {
deba@867
  2371
        _delta4_index->resize(_blossom_num);
deba@326
  2372
      }
deba@326
  2373
    }
deba@326
  2374
deba@326
  2375
    void destroyStructures() {
deba@326
  2376
      if (_matching) {
deba@326
  2377
        delete _matching;
deba@326
  2378
      }
deba@326
  2379
      if (_node_potential) {
deba@326
  2380
        delete _node_potential;
deba@326
  2381
      }
deba@326
  2382
      if (_blossom_set) {
deba@326
  2383
        delete _blossom_index;
deba@326
  2384
        delete _blossom_set;
deba@326
  2385
        delete _blossom_data;
deba@326
  2386
      }
deba@326
  2387
deba@326
  2388
      if (_node_index) {
deba@326
  2389
        delete _node_index;
deba@326
  2390
        delete _node_heap_index;
deba@326
  2391
        delete _node_data;
deba@326
  2392
      }
deba@326
  2393
deba@326
  2394
      if (_tree_set) {
deba@326
  2395
        delete _tree_set_index;
deba@326
  2396
        delete _tree_set;
deba@326
  2397
      }
deba@326
  2398
      if (_delta2) {
deba@326
  2399
        delete _delta2_index;
deba@326
  2400
        delete _delta2;
deba@326
  2401
      }
deba@326
  2402
      if (_delta3) {
deba@326
  2403
        delete _delta3_index;
deba@326
  2404
        delete _delta3;
deba@326
  2405
      }
deba@326
  2406
      if (_delta4) {
deba@326
  2407
        delete _delta4_index;
deba@326
  2408
        delete _delta4;
deba@326
  2409
      }
deba@326
  2410
    }
deba@326
  2411
deba@326
  2412
    void matchedToEven(int blossom, int tree) {
deba@326
  2413
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
deba@326
  2414
        _delta2->erase(blossom);
deba@326
  2415
      }
deba@326
  2416
deba@326
  2417
      if (!_blossom_set->trivial(blossom)) {
deba@326
  2418
        (*_blossom_data)[blossom].pot -=
deba@326
  2419
          2 * (_delta_sum - (*_blossom_data)[blossom].offset);
deba@326
  2420
      }
deba@326
  2421
deba@326
  2422
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
deba@326
  2423
           n != INVALID; ++n) {
deba@326
  2424
deba@326
  2425
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
deba@326
  2426
        int ni = (*_node_index)[n];
deba@326
  2427
deba@326
  2428
        (*_node_data)[ni].heap.clear();
deba@326
  2429
        (*_node_data)[ni].heap_index.clear();
deba@326
  2430
deba@326
  2431
        (*_node_data)[ni].pot += _delta_sum - (*_blossom_data)[blossom].offset;
deba@326
  2432
deba@326
  2433
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
deba@326
  2434
          Node v = _graph.source(e);
deba@326
  2435
          int vb = _blossom_set->find(v);
deba@326
  2436
          int vi = (*_node_index)[v];
deba@326
  2437
deba@326
  2438
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
deba@326
  2439
            dualScale * _weight[e];
deba@326
  2440
deba@326
  2441
          if ((*_blossom_data)[vb].status == EVEN) {
deba@326
  2442
            if (_delta3->state(e) != _delta3->IN_HEAP && blossom != vb) {
deba@326
  2443
              _delta3->push(e, rw / 2);
deba@326
  2444
            }
deba@326
  2445
          } else {
deba@326
  2446
            typename std::map<int, Arc>::iterator it =
deba@326
  2447
              (*_node_data)[vi].heap_index.find(tree);
deba@326
  2448
deba@326
  2449
            if (it != (*_node_data)[vi].heap_index.end()) {
deba@326
  2450
              if ((*_node_data)[vi].heap[it->second] > rw) {
deba@326
  2451
                (*_node_data)[vi].heap.replace(it->second, e);
deba@326
  2452
                (*_node_data)[vi].heap.decrease(e, rw);
deba@326
  2453
                it->second = e;
deba@326
  2454
              }
deba@326
  2455
            } else {
deba@326
  2456
              (*_node_data)[vi].heap.push(e, rw);
deba@326
  2457
              (*_node_data)[vi].heap_index.insert(std::make_pair(tree, e));
deba@326
  2458
            }
deba@326
  2459
deba@326
  2460
            if ((*_blossom_set)[v] > (*_node_data)[vi].heap.prio()) {
deba@326
  2461
              _blossom_set->decrease(v, (*_node_data)[vi].heap.prio());
deba@326
  2462
deba@326
  2463
              if ((*_blossom_data)[vb].status == MATCHED) {
deba@326
  2464
                if (_delta2->state(vb) != _delta2->IN_HEAP) {
deba@326
  2465
                  _delta2->push(vb, _blossom_set->classPrio(vb) -
deba@326
  2466
                               (*_blossom_data)[vb].offset);
deba@326
  2467
                } else if ((*_delta2)[vb] > _blossom_set->classPrio(vb) -
deba@326
  2468
                           (*_blossom_data)[vb].offset){
deba@326
  2469
                  _delta2->decrease(vb, _blossom_set->classPrio(vb) -
deba@326
  2470
                                   (*_blossom_data)[vb].offset);
deba@326
  2471
                }
deba@326
  2472
              }
deba@326
  2473
            }
deba@326
  2474
          }
deba@326
  2475
        }
deba@326
  2476
      }
deba@326
  2477
      (*_blossom_data)[blossom].offset = 0;
deba@326
  2478
    }
deba@326
  2479
deba@326
  2480
    void matchedToOdd(int blossom) {
deba@326
  2481
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
deba@326
  2482
        _delta2->erase(blossom);
deba@326
  2483
      }
deba@326
  2484
      (*_blossom_data)[blossom].offset += _delta_sum;
deba@326
  2485
      if (!_blossom_set->trivial(blossom)) {
deba@326
  2486
        _delta4->push(blossom, (*_blossom_data)[blossom].pot / 2 +
deba@326
  2487
                     (*_blossom_data)[blossom].offset);
deba@326
  2488
      }
deba@326
  2489
    }
deba@326
  2490
deba@326
  2491
    void evenToMatched(int blossom, int tree) {
deba@326
  2492
      if (!_blossom_set->trivial(blossom)) {
deba@326
  2493
        (*_blossom_data)[blossom].pot += 2 * _delta_sum;
deba@326
  2494
      }
deba@326
  2495
deba@326
  2496
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
deba@326
  2497
           n != INVALID; ++n) {
deba@326
  2498
        int ni = (*_node_index)[n];
deba@326
  2499
        (*_node_data)[ni].pot -= _delta_sum;
deba@326
  2500
deba@326
  2501
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
deba@326
  2502
          Node v = _graph.source(e);
deba@326
  2503
          int vb = _blossom_set->find(v);
deba@326
  2504
          int vi = (*_node_index)[v];
deba@326
  2505
deba@326
  2506
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
deba@326
  2507
            dualScale * _weight[e];
deba@326
  2508
deba@326
  2509
          if (vb == blossom) {
deba@326
  2510
            if (_delta3->state(e) == _delta3->IN_HEAP) {
deba@326
  2511
              _delta3->erase(e);
deba@326
  2512
            }
deba@326
  2513
          } else if ((*_blossom_data)[vb].status == EVEN) {
deba@326
  2514
deba@326
  2515
            if (_delta3->state(e) == _delta3->IN_HEAP) {
deba@326
  2516
              _delta3->erase(e);
deba@326
  2517
            }
deba@326
  2518
deba@326
  2519
            int vt = _tree_set->find(vb);
deba@326
  2520
deba@326
  2521
            if (vt != tree) {
deba@326
  2522
deba@326
  2523
              Arc r = _graph.oppositeArc(e);
deba@326
  2524
deba@326
  2525
              typename std::map<int, Arc>::iterator it =
deba@326
  2526
                (*_node_data)[ni].heap_index.find(vt);
deba@326
  2527
deba@326
  2528
              if (it != (*_node_data)[ni].heap_index.end()) {
deba@326
  2529
                if ((*_node_data)[ni].heap[it->second] > rw) {
deba@326
  2530
                  (*_node_data)[ni].heap.replace(it->second, r);
deba@326
  2531
                  (*_node_data)[ni].heap.decrease(r, rw);
deba@326
  2532
                  it->second = r;
deba@326
  2533
                }
deba@326
  2534
              } else {
deba@326
  2535
                (*_node_data)[ni].heap.push(r, rw);
deba@326
  2536
                (*_node_data)[ni].heap_index.insert(std::make_pair(vt, r));
deba@326
  2537
              }
deba@326
  2538
deba@326
  2539
              if ((*_blossom_set)[n] > (*_node_data)[ni].heap.prio()) {
deba@326
  2540
                _blossom_set->decrease(n, (*_node_data)[ni].heap.prio());
deba@326
  2541
deba@326
  2542
                if (_delta2->state(blossom) != _delta2->IN_HEAP) {
deba@326
  2543
                  _delta2->push(blossom, _blossom_set->classPrio(blossom) -
deba@326
  2544
                               (*_blossom_data)[blossom].offset);
deba@326
  2545
                } else if ((*_delta2)[blossom] >
deba@326
  2546
                           _blossom_set->classPrio(blossom) -
deba@326
  2547
                           (*_blossom_data)[blossom].offset){
deba@326
  2548
                  _delta2->decrease(blossom, _blossom_set->classPrio(blossom) -
deba@326
  2549
                                   (*_blossom_data)[blossom].offset);
deba@326
  2550
                }
deba@326
  2551
              }
deba@326
  2552
            }
deba@326
  2553
          } else {
deba@326
  2554
deba@326
  2555
            typename std::map<int, Arc>::iterator it =
deba@326
  2556
              (*_node_data)[vi].heap_index.find(tree);
deba@326
  2557
deba@326
  2558
            if (it != (*_node_data)[vi].heap_index.end()) {
deba@326
  2559
              (*_node_data)[vi].heap.erase(it->second);
deba@326
  2560
              (*_node_data)[vi].heap_index.erase(it);
deba@326
  2561
              if ((*_node_data)[vi].heap.empty()) {
deba@326
  2562
                _blossom_set->increase(v, std::numeric_limits<Value>::max());
deba@326
  2563
              } else if ((*_blossom_set)[v] < (*_node_data)[vi].heap.prio()) {
deba@326
  2564
                _blossom_set->increase(v, (*_node_data)[vi].heap.prio());
deba@326
  2565
              }
deba@326
  2566
deba@326
  2567
              if ((*_blossom_data)[vb].status == MATCHED) {
deba@326
  2568
                if (_blossom_set->classPrio(vb) ==
deba@326
  2569
                    std::numeric_limits<Value>::max()) {
deba@326
  2570
                  _delta2->erase(vb);
deba@326
  2571
                } else if ((*_delta2)[vb] < _blossom_set->classPrio(vb) -
deba@326
  2572
                           (*_blossom_data)[vb].offset) {
deba@326
  2573
                  _delta2->increase(vb, _blossom_set->classPrio(vb) -
deba@326
  2574
                                   (*_blossom_data)[vb].offset);
deba@326
  2575
                }
deba@326
  2576
              }
deba@326
  2577
            }
deba@326
  2578
          }
deba@326
  2579
        }
deba@326
  2580
      }
deba@326
  2581
    }
deba@326
  2582
deba@326
  2583
    void oddToMatched(int blossom) {
deba@326
  2584
      (*_blossom_data)[blossom].offset -= _delta_sum;
deba@326
  2585
deba@326
  2586
      if (_blossom_set->classPrio(blossom) !=
deba@326
  2587
          std::numeric_limits<Value>::max()) {
deba@326
  2588
        _delta2->push(blossom, _blossom_set->classPrio(blossom) -
deba@326
  2589
                       (*_blossom_data)[blossom].offset);
deba@326
  2590
      }
deba@326
  2591
deba@326
  2592
      if (!_blossom_set->trivial(blossom)) {
deba@326
  2593
        _delta4->erase(blossom);
deba@326
  2594
      }
deba@326
  2595
    }
deba@326
  2596
deba@326
  2597
    void oddToEven(int blossom, int tree) {
deba@326
  2598
      if (!_blossom_set->trivial(blossom)) {
deba@326
  2599
        _delta4->erase(blossom);
deba@326
  2600
        (*_blossom_data)[blossom].pot -=
deba@326
  2601
          2 * (2 * _delta_sum - (*_blossom_data)[blossom].offset);
deba@326
  2602
      }
deba@326
  2603
deba@326
  2604
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
deba@326
  2605
           n != INVALID; ++n) {
deba@326
  2606
        int ni = (*_node_index)[n];
deba@326
  2607
deba@326
  2608
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
deba@326
  2609
deba@326
  2610
        (*_node_data)[ni].heap.clear();
deba@326
  2611
        (*_node_data)[ni].heap_index.clear();
deba@326
  2612
        (*_node_data)[ni].pot +=
deba@326
  2613
          2 * _delta_sum - (*_blossom_data)[blossom].offset;
deba@326
  2614
deba@326
  2615
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
deba@326
  2616
          Node v = _graph.source(e);
deba@326
  2617
          int vb = _blossom_set->find(v);
deba@326
  2618
          int vi = (*_node_index)[v];
deba@326
  2619
deba@326
  2620
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
deba@326
  2621
            dualScale * _weight[e];
deba@326
  2622
deba@326
  2623
          if ((*_blossom_data)[vb].status == EVEN) {
deba@326
  2624
            if (_delta3->state(e) != _delta3->IN_HEAP && blossom != vb) {
deba@326
  2625
              _delta3->push(e, rw / 2);
deba@326
  2626
            }
deba@326
  2627
          } else {
deba@326
  2628
deba@326
  2629
            typename std::map<int, Arc>::iterator it =
deba@326
  2630
              (*_node_data)[vi].heap_index.find(tree);
deba@326
  2631
deba@326
  2632
            if (it != (*_node_data)[vi].heap_index.end()) {
deba@326
  2633
              if ((*_node_data)[vi].heap[it->second] > rw) {
deba@326
  2634
                (*_node_data)[vi].heap.replace(it->second, e);
deba@326
  2635
                (*_node_data)[vi].heap.decrease(e, rw);
deba@326
  2636
                it->second = e;
deba@326
  2637
              }
deba@326
  2638
            } else {
deba@326
  2639
              (*_node_data)[vi].heap.push(e, rw);
deba@326
  2640
              (*_node_data)[vi].heap_index.insert(std::make_pair(tree, e));
deba@326
  2641
            }
deba@326
  2642
deba@326
  2643
            if ((*_blossom_set)[v] > (*_node_data)[vi].heap.prio()) {
deba@326
  2644
              _blossom_set->decrease(v, (*_node_data)[vi].heap.prio());
deba@326
  2645
deba@326
  2646
              if ((*_blossom_data)[vb].status == MATCHED) {
deba@326
  2647
                if (_delta2->state(vb) != _delta2->IN_HEAP) {
deba@326
  2648
                  _delta2->push(vb, _blossom_set->classPrio(vb) -
deba@326
  2649
                               (*_blossom_data)[vb].offset);
deba@326
  2650
                } else if ((*_delta2)[vb] > _blossom_set->classPrio(vb) -
deba@326
  2651
                           (*_blossom_data)[vb].offset) {
deba@326
  2652
                  _delta2->decrease(vb, _blossom_set->classPrio(vb) -
deba@326
  2653
                                   (*_blossom_data)[vb].offset);
deba@326
  2654
                }
deba@326
  2655
              }
deba@326
  2656
            }
deba@326
  2657
          }
deba@326
  2658
        }
deba@326
  2659
      }
deba@326
  2660
      (*_blossom_data)[blossom].offset = 0;
deba@326
  2661
    }
deba@326
  2662
deba@326
  2663
    void alternatePath(int even, int tree) {
deba@326
  2664
      int odd;
deba@326
  2665
deba@326
  2666
      evenToMatched(even, tree);
deba@326
  2667
      (*_blossom_data)[even].status = MATCHED;
deba@326
  2668
deba@326
  2669
      while ((*_blossom_data)[even].pred != INVALID) {
deba@326
  2670
        odd = _blossom_set->find(_graph.target((*_blossom_data)[even].pred));
deba@326
  2671
        (*_blossom_data)[odd].status = MATCHED;
deba@326
  2672
        oddToMatched(odd);
deba@326
  2673
        (*_blossom_data)[odd].next = (*_blossom_data)[odd].pred;
deba@326
  2674
deba@326
  2675
        even = _blossom_set->find(_graph.target((*_blossom_data)[odd].pred));
deba@326
  2676
        (*_blossom_data)[even].status = MATCHED;
deba@326
  2677
        evenToMatched(even, tree);
deba@326
  2678
        (*_blossom_data)[even].next =
deba@326
  2679
          _graph.oppositeArc((*_blossom_data)[odd].pred);
deba@326
  2680
      }
deba@326
  2681
deba@326
  2682
    }
deba@326
  2683
deba@326
  2684
    void destroyTree(int tree) {
deba@326
  2685
      for (TreeSet::ItemIt b(*_tree_set, tree); b != INVALID; ++b) {
deba@326
  2686
        if ((*_blossom_data)[b].status == EVEN) {
deba@326
  2687
          (*_blossom_data)[b].status = MATCHED;
deba@326
  2688
          evenToMatched(b, tree);
deba@326
  2689
        } else if ((*_blossom_data)[b].status == ODD) {
deba@326
  2690
          (*_blossom_data)[b].status = MATCHED;
deba@326
  2691
          oddToMatched(b);
deba@326
  2692
        }
deba@326
  2693
      }
deba@326
  2694
      _tree_set->eraseClass(tree);
deba@326
  2695
    }
deba@326
  2696
deba@327
  2697
    void augmentOnEdge(const Edge& edge) {
deba@327
  2698
deba@327
  2699
      int left = _blossom_set->find(_graph.u(edge));
deba@327
  2700
      int right = _blossom_set->find(_graph.v(edge));
deba@326
  2701
deba@326
  2702
      int left_tree = _tree_set->find(left);
deba@326
  2703
      alternatePath(left, left_tree);
deba@326
  2704
      destroyTree(left_tree);
deba@326
  2705
deba@326
  2706
      int right_tree = _tree_set->find(right);
deba@326
  2707
      alternatePath(right, right_tree);
deba@326
  2708
      destroyTree(right_tree);
deba@326
  2709
deba@327
  2710
      (*_blossom_data)[left].next = _graph.direct(edge, true);
deba@327
  2711
      (*_blossom_data)[right].next = _graph.direct(edge, false);
deba@326
  2712
    }
deba@326
  2713
deba@326
  2714
    void extendOnArc(const Arc& arc) {
deba@326
  2715
      int base = _blossom_set->find(_graph.target(arc));
deba@326
  2716
      int tree = _tree_set->find(base);
deba@326
  2717
deba@326
  2718
      int odd = _blossom_set->find(_graph.source(arc));
deba@326
  2719
      _tree_set->insert(odd, tree);
deba@326
  2720
      (*_blossom_data)[odd].status = ODD;
deba@326
  2721
      matchedToOdd(odd);
deba@326
  2722
      (*_blossom_data)[odd].pred = arc;
deba@326
  2723
deba@326
  2724
      int even = _blossom_set->find(_graph.target((*_blossom_data)[odd].next));
deba@326
  2725
      (*_blossom_data)[even].pred = (*_blossom_data)[even].next;
deba@326
  2726
      _tree_set->insert(even, tree);
deba@326
  2727
      (*_blossom_data)[even].status = EVEN;
deba@326
  2728
      matchedToEven(even, tree);
deba@326
  2729
    }
deba@326
  2730
deba@327
  2731
    void shrinkOnEdge(const Edge& edge, int tree) {
deba@326
  2732
      int nca = -1;
deba@326
  2733
      std::vector<int> left_path, right_path;
deba@326
  2734
deba@326
  2735
      {
deba@326
  2736
        std::set<int> left_set, right_set;
deba@326
  2737
        int left = _blossom_set->find(_graph.u(edge));
deba@326
  2738
        left_path.push_back(left);
deba@326
  2739
        left_set.insert(left);
deba@326
  2740
deba@326
  2741
        int right = _blossom_set->find(_graph.v(edge));
deba@326
  2742
        right_path.push_back(right);
deba@326
  2743
        right_set.insert(right);
deba@326
  2744
deba@326
  2745
        while (true) {
deba@326
  2746
deba@326
  2747
          if ((*_blossom_data)[left].pred == INVALID) break;
deba@326
  2748
deba@326
  2749
          left =
deba@326
  2750
            _blossom_set->find(_graph.target((*_blossom_data)[left].pred));
deba@326
  2751
          left_path.push_back(left);
deba@326
  2752
          left =
deba@326
  2753
            _blossom_set->find(_graph.target((*_blossom_data)[left].pred));
deba@326
  2754
          left_path.push_back(left);
deba@326
  2755
deba@326
  2756
          left_set.insert(left);
deba@326
  2757
deba@326
  2758
          if (right_set.find(left) != right_set.end()) {
deba@326
  2759
            nca = left;
deba@326
  2760
            break;
deba@326
  2761
          }
deba@326
  2762
deba@326
  2763
          if ((*_blossom_data)[right].pred == INVALID) break;
deba@326
  2764
deba@326
  2765
          right =
deba@326
  2766
            _blossom_set->find(_graph.target((*_blossom_data)[right].pred));
deba@326
  2767
          right_path.push_back(right);
deba@326
  2768
          right =
deba@326
  2769
            _blossom_set->find(_graph.target((*_blossom_data)[right].pred));
deba@326
  2770
          right_path.push_back(right);
deba@326
  2771
deba@326
  2772
          right_set.insert(right);
deba@326
  2773
deba@326
  2774
          if (left_set.find(right) != left_set.end()) {
deba@326
  2775
            nca = right;
deba@326
  2776
            break;
deba@326
  2777
          }
deba@326
  2778
deba@326
  2779
        }
deba@326
  2780
deba@326
  2781
        if (nca == -1) {
deba@326
  2782
          if ((*_blossom_data)[left].pred == INVALID) {
deba@326
  2783
            nca = right;
deba@326
  2784
            while (left_set.find(nca) == left_set.end()) {
deba@326
  2785
              nca =
deba@326
  2786
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
deba@326
  2787
              right_path.push_back(nca);
deba@326
  2788
              nca =
deba@326
  2789
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
deba@326
  2790
              right_path.push_back(nca);
deba@326
  2791
            }
deba@326
  2792
          } else {
deba@326
  2793
            nca = left;
deba@326
  2794
            while (right_set.find(nca) == right_set.end()) {
deba@326
  2795
              nca =
deba@326
  2796
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
deba@326
  2797
              left_path.push_back(nca);
deba@326
  2798
              nca =
deba@326
  2799
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
deba@326
  2800
              left_path.push_back(nca);
deba@326
  2801
            }
deba@326
  2802
          }
deba@326
  2803
        }
deba@326
  2804
      }
deba@326
  2805
deba@326
  2806
      std::vector<int> subblossoms;
deba@326
  2807
      Arc prev;
deba@326
  2808
deba@326
  2809
      prev = _graph.direct(edge, true);
deba@326
  2810
      for (int i = 0; left_path[i] != nca; i += 2) {
deba@326
  2811
        subblossoms.push_back(left_path[i]);
deba@326
  2812
        (*_blossom_data)[left_path[i]].next = prev;
deba@326
  2813
        _tree_set->erase(left_path[i]);
deba@326
  2814
deba@326
  2815
        subblossoms.push_back(left_path[i + 1]);
deba@326
  2816
        (*_blossom_data)[left_path[i + 1]].status = EVEN;
deba@326
  2817
        oddToEven(left_path[i + 1], tree);
deba@326
  2818
        _tree_set->erase(left_path[i + 1]);
deba@326
  2819
        prev = _graph.oppositeArc((*_blossom_data)[left_path[i + 1]].pred);
deba@326
  2820
      }
deba@326
  2821
deba@326
  2822
      int k = 0;
deba@326
  2823
      while (right_path[k] != nca) ++k;
deba@326
  2824
deba@326
  2825
      subblossoms.push_back(nca);
deba@326
  2826
      (*_blossom_data)[nca].next = prev;
deba@326
  2827
deba@326
  2828
      for (int i = k - 2; i >= 0; i -= 2) {
deba@326
  2829
        subblossoms.push_back(right_path[i + 1]);
deba@326
  2830
        (*_blossom_data)[right_path[i + 1]].status = EVEN;
deba@326
  2831
        oddToEven(right_path[i + 1], tree);
deba@326
  2832
        _tree_set->erase(right_path[i + 1]);
deba@326
  2833
deba@326
  2834
        (*_blossom_data)[right_path[i + 1]].next =
deba@326
  2835
          (*_blossom_data)[right_path[i + 1]].pred;
deba@326
  2836
deba@326
  2837
        subblossoms.push_back(right_path[i]);
deba@326
  2838
        _tree_set->erase(right_path[i]);
deba@326
  2839
      }
deba@326
  2840
deba@326
  2841
      int surface =
deba@326
  2842
        _blossom_set->join(subblossoms.begin(), subblossoms.end());
deba@326
  2843
deba@326
  2844
      for (int i = 0; i < int(subblossoms.size()); ++i) {
deba@326
  2845
        if (!_blossom_set->trivial(subblossoms[i])) {
deba@326
  2846
          (*_blossom_data)[subblossoms[i]].pot += 2 * _delta_sum;
deba@326
  2847
        }
deba@326
  2848
        (*_blossom_data)[subblossoms[i]].status = MATCHED;
deba@326
  2849
      }
deba@326
  2850
deba@326
  2851
      (*_blossom_data)[surface].pot = -2 * _delta_sum;
deba@326
  2852
      (*_blossom_data)[surface].offset = 0;
deba@326
  2853
      (*_blossom_data)[surface].status = EVEN;
deba@326
  2854
      (*_blossom_data)[surface].pred = (*_blossom_data)[nca].pred;
deba@326
  2855
      (*_blossom_data)[surface].next = (*_blossom_data)[nca].pred;
deba@326
  2856
deba@326
  2857
      _tree_set->insert(surface, tree);
deba@326
  2858
      _tree_set->erase(nca);
deba@326
  2859
    }
deba@326
  2860
deba@326
  2861
    void splitBlossom(int blossom) {
deba@326
  2862
      Arc next = (*_blossom_data)[blossom].next;
deba@326
  2863
      Arc pred = (*_blossom_data)[blossom].pred;
deba@326
  2864
deba@326
  2865
      int tree = _tree_set->find(blossom);
deba@326
  2866
deba@326
  2867
      (*_blossom_data)[blossom].status = MATCHED;
deba@326
  2868
      oddToMatched(blossom);
deba@326
  2869
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
deba@326
  2870
        _delta2->erase(blossom);
deba@326
  2871
      }
deba@326
  2872
deba@326
  2873
      std::vector<int> subblossoms;
deba@326
  2874
      _blossom_set->split(blossom, std::back_inserter(subblossoms));
deba@326
  2875
deba@326
  2876
      Value offset = (*_blossom_data)[blossom].offset;
deba@326
  2877
      int b = _blossom_set->find(_graph.source(pred));
deba@326
  2878
      int d = _blossom_set->find(_graph.source(next));
deba@326
  2879
deba@326
  2880
      int ib = -1, id = -1;
deba@326
  2881
      for (int i = 0; i < int(subblossoms.size()); ++i) {
deba@326
  2882
        if (subblossoms[i] == b) ib = i;
deba@326
  2883
        if (subblossoms[i] == d) id = i;
deba@326
  2884
deba@326
  2885
        (*_blossom_data)[subblossoms[i]].offset = offset;
deba@326
  2886
        if (!_blossom_set->trivial(subblossoms[i])) {
deba@326
  2887
          (*_blossom_data)[subblossoms[i]].pot -= 2 * offset;
deba@326
  2888
        }
deba@326
  2889
        if (_blossom_set->classPrio(subblossoms[i]) !=
deba@326
  2890
            std::numeric_limits<Value>::max()) {
deba@326
  2891
          _delta2->push(subblossoms[i],
deba@326
  2892
                        _blossom_set->classPrio(subblossoms[i]) -
deba@326
  2893
                        (*_blossom_data)[subblossoms[i]].offset);
deba@326
  2894
        }
deba@326
  2895
      }
deba@326
  2896
deba@326
  2897
      if (id > ib ? ((id - ib) % 2 == 0) : ((ib - id) % 2 == 1)) {
deba@326
  2898
        for (int i = (id + 1) % subblossoms.size();
deba@326
  2899
             i != ib; i = (i + 2) % subblossoms.size()) {
deba@326
  2900
          int sb = subblossoms[i];
deba@326
  2901
          int tb = subblossoms[(i + 1) % subblossoms.size()];
deba@326
  2902
          (*_blossom_data)[sb].next =
deba@326
  2903
            _graph.oppositeArc((*_blossom_data)[tb].next);
deba@326
  2904
        }
deba@326
  2905
deba@326
  2906
        for (int i = ib; i != id; i = (i + 2) % subblossoms.size()) {
deba@326
  2907
          int sb = subblossoms[i];
deba@326
  2908
          int tb = subblossoms[(i + 1) % subblossoms.size()];
deba@326
  2909
          int ub = subblossoms[(i + 2) % subblossoms.size()];
deba@326
  2910
deba@326
  2911
          (*_blossom_data)[sb].status = ODD;
deba@326
  2912
          matchedToOdd(sb);
deba@326
  2913
          _tree_set->insert(sb, tree);
deba@326
  2914
          (*_blossom_data)[sb].pred = pred;
deba@326
  2915
          (*_blossom_data)[sb].next =
deba@326
  2916
                           _graph.oppositeArc((*_blossom_data)[tb].next);
deba@326
  2917
deba@326
  2918
          pred = (*_blossom_data)[ub].next;
deba@326
  2919
deba@326
  2920
          (*_blossom_data)[tb].status = EVEN;
deba@326
  2921
          matchedToEven(tb, tree);
deba@326
  2922
          _tree_set->insert(tb, tree);
deba@326
  2923
          (*_blossom_data)[tb].pred = (*_blossom_data)[tb].next;
deba@326
  2924
        }
deba@326
  2925
deba@326
  2926
        (*_blossom_data)[subblossoms[id]].status = ODD;
deba@326
  2927
        matchedToOdd(subblossoms[id]);
deba@326
  2928
        _tree_set->insert(subblossoms[id], tree);
deba@326
  2929
        (*_blossom_data)[subblossoms[id]].next = next;
deba@326
  2930
        (*_blossom_data)[subblossoms[id]].pred = pred;
deba@326
  2931
deba@326
  2932
      } else {
deba@326
  2933
deba@326
  2934
        for (int i = (ib + 1) % subblossoms.size();
deba@326
  2935
             i != id; i = (i + 2) % subblossoms.size()) {
deba@326
  2936
          int sb = subblossoms[i];
deba@326
  2937
          int tb = subblossoms[(i + 1) % subblossoms.size()];
deba@326
  2938
          (*_blossom_data)[sb].next =
deba@326
  2939
            _graph.oppositeArc((*_blossom_data)[tb].next);
deba@326
  2940
        }
deba@326
  2941
deba@326
  2942
        for (int i = id; i != ib; i = (i + 2) % subblossoms.size()) {
deba@326
  2943
          int sb = subblossoms[i];
deba@326
  2944
          int tb = subblossoms[(i + 1) % subblossoms.size()];
deba@326
  2945
          int ub = subblossoms[(i + 2) % subblossoms.size()];
deba@326
  2946
deba@326
  2947
          (*_blossom_data)[sb].status = ODD;
deba@326
  2948
          matchedToOdd(sb);
deba@326
  2949
          _tree_set->insert(sb, tree);
deba@326
  2950
          (*_blossom_data)[sb].next = next;
deba@326
  2951
          (*_blossom_data)[sb].pred =
deba@326
  2952
            _graph.oppositeArc((*_blossom_data)[tb].next);
deba@326
  2953
deba@326
  2954
          (*_blossom_data)[tb].status = EVEN;
deba@326
  2955
          matchedToEven(tb, tree);
deba@326
  2956
          _tree_set->insert(tb, tree);
deba@326
  2957
          (*_blossom_data)[tb].pred =
deba@326
  2958
            (*_blossom_data)[tb].next =
deba@326
  2959
            _graph.oppositeArc((*_blossom_data)[ub].next);
deba@326
  2960
          next = (*_blossom_data)[ub].next;
deba@326
  2961
        }
deba@326
  2962
deba@326
  2963
        (*_blossom_data)[subblossoms[ib]].status = ODD;
deba@326
  2964
        matchedToOdd(subblossoms[ib]);
deba@326
  2965
        _tree_set->insert(subblossoms[ib], tree);
deba@326
  2966
        (*_blossom_data)[subblossoms[ib]].next = next;
deba@326
  2967
        (*_blossom_data)[subblossoms[ib]].pred = pred;
deba@326
  2968
      }
deba@326
  2969
      _tree_set->erase(blossom);
deba@326
  2970
    }
deba@326
  2971
deba@1208
  2972
    struct ExtractBlossomItem {
deba@1208
  2973
      int blossom;
deba@1208
  2974
      Node base;
deba@1208
  2975
      Arc matching;
deba@1208
  2976
      int close_index;
deba@1208
  2977
      ExtractBlossomItem(int _blossom, Node _base,
deba@1208
  2978
                         Arc _matching, int _close_index)
deba@1208
  2979
          : blossom(_blossom), base(_base), matching(_matching),
deba@1208
  2980
            close_index(_close_index) {}
deba@1208
  2981
    };
deba@1208
  2982
deba@326
  2983
    void extractBlossom(int blossom, const Node& base, const Arc& matching) {
deba@1208
  2984
      std::vector<ExtractBlossomItem> stack;
deba@1208
  2985
      std::vector<int> close_stack;
deba@1208
  2986
      stack.push_back(ExtractBlossomItem(blossom, base, matching, 0));
deba@1208
  2987
      while (!stack.empty()) {
deba@1208
  2988
        if (_blossom_set->trivial(stack.back().blossom)) {
deba@1208
  2989
          int bi = (*_node_index)[stack.back().base];
deba@1208
  2990
          Value pot = (*_node_data)[bi].pot;
deba@1208
  2991
deba@1208
  2992
          (*_matching)[stack.back().base] = stack.back().matching;
deba@1208
  2993
          (*_node_potential)[stack.back().base] = pot;
deba@1208
  2994
          _blossom_node_list.push_back(stack.back().base);
deba@1208
  2995
          while (int(close_stack.size()) > stack.back().close_index) {
deba@1208
  2996
            _blossom_potential[close_stack.back()].end = _blossom_node_list.size();
deba@1208
  2997
            close_stack.pop_back();
deba@1208
  2998
          }
deba@1208
  2999
          stack.pop_back();
deba@1208
  3000
        } else {
deba@1208
  3001
          Value pot = (*_blossom_data)[stack.back().blossom].pot;
deba@1208
  3002
          int bn = _blossom_node_list.size();
deba@1208
  3003
          close_stack.push_back(_blossom_potential.size());
deba@1208
  3004
          _blossom_potential.push_back(BlossomVariable(bn, pot));
deba@1208
  3005
deba@1208
  3006
          std::vector<int> subblossoms;
deba@1208
  3007
          _blossom_set->split(stack.back().blossom, std::back_inserter(subblossoms));
deba@1208
  3008
          int b = _blossom_set->find(stack.back().base);
deba@1208
  3009
          int ib = -1;
deba@1208
  3010
          for (int i = 0; i < int(subblossoms.size()); ++i) {
deba@1208
  3011
            if (subblossoms[i] == b) { ib = i; break; }
deba@1208
  3012
          }
deba@1208
  3013
deba@1208
  3014
          stack.back().blossom = subblossoms[ib];
deba@1208
  3015
          for (int i = 1; i < int(subblossoms.size()); i += 2) {
deba@1208
  3016
            int sb = subblossoms[(ib + i) % subblossoms.size()];
deba@1208
  3017
            int tb = subblossoms[(ib + i + 1) % subblossoms.size()];
deba@1208
  3018
deba@1208
  3019
            Arc m = (*_blossom_data)[tb].next;
deba@1208
  3020
            stack.push_back(ExtractBlossomItem(
deba@1208
  3021
                sb, _graph.target(m), _graph.oppositeArc(m), close_stack.size()));
deba@1208
  3022
            stack.push_back(ExtractBlossomItem(
deba@1208
  3023
                tb, _graph.source(m), m, close_stack.size()));
deba@1208
  3024
          }
deba@326
  3025
        }
deba@326
  3026
      }
deba@326
  3027
    }
deba@326
  3028
deba@326
  3029
    void extractMatching() {
deba@326
  3030
      std::vector<int> blossoms;
deba@326
  3031
      for (typename BlossomSet::ClassIt c(*_blossom_set); c != INVALID; ++c) {
deba@326
  3032
        blossoms.push_back(c);
deba@326
  3033
      }
deba@326
  3034
deba@326
  3035
      for (int i = 0; i < int(blossoms.size()); ++i) {
deba@326
  3036
deba@326
  3037
        Value offset = (*_blossom_data)[blossoms[i]].offset;
deba@326
  3038
        (*_blossom_data)[blossoms[i]].pot += 2 * offset;
deba@326
  3039
        for (typename BlossomSet::ItemIt n(*_blossom_set, blossoms[i]);
deba@326
  3040
             n != INVALID; ++n) {
deba@326
  3041
          (*_node_data)[(*_node_index)[n]].pot -= offset;
deba@326
  3042
        }
deba@326
  3043
deba@326
  3044
        Arc matching = (*_blossom_data)[blossoms[i]].next;
deba@326
  3045
        Node base = _graph.source(matching);
deba@326
  3046
        extractBlossom(blossoms[i], base, matching);
deba@326
  3047
      }
deba@326
  3048
    }
deba@326
  3049
deba@326
  3050
  public:
deba@326
  3051
deba@326
  3052
    /// \brief Constructor
deba@326
  3053
    ///
deba@326
  3054
    /// Constructor.
deba@326
  3055
    MaxWeightedPerfectMatching(const Graph& graph, const WeightMap& weight)
deba@326
  3056
      : _graph(graph), _weight(weight), _matching(0),
deba@326
  3057
        _node_potential(0), _blossom_potential(), _blossom_node_list(),
deba@326
  3058
        _node_num(0), _blossom_num(0),
deba@326
  3059
deba@326
  3060
        _blossom_index(0), _blossom_set(0), _blossom_data(0),
deba@326
  3061
        _node_index(0), _node_heap_index(0), _node_data(0),
deba@326
  3062
        _tree_set_index(0), _tree_set(0),
deba@326
  3063
deba@326
  3064
        _delta2_index(0), _delta2(0),
deba@326
  3065
        _delta3_index(0), _delta3(0),
deba@326
  3066
        _delta4_index(0), _delta4(0),
deba@326
  3067
deba@870
  3068
        _delta_sum(), _unmatched(0),
deba@870
  3069
deba@870
  3070
        _fractional(0)
deba@870
  3071
    {}
deba@326
  3072
deba@326
  3073
    ~MaxWeightedPerfectMatching() {
deba@326
  3074
      destroyStructures();
deba@870
  3075
      if (_fractional) {
deba@870
  3076
        delete _fractional;
deba@870
  3077
      }
deba@326
  3078
    }
deba@326
  3079
kpeter@590
  3080
    /// \name Execution Control
alpar@330
  3081
    /// The simplest way to execute the algorithm is to use the
kpeter@590
  3082
    /// \ref run() member function.
deba@326
  3083
deba@326
  3084
    ///@{
deba@326
  3085
deba@326
  3086
    /// \brief Initialize the algorithm
deba@326
  3087
    ///
kpeter@590
  3088
    /// This function initializes the algorithm.
deba@326
  3089
    void init() {
deba@326
  3090
      createStructures();
deba@326
  3091
deba@867
  3092
      _blossom_node_list.clear();
deba@867
  3093
      _blossom_potential.clear();
deba@867
  3094
deba@326
  3095
      for (ArcIt e(_graph); e != INVALID; ++e) {
kpeter@581
  3096
        (*_node_heap_index)[e] = BinHeap<Value, IntArcMap>::PRE_HEAP;
deba@326
  3097
      }
deba@326
  3098
      for (EdgeIt e(_graph); e != INVALID; ++e) {
kpeter@581
  3099
        (*_delta3_index)[e] = _delta3->PRE_HEAP;
deba@326
  3100
      }
deba@326
  3101
      for (int i = 0; i < _blossom_num; ++i) {
kpeter@581
  3102
        (*_delta2_index)[i] = _delta2->PRE_HEAP;
kpeter@581
  3103
        (*_delta4_index)[i] = _delta4->PRE_HEAP;
deba@326
  3104
      }
deba@326
  3105
deba@870
  3106
      _unmatched = _node_num;
deba@870
  3107
deba@867
  3108
      _delta2->clear();
deba@867
  3109
      _delta3->clear();
deba@867
  3110
      _delta4->clear();
deba@867
  3111
      _blossom_set->clear();
deba@867
  3112
      _tree_set->clear();
deba@867
  3113
deba@326
  3114
      int index = 0;
deba@326
  3115
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@326
  3116
        Value max = - std::numeric_limits<Value>::max();
deba@326
  3117
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
deba@326
  3118
          if (_graph.target(e) == n) continue;
deba@326
  3119
          if ((dualScale * _weight[e]) / 2 > max) {
deba@326
  3120
            max = (dualScale * _weight[e]) / 2;
deba@326
  3121
          }
deba@326
  3122
        }
kpeter@581
  3123
        (*_node_index)[n] = index;
deba@867
  3124
        (*_node_data)[index].heap_index.clear();
deba@867
  3125
        (*_node_data)[index].heap.clear();
deba@326
  3126
        (*_node_data)[index].pot = max;
deba@326
  3127
        int blossom =
deba@326
  3128
          _blossom_set->insert(n, std::numeric_limits<Value>::max());
deba@326
  3129
deba@326
  3130
        _tree_set->insert(blossom);
deba@326
  3131
deba@326
  3132
        (*_blossom_data)[blossom].status = EVEN;
deba@326
  3133
        (*_blossom_data)[blossom].pred = INVALID;
deba@326
  3134
        (*_blossom_data)[blossom].next = INVALID;
deba@326
  3135
        (*_blossom_data)[blossom].pot = 0;
deba@326
  3136
        (*_blossom_data)[blossom].offset = 0;
deba@326
  3137
        ++index;
deba@326
  3138
      }
deba@326
  3139
      for (EdgeIt e(_graph); e != INVALID; ++e) {
deba@326
  3140
        int si = (*_node_index)[_graph.u(e)];
deba@326
  3141
        int ti = (*_node_index)[_graph.v(e)];
deba@326
  3142
        if (_graph.u(e) != _graph.v(e)) {
deba@326
  3143
          _delta3->push(e, ((*_node_data)[si].pot + (*_node_data)[ti].pot -
deba@326
  3144
                            dualScale * _weight[e]) / 2);
deba@326
  3145
        }
deba@326
  3146
      }
deba@326
  3147
    }
deba@326
  3148
deba@870
  3149
    /// \brief Initialize the algorithm with fractional matching
deba@870
  3150
    ///
deba@870
  3151
    /// This function initializes the algorithm with a fractional
deba@870
  3152
    /// matching. This initialization is also called jumpstart heuristic.
deba@870
  3153
    void fractionalInit() {
deba@870
  3154
      createStructures();
deba@876
  3155
deba@876
  3156
      _blossom_node_list.clear();
deba@876
  3157
      _blossom_potential.clear();
alpar@877
  3158
deba@870
  3159
      if (_fractional == 0) {
deba@870
  3160
        _fractional = new FractionalMatching(_graph, _weight, false);
deba@870
  3161
      }
deba@870
  3162
      if (!_fractional->run()) {
deba@870
  3163
        _unmatched = -1;
deba@870
  3164
        return;
deba@870
  3165
      }
deba@870
  3166
deba@870
  3167
      for (ArcIt e(_graph); e != INVALID; ++e) {
deba@870
  3168
        (*_node_heap_index)[e] = BinHeap<Value, IntArcMap>::PRE_HEAP;
deba@870
  3169
      }
deba@870
  3170
      for (EdgeIt e(_graph); e != INVALID; ++e) {
deba@870
  3171
        (*_delta3_index)[e] = _delta3->PRE_HEAP;
deba@870
  3172
      }
deba@870
  3173
      for (int i = 0; i < _blossom_num; ++i) {
deba@870
  3174
        (*_delta2_index)[i] = _delta2->PRE_HEAP;
deba@870
  3175
        (*_delta4_index)[i] = _delta4->PRE_HEAP;
deba@870
  3176
      }
deba@870
  3177
deba@870
  3178
      _unmatched = 0;
deba@870
  3179
deba@876
  3180
      _delta2->clear();
deba@876
  3181
      _delta3->clear();
deba@876
  3182
      _delta4->clear();
deba@876
  3183
      _blossom_set->clear();
deba@876
  3184
      _tree_set->clear();
deba@876
  3185
deba@870
  3186
      int index = 0;
deba@870
  3187
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@870
  3188
        Value pot = _fractional->nodeValue(n);
deba@870
  3189
        (*_node_index)[n] = index;
deba@870
  3190
        (*_node_data)[index].pot = pot;
deba@876
  3191
        (*_node_data)[index].heap_index.clear();
deba@876
  3192
        (*_node_data)[index].heap.clear();
deba@870
  3193
        int blossom =
deba@870
  3194
          _blossom_set->insert(n, std::numeric_limits<Value>::max());
deba@870
  3195
deba@870
  3196
        (*_blossom_data)[blossom].status = MATCHED;
deba@870
  3197
        (*_blossom_data)[blossom].pred = INVALID;
deba@870
  3198
        (*_blossom_data)[blossom].next = _fractional->matching(n);
deba@870
  3199
        (*_blossom_data)[blossom].pot = 0;
deba@870
  3200
        (*_blossom_data)[blossom].offset = 0;
deba@870
  3201
        ++index;
deba@870
  3202
      }
deba@870
  3203
deba@870
  3204
      typename Graph::template NodeMap<bool> processed(_graph, false);
deba@870
  3205
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@870
  3206
        if (processed[n]) continue;
deba@870
  3207
        processed[n] = true;
deba@870
  3208
        if (_fractional->matching(n) == INVALID) continue;
deba@870
  3209
        int num = 1;
deba@870
  3210
        Node v = _graph.target(_fractional->matching(n));
deba@870
  3211
        while (n != v) {
deba@870
  3212
          processed[v] = true;
deba@870
  3213
          v = _graph.target(_fractional->matching(v));
deba@870
  3214
          ++num;
deba@870
  3215
        }
deba@870
  3216
deba@870
  3217
        if (num % 2 == 1) {
deba@870
  3218
          std::vector<int> subblossoms(num);
deba@870
  3219
deba@870
  3220
          subblossoms[--num] = _blossom_set->find(n);
deba@870
  3221
          v = _graph.target(_fractional->matching(n));
deba@870
  3222
          while (n != v) {
deba@870
  3223
            subblossoms[--num] = _blossom_set->find(v);
alpar@877
  3224
            v = _graph.target(_fractional->matching(v));
deba@870
  3225
          }
alpar@877
  3226
alpar@877
  3227
          int surface =
deba@870
  3228
            _blossom_set->join(subblossoms.begin(), subblossoms.end());
deba@870
  3229
          (*_blossom_data)[surface].status = EVEN;
deba@870
  3230
          (*_blossom_data)[surface].pred = INVALID;
deba@870
  3231
          (*_blossom_data)[surface].next = INVALID;
deba@870
  3232
          (*_blossom_data)[surface].pot = 0;
deba@870
  3233
          (*_blossom_data)[surface].offset = 0;
alpar@877
  3234
deba@870
  3235
          _tree_set->insert(surface);
deba@870
  3236
          ++_unmatched;
deba@870
  3237
        }
deba@870
  3238
      }
deba@870
  3239
deba@870
  3240
      for (EdgeIt e(_graph); e != INVALID; ++e) {
deba@870
  3241
        int si = (*_node_index)[_graph.u(e)];
deba@870
  3242
        int sb = _blossom_set->find(_graph.u(e));
deba@870
  3243
        int ti = (*_node_index)[_graph.v(e)];
deba@870
  3244
        int tb = _blossom_set->find(_graph.v(e));
deba@870
  3245
        if ((*_blossom_data)[sb].status == EVEN &&
deba@870
  3246
            (*_blossom_data)[tb].status == EVEN && sb != tb) {
deba@870
  3247
          _delta3->push(e, ((*_node_data)[si].pot + (*_node_data)[ti].pot -
deba@870
  3248
                            dualScale * _weight[e]) / 2);
deba@870
  3249
        }
deba@870
  3250
      }
deba@870
  3251
deba@870
  3252
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@870
  3253
        int nb = _blossom_set->find(n);
deba@870
  3254
        if ((*_blossom_data)[nb].status != MATCHED) continue;
deba@870
  3255
        int ni = (*_node_index)[n];
deba@870
  3256
deba@870
  3257
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
deba@870
  3258
          Node v = _graph.target(e);
deba@870
  3259
          int vb = _blossom_set->find(v);
deba@870
  3260
          int vi = (*_node_index)[v];
deba@870
  3261
deba@870
  3262
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
deba@870
  3263
            dualScale * _weight[e];
deba@870
  3264
deba@870
  3265
          if ((*_blossom_data)[vb].status == EVEN) {
deba@870
  3266
deba@870
  3267
            int vt = _tree_set->find(vb);
deba@870
  3268
deba@870
  3269
            typename std::map<int, Arc>::iterator it =
deba@870
  3270
              (*_node_data)[ni].heap_index.find(vt);
deba@870
  3271
deba@870
  3272
            if (it != (*_node_data)[ni].heap_index.end()) {
deba@870
  3273
              if ((*_node_data)[ni].heap[it->second] > rw) {
deba@870
  3274
                (*_node_data)[ni].heap.replace(it->second, e);
deba@870
  3275
                (*_node_data)[ni].heap.decrease(e, rw);
deba@870
  3276
                it->second = e;
deba@870
  3277
              }
deba@870
  3278
            } else {
deba@870
  3279
              (*_node_data)[ni].heap.push(e, rw);
deba@870
  3280
              (*_node_data)[ni].heap_index.insert(std::make_pair(vt, e));
deba@870
  3281
            }
deba@870
  3282
          }
deba@870
  3283
        }
alpar@877
  3284
deba@870
  3285
        if (!(*_node_data)[ni].heap.empty()) {
deba@870
  3286
          _blossom_set->decrease(n, (*_node_data)[ni].heap.prio());
deba@870
  3287
          _delta2->push(nb, _blossom_set->classPrio(nb));
deba@870
  3288
        }
deba@870
  3289
      }
deba@870
  3290
    }
deba@870
  3291
kpeter@590
  3292
    /// \brief Start the algorithm
deba@326
  3293
    ///
kpeter@590
  3294
    /// This function starts the algorithm.
kpeter@590
  3295
    ///
deba@870
  3296
    /// \pre \ref init() or \ref fractionalInit() must be called before
deba@870
  3297
    /// using this function.
deba@326
  3298
    bool start() {
deba@326
  3299
      enum OpType {
deba@326
  3300
        D2, D3, D4
deba@326
  3301
      };
deba@326
  3302
deba@870
  3303
      if (_unmatched == -1) return false;
deba@870
  3304
deba@870
  3305
      while (_unmatched > 0) {
deba@326
  3306
        Value d2 = !_delta2->empty() ?
deba@326
  3307
          _delta2->prio() : std::numeric_limits<Value>::max();
deba@326
  3308
deba@326
  3309
        Value d3 = !_delta3->empty() ?
deba@326
  3310
          _delta3->prio() : std::numeric_limits<Value>::max();
deba@326
  3311
deba@326
  3312
        Value d4 = !_delta4->empty() ?
deba@326
  3313
          _delta4->prio() : std::numeric_limits<Value>::max();
deba@326
  3314
deba@868
  3315
        _delta_sum = d3; OpType ot = D3;
deba@868
  3316
        if (d2 < _delta_sum) { _delta_sum = d2; ot = D2; }
deba@326
  3317
        if (d4 < _delta_sum) { _delta_sum = d4; ot = D4; }
deba@326
  3318
deba@326
  3319
        if (_delta_sum == std::numeric_limits<Value>::max()) {
deba@326
  3320
          return false;
deba@326
  3321
        }
deba@326
  3322
deba@326
  3323
        switch (ot) {
deba@326
  3324
        case D2:
deba@326
  3325
          {
deba@326
  3326
            int blossom = _delta2->top();
deba@326
  3327
            Node n = _blossom_set->classTop(blossom);
deba@326
  3328
            Arc e = (*_node_data)[(*_node_index)[n]].heap.top();
deba@326
  3329
            extendOnArc(e);
deba@326
  3330
          }
deba@326
  3331
          break;
deba@326
  3332
        case D3:
deba@326
  3333
          {
deba@326
  3334
            Edge e = _delta3->top();
deba@326
  3335
deba@326
  3336
            int left_blossom = _blossom_set->find(_graph.u(e));
deba@326
  3337
            int right_blossom = _blossom_set->find(_graph.v(e));
deba@326
  3338
deba@326
  3339
            if (left_blossom == right_blossom) {
deba@326
  3340
              _delta3->pop();
deba@326
  3341
            } else {
deba@326
  3342
              int left_tree = _tree_set->find(left_blossom);
deba@326
  3343
              int right_tree = _tree_set->find(right_blossom);
deba@326
  3344
deba@326
  3345
              if (left_tree == right_tree) {
deba@327
  3346
                shrinkOnEdge(e, left_tree);
deba@326
  3347
              } else {
deba@327
  3348
                augmentOnEdge(e);
deba@870
  3349
                _unmatched -= 2;
deba@326
  3350
              }
deba@326
  3351
            }
deba@326
  3352
          } break;
deba@326
  3353
        case D4:
deba@326
  3354
          splitBlossom(_delta4->top());
deba@326
  3355
          break;
deba@326
  3356
        }
deba@326
  3357
      }
deba@326
  3358
      extractMatching();
deba@326
  3359
      return true;
deba@326
  3360
    }
deba@326
  3361
kpeter@590
  3362
    /// \brief Run the algorithm.
deba@326
  3363
    ///
kpeter@590
  3364
    /// This method runs the \c %MaxWeightedPerfectMatching algorithm.
deba@326
  3365
    ///
kpeter@590
  3366
    /// \note mwpm.run() is just a shortcut of the following code.
deba@326
  3367
    /// \code
deba@870
  3368
    ///   mwpm.fractionalInit();
kpeter@590
  3369
    ///   mwpm.start();
deba@326
  3370
    /// \endcode
deba@326
  3371
    bool run() {
deba@870
  3372
      fractionalInit();
deba@326
  3373
      return start();
deba@326
  3374
    }
deba@326
  3375
deba@326
  3376
    /// @}
deba@326
  3377
kpeter@590
  3378
    /// \name Primal Solution
deba@868
  3379
    /// Functions to get the primal solution, i.e. the maximum weighted
kpeter@590
  3380
    /// perfect matching.\n
kpeter@590
  3381
    /// Either \ref run() or \ref start() function should be called before
kpeter@590
  3382
    /// using them.
deba@326
  3383
deba@326
  3384
    /// @{
deba@326
  3385
kpeter@590
  3386
    /// \brief Return the weight of the matching.
deba@326
  3387
    ///
kpeter@590
  3388
    /// This function returns the weight of the found matching.
kpeter@590
  3389
    ///
kpeter@590
  3390
    /// \pre Either run() or start() must be called before using this function.
kpeter@593
  3391
    Value matchingWeight() const {
deba@326
  3392
      Value sum = 0;
deba@326
  3393
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@326
  3394
        if ((*_matching)[n] != INVALID) {
deba@326
  3395
          sum += _weight[(*_matching)[n]];
deba@326
  3396
        }
deba@326
  3397
      }
deba@868
  3398
      return sum / 2;
deba@326
  3399
    }
deba@326
  3400
kpeter@590
  3401
    /// \brief Return \c true if the given edge is in the matching.
deba@326
  3402
    ///
deba@868
  3403
    /// This function returns \c true if the given edge is in the found
kpeter@590
  3404
    /// matching.
kpeter@590
  3405
    ///
kpeter@590
  3406
    /// \pre Either run() or start() must be called before using this function.
deba@327
  3407
    bool matching(const Edge& edge) const {
deba@327
  3408
      return static_cast<const Edge&>((*_matching)[_graph.u(edge)]) == edge;
deba@326
  3409
    }
deba@326
  3410
kpeter@590
  3411
    /// \brief Return the matching arc (or edge) incident to the given node.
deba@326
  3412
    ///
kpeter@590
  3413
    /// This function returns the matching arc (or edge) incident to the
deba@868
  3414
    /// given node in the found matching or \c INVALID if the node is
kpeter@590
  3415
    /// not covered by the matching.
kpeter@590
  3416
    ///
kpeter@590
  3417
    /// \pre Either run() or start() must be called before using this function.
deba@326
  3418
    Arc matching(const Node& node) const {
deba@326
  3419
      return (*_matching)[node];
deba@326
  3420
    }
deba@326
  3421
kpeter@593
  3422
    /// \brief Return a const reference to the matching map.
kpeter@593
  3423
    ///
kpeter@593
  3424
    /// This function returns a const reference to a node map that stores
kpeter@593
  3425
    /// the matching arc (or edge) incident to each node.
kpeter@593
  3426
    const MatchingMap& matchingMap() const {
kpeter@593
  3427
      return *_matching;
kpeter@593
  3428
    }
kpeter@593
  3429
kpeter@590
  3430
    /// \brief Return the mate of the given node.
deba@326
  3431
    ///
deba@868
  3432
    /// This function returns the mate of the given node in the found
kpeter@590
  3433
    /// matching or \c INVALID if the node is not covered by the matching.
kpeter@590
  3434
    ///
kpeter@590
  3435
    /// \pre Either run() or start() must be called before using this function.
deba@326
  3436
    Node mate(const Node& node) const {
deba@326
  3437
      return _graph.target((*_matching)[node]);
deba@326
  3438
    }
deba@326
  3439
deba@326
  3440
    /// @}
deba@326
  3441
kpeter@590
  3442
    /// \name Dual Solution
kpeter@590
  3443
    /// Functions to get the dual solution.\n
kpeter@590
  3444
    /// Either \ref run() or \ref start() function should be called before
kpeter@590
  3445
    /// using them.
deba@326
  3446
deba@326
  3447
    /// @{
deba@326
  3448
kpeter@590
  3449
    /// \brief Return the value of the dual solution.
deba@326
  3450
    ///
deba@868
  3451
    /// This function returns the value of the dual solution.
deba@868
  3452
    /// It should be equal to the primal value scaled by \ref dualScale
kpeter@590
  3453
    /// "dual scale".
kpeter@590
  3454
    ///
kpeter@590
  3455
    /// \pre Either run() or start() must be called before using this function.
deba@326
  3456
    Value dualValue() const {
deba@326
  3457
      Value sum = 0;
deba@326
  3458
      for (NodeIt n(_graph); n != INVALID; ++n) {
deba@326
  3459
        sum += nodeValue(n);
deba@326
  3460
      }
deba@326
  3461
      for (int i = 0; i < blossomNum(); ++i) {
deba@326
  3462
        sum += blossomValue(i) * (blossomSize(i) / 2);
deba@326
  3463
      }
deba@326
  3464
      return sum;
deba@326
  3465
    }
deba@326
  3466
kpeter@590
  3467
    /// \brief Return the dual value (potential) of the given node.
deba@326
  3468
    ///
kpeter@590
  3469
    /// This function returns the dual value (potential) of the given node.
kpeter@590
  3470
    ///
kpeter@590
  3471
    /// \pre Either run() or start() must be called before using this function.
deba@326
  3472
    Value nodeValue(const Node& n) const {
deba@326
  3473
      return (*_node_potential)[n];
deba@326
  3474
    }
deba@326
  3475
kpeter@590
  3476
    /// \brief Return the number of the blossoms in the basis.
deba@326
  3477
    ///
kpeter@590
  3478
    /// This function returns the number of the blossoms in the basis.
kpeter@590
  3479
    ///
kpeter@590
  3480
    /// \pre Either run() or start() must be called before using this function.
deba@326
  3481
    /// \see BlossomIt
deba@326
  3482
    int blossomNum() const {
deba@326
  3483
      return _blossom_potential.size();
deba@326
  3484
    }
deba@326
  3485
kpeter@590
  3486
    /// \brief Return the number of the nodes in the given blossom.
deba@326
  3487
    ///
kpeter@590
  3488
    /// This function returns the number of the nodes in the given blossom.
kpeter@590
  3489
    ///
kpeter@590
  3490
    /// \pre Either run() or start() must be called before using this function.
kpeter@590
  3491
    /// \see BlossomIt
deba@326
  3492
    int blossomSize(int k) const {
deba@326
  3493
      return _blossom_potential[k].end - _blossom_potential[k].begin;
deba@326
  3494
    }
deba@326
  3495
kpeter@590
  3496
    /// \brief Return the dual value (ptential) of the given blossom.
deba@326
  3497
    ///
kpeter@590
  3498
    /// This function returns the dual value (ptential) of the given blossom.
kpeter@590
  3499
    ///
kpeter@590
  3500
    /// \pre Either run() or start() must be called before using this function.
deba@326
  3501
    Value blossomValue(int k) const {
deba@326
  3502
      return _blossom_potential[k].value;
deba@326
  3503
    }
deba@326
  3504
kpeter@590
  3505
    /// \brief Iterator for obtaining the nodes of a blossom.
deba@326
  3506
    ///
deba@868
  3507
    /// This class provides an iterator for obtaining the nodes of the
kpeter@590
  3508
    /// given blossom. It lists a subset of the nodes.
deba@868
  3509
    /// Before using this iterator, you must allocate a
kpeter@590
  3510
    /// MaxWeightedPerfectMatching class and execute it.
deba@326
  3511
    class BlossomIt {
deba@326
  3512
    public:
deba@326
  3513
deba@326
  3514
      /// \brief Constructor.
deba@326
  3515
      ///
kpeter@590
  3516
      /// Constructor to get the nodes of the given variable.
kpeter@590
  3517
      ///
deba@868
  3518
      /// \pre Either \ref MaxWeightedPerfectMatching::run() "algorithm.run()"
deba@868
  3519
      /// or \ref MaxWeightedPerfectMatching::start() "algorithm.start()"
kpeter@590
  3520
      /// must be called before initializing this iterator.
deba@326
  3521
      BlossomIt(const MaxWeightedPerfectMatching& algorithm, int variable)
deba@326
  3522
        : _algorithm(&algorithm)
deba@326
  3523
      {
deba@326
  3524
        _index = _algorithm->_blossom_potential[variable].begin;
deba@326
  3525
        _last = _algorithm->_blossom_potential[variable].end;
deba@326
  3526
      }
deba@326
  3527
kpeter@590
  3528
      /// \brief Conversion to \c Node.
deba@326
  3529
      ///
kpeter@590
  3530
      /// Conversion to \c Node.
deba@326
  3531
      operator Node() const {
deba@327
  3532
        return _algorithm->_blossom_node_list[_index];
deba@326
  3533
      }
deba@326
  3534
deba@326
  3535
      /// \brief Increment operator.
deba@326
  3536
      ///
deba@326
  3537
      /// Increment operator.
deba@326
  3538
      BlossomIt& operator++() {
deba@326
  3539
        ++_index;
deba@326
  3540
        return *this;
deba@326
  3541
      }
deba@326
  3542
deba@327
  3543
      /// \brief Validity checking
deba@327
  3544
      ///
kpeter@590
  3545
      /// This function checks whether the iterator is invalid.
deba@327
  3546
      bool operator==(Invalid) const { return _index == _last; }
deba@327
  3547
deba@327
  3548
      /// \brief Validity checking
deba@327
  3549
      ///
kpeter@590
  3550
      /// This function checks whether the iterator is valid.
deba@327
  3551
      bool operator!=(Invalid) const { return _index != _last; }
deba@326
  3552
deba@326
  3553
    private:
deba@326
  3554
      const MaxWeightedPerfectMatching* _algorithm;
deba@326
  3555
      int _last;
deba@326
  3556
      int _index;
deba@326
  3557
    };
deba@326
  3558
deba@326
  3559
    /// @}
deba@326
  3560
deba@326
  3561
  };
deba@326
  3562
deba@326
  3563
} //END OF NAMESPACE LEMON
deba@326
  3564
deba@868
  3565
#endif //LEMON_MATCHING_H