lemon/min_cost_arborescence.h
author Peter Kovacs <kpeter@inf.elte.hu>
Tue, 02 Mar 2010 10:03:07 +0100
changeset 860 930ddeafdb20
parent 713 4ac30454f1c1
child 877 141f9c0db4a3
permissions -rw-r--r--
Add tolerance() functions for HaoOrlin (#306)
deba@490
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
deba@490
     2
 *
deba@490
     3
 * This file is a part of LEMON, a generic C++ optimization library.
deba@490
     4
 *
deba@490
     5
 * Copyright (C) 2003-2008
deba@490
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
deba@490
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
deba@490
     8
 *
deba@490
     9
 * Permission to use, modify and distribute this software is granted
deba@490
    10
 * provided that this copyright notice appears in all copies. For
deba@490
    11
 * precise terms see the accompanying LICENSE file.
deba@490
    12
 *
deba@490
    13
 * This software is provided "AS IS" with no warranty of any kind,
deba@490
    14
 * express or implied, and with no claim as to its suitability for any
deba@490
    15
 * purpose.
deba@490
    16
 *
deba@490
    17
 */
deba@490
    18
deba@490
    19
#ifndef LEMON_MIN_COST_ARBORESCENCE_H
deba@490
    20
#define LEMON_MIN_COST_ARBORESCENCE_H
deba@490
    21
deba@490
    22
///\ingroup spantree
deba@490
    23
///\file
deba@490
    24
///\brief Minimum Cost Arborescence algorithm.
deba@490
    25
deba@490
    26
#include <vector>
deba@490
    27
deba@490
    28
#include <lemon/list_graph.h>
deba@490
    29
#include <lemon/bin_heap.h>
deba@490
    30
#include <lemon/assert.h>
deba@490
    31
deba@490
    32
namespace lemon {
deba@490
    33
deba@490
    34
deba@490
    35
  /// \brief Default traits class for MinCostArborescence class.
deba@490
    36
  ///
deba@490
    37
  /// Default traits class for MinCostArborescence class.
kpeter@559
    38
  /// \param GR Digraph type.
kpeter@625
    39
  /// \param CM Type of the cost map.
kpeter@559
    40
  template <class GR, class CM>
deba@490
    41
  struct MinCostArborescenceDefaultTraits{
deba@490
    42
deba@490
    43
    /// \brief The digraph type the algorithm runs on.
kpeter@559
    44
    typedef GR Digraph;
deba@490
    45
deba@490
    46
    /// \brief The type of the map that stores the arc costs.
deba@490
    47
    ///
deba@490
    48
    /// The type of the map that stores the arc costs.
kpeter@625
    49
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
kpeter@559
    50
    typedef CM CostMap;
deba@490
    51
deba@490
    52
    /// \brief The value type of the costs.
deba@490
    53
    ///
deba@490
    54
    /// The value type of the costs.
deba@490
    55
    typedef typename CostMap::Value Value;
deba@490
    56
deba@490
    57
    /// \brief The type of the map that stores which arcs are in the
deba@490
    58
    /// arborescence.
deba@490
    59
    ///
deba@490
    60
    /// The type of the map that stores which arcs are in the
kpeter@625
    61
    /// arborescence.  It must conform to the \ref concepts::WriteMap
kpeter@625
    62
    /// "WriteMap" concept, and its value type must be \c bool
kpeter@625
    63
    /// (or convertible). Initially it will be set to \c false on each
kpeter@625
    64
    /// arc, then it will be set on each arborescence arc once.
deba@490
    65
    typedef typename Digraph::template ArcMap<bool> ArborescenceMap;
deba@490
    66
kpeter@559
    67
    /// \brief Instantiates a \c ArborescenceMap.
deba@490
    68
    ///
kpeter@559
    69
    /// This function instantiates a \c ArborescenceMap.
kpeter@625
    70
    /// \param digraph The digraph to which we would like to calculate
kpeter@625
    71
    /// the \c ArborescenceMap.
deba@490
    72
    static ArborescenceMap *createArborescenceMap(const Digraph &digraph){
deba@490
    73
      return new ArborescenceMap(digraph);
deba@490
    74
    }
deba@490
    75
kpeter@559
    76
    /// \brief The type of the \c PredMap
deba@490
    77
    ///
kpeter@625
    78
    /// The type of the \c PredMap. It must confrom to the
kpeter@625
    79
    /// \ref concepts::WriteMap "WriteMap" concept, and its value type
kpeter@625
    80
    /// must be the \c Arc type of the digraph.
deba@490
    81
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
deba@490
    82
kpeter@559
    83
    /// \brief Instantiates a \c PredMap.
deba@490
    84
    ///
kpeter@559
    85
    /// This function instantiates a \c PredMap.
kpeter@559
    86
    /// \param digraph The digraph to which we would like to define the
kpeter@559
    87
    /// \c PredMap.
deba@490
    88
    static PredMap *createPredMap(const Digraph &digraph){
deba@490
    89
      return new PredMap(digraph);
deba@490
    90
    }
deba@490
    91
deba@490
    92
  };
deba@490
    93
deba@490
    94
  /// \ingroup spantree
deba@490
    95
  ///
kpeter@584
    96
  /// \brief Minimum Cost Arborescence algorithm class.
deba@490
    97
  ///
kpeter@625
    98
  /// This class provides an efficient implementation of the
kpeter@584
    99
  /// Minimum Cost Arborescence algorithm. The arborescence is a tree
deba@490
   100
  /// which is directed from a given source node of the digraph. One or
kpeter@625
   101
  /// more sources should be given to the algorithm and it will calculate
kpeter@625
   102
  /// the minimum cost subgraph that is the union of arborescences with the
deba@490
   103
  /// given sources and spans all the nodes which are reachable from the
kpeter@559
   104
  /// sources. The time complexity of the algorithm is O(n<sup>2</sup>+e).
deba@490
   105
  ///
kpeter@625
   106
  /// The algorithm also provides an optimal dual solution, therefore
deba@490
   107
  /// the optimality of the solution can be checked.
deba@490
   108
  ///
kpeter@625
   109
  /// \param GR The digraph type the algorithm runs on.
kpeter@625
   110
  /// \param CM A read-only arc map storing the costs of the
deba@490
   111
  /// arcs. It is read once for each arc, so the map may involve in
kpeter@625
   112
  /// relatively time consuming process to compute the arc costs if
deba@490
   113
  /// it is necessary. The default map type is \ref
deba@490
   114
  /// concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
kpeter@825
   115
  /// \tparam TR The traits class that defines various types used by the
kpeter@825
   116
  /// algorithm. By default, it is \ref MinCostArborescenceDefaultTraits
kpeter@625
   117
  /// "MinCostArborescenceDefaultTraits<GR, CM>".
kpeter@825
   118
  /// In most cases, this parameter should not be set directly,
kpeter@825
   119
  /// consider to use the named template parameters instead.
deba@490
   120
#ifndef DOXYGEN
kpeter@625
   121
  template <typename GR,
kpeter@559
   122
            typename CM = typename GR::template ArcMap<int>,
kpeter@559
   123
            typename TR =
kpeter@559
   124
              MinCostArborescenceDefaultTraits<GR, CM> >
deba@490
   125
#else
kpeter@825
   126
  template <typename GR, typename CM, typename TR>
deba@490
   127
#endif
deba@490
   128
  class MinCostArborescence {
deba@490
   129
  public:
deba@490
   130
kpeter@625
   131
    /// \brief The \ref MinCostArborescenceDefaultTraits "traits class" 
kpeter@625
   132
    /// of the algorithm. 
kpeter@559
   133
    typedef TR Traits;
deba@490
   134
    /// The type of the underlying digraph.
deba@490
   135
    typedef typename Traits::Digraph Digraph;
deba@490
   136
    /// The type of the map that stores the arc costs.
deba@490
   137
    typedef typename Traits::CostMap CostMap;
deba@490
   138
    ///The type of the costs of the arcs.
deba@490
   139
    typedef typename Traits::Value Value;
deba@490
   140
    ///The type of the predecessor map.
deba@490
   141
    typedef typename Traits::PredMap PredMap;
deba@490
   142
    ///The type of the map that stores which arcs are in the arborescence.
deba@490
   143
    typedef typename Traits::ArborescenceMap ArborescenceMap;
deba@490
   144
deba@490
   145
    typedef MinCostArborescence Create;
deba@490
   146
deba@490
   147
  private:
deba@490
   148
deba@490
   149
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
deba@490
   150
deba@490
   151
    struct CostArc {
deba@490
   152
deba@490
   153
      Arc arc;
deba@490
   154
      Value value;
deba@490
   155
deba@490
   156
      CostArc() {}
deba@490
   157
      CostArc(Arc _arc, Value _value) : arc(_arc), value(_value) {}
deba@490
   158
deba@490
   159
    };
deba@490
   160
deba@490
   161
    const Digraph *_digraph;
deba@490
   162
    const CostMap *_cost;
deba@490
   163
deba@490
   164
    PredMap *_pred;
deba@490
   165
    bool local_pred;
deba@490
   166
deba@490
   167
    ArborescenceMap *_arborescence;
deba@490
   168
    bool local_arborescence;
deba@490
   169
deba@490
   170
    typedef typename Digraph::template ArcMap<int> ArcOrder;
deba@490
   171
    ArcOrder *_arc_order;
deba@490
   172
deba@490
   173
    typedef typename Digraph::template NodeMap<int> NodeOrder;
deba@490
   174
    NodeOrder *_node_order;
deba@490
   175
deba@490
   176
    typedef typename Digraph::template NodeMap<CostArc> CostArcMap;
deba@490
   177
    CostArcMap *_cost_arcs;
deba@490
   178
deba@490
   179
    struct StackLevel {
deba@490
   180
deba@490
   181
      std::vector<CostArc> arcs;
deba@490
   182
      int node_level;
deba@490
   183
deba@490
   184
    };
deba@490
   185
deba@490
   186
    std::vector<StackLevel> level_stack;
deba@490
   187
    std::vector<Node> queue;
deba@490
   188
deba@490
   189
    typedef std::vector<typename Digraph::Node> DualNodeList;
deba@490
   190
deba@490
   191
    DualNodeList _dual_node_list;
deba@490
   192
deba@490
   193
    struct DualVariable {
deba@490
   194
      int begin, end;
deba@490
   195
      Value value;
deba@490
   196
deba@490
   197
      DualVariable(int _begin, int _end, Value _value)
deba@490
   198
        : begin(_begin), end(_end), value(_value) {}
deba@490
   199
deba@490
   200
    };
deba@490
   201
deba@490
   202
    typedef std::vector<DualVariable> DualVariables;
deba@490
   203
deba@490
   204
    DualVariables _dual_variables;
deba@490
   205
deba@490
   206
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
deba@490
   207
deba@490
   208
    HeapCrossRef *_heap_cross_ref;
deba@490
   209
deba@490
   210
    typedef BinHeap<int, HeapCrossRef> Heap;
deba@490
   211
deba@490
   212
    Heap *_heap;
deba@490
   213
deba@490
   214
  protected:
deba@490
   215
deba@490
   216
    MinCostArborescence() {}
deba@490
   217
deba@490
   218
  private:
deba@490
   219
deba@490
   220
    void createStructures() {
deba@490
   221
      if (!_pred) {
deba@490
   222
        local_pred = true;
deba@490
   223
        _pred = Traits::createPredMap(*_digraph);
deba@490
   224
      }
deba@490
   225
      if (!_arborescence) {
deba@490
   226
        local_arborescence = true;
deba@490
   227
        _arborescence = Traits::createArborescenceMap(*_digraph);
deba@490
   228
      }
deba@490
   229
      if (!_arc_order) {
deba@490
   230
        _arc_order = new ArcOrder(*_digraph);
deba@490
   231
      }
deba@490
   232
      if (!_node_order) {
deba@490
   233
        _node_order = new NodeOrder(*_digraph);
deba@490
   234
      }
deba@490
   235
      if (!_cost_arcs) {
deba@490
   236
        _cost_arcs = new CostArcMap(*_digraph);
deba@490
   237
      }
deba@490
   238
      if (!_heap_cross_ref) {
deba@490
   239
        _heap_cross_ref = new HeapCrossRef(*_digraph, -1);
deba@490
   240
      }
deba@490
   241
      if (!_heap) {
deba@490
   242
        _heap = new Heap(*_heap_cross_ref);
deba@490
   243
      }
deba@490
   244
    }
deba@490
   245
deba@490
   246
    void destroyStructures() {
deba@490
   247
      if (local_arborescence) {
deba@490
   248
        delete _arborescence;
deba@490
   249
      }
deba@490
   250
      if (local_pred) {
deba@490
   251
        delete _pred;
deba@490
   252
      }
deba@490
   253
      if (_arc_order) {
deba@490
   254
        delete _arc_order;
deba@490
   255
      }
deba@490
   256
      if (_node_order) {
deba@490
   257
        delete _node_order;
deba@490
   258
      }
deba@490
   259
      if (_cost_arcs) {
deba@490
   260
        delete _cost_arcs;
deba@490
   261
      }
deba@490
   262
      if (_heap) {
deba@490
   263
        delete _heap;
deba@490
   264
      }
deba@490
   265
      if (_heap_cross_ref) {
deba@490
   266
        delete _heap_cross_ref;
deba@490
   267
      }
deba@490
   268
    }
deba@490
   269
deba@490
   270
    Arc prepare(Node node) {
deba@490
   271
      std::vector<Node> nodes;
deba@490
   272
      (*_node_order)[node] = _dual_node_list.size();
deba@490
   273
      StackLevel level;
deba@490
   274
      level.node_level = _dual_node_list.size();
deba@490
   275
      _dual_node_list.push_back(node);
deba@490
   276
      for (InArcIt it(*_digraph, node); it != INVALID; ++it) {
deba@490
   277
        Arc arc = it;
deba@490
   278
        Node source = _digraph->source(arc);
deba@490
   279
        Value value = (*_cost)[it];
deba@490
   280
        if (source == node || (*_node_order)[source] == -3) continue;
deba@490
   281
        if ((*_cost_arcs)[source].arc == INVALID) {
deba@490
   282
          (*_cost_arcs)[source].arc = arc;
deba@490
   283
          (*_cost_arcs)[source].value = value;
deba@490
   284
          nodes.push_back(source);
deba@490
   285
        } else {
deba@490
   286
          if ((*_cost_arcs)[source].value > value) {
deba@490
   287
            (*_cost_arcs)[source].arc = arc;
deba@490
   288
            (*_cost_arcs)[source].value = value;
deba@490
   289
          }
deba@490
   290
        }
deba@490
   291
      }
deba@490
   292
      CostArc minimum = (*_cost_arcs)[nodes[0]];
deba@490
   293
      for (int i = 1; i < int(nodes.size()); ++i) {
deba@490
   294
        if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
deba@490
   295
          minimum = (*_cost_arcs)[nodes[i]];
deba@490
   296
        }
deba@490
   297
      }
kpeter@581
   298
      (*_arc_order)[minimum.arc] = _dual_variables.size();
deba@490
   299
      DualVariable var(_dual_node_list.size() - 1,
deba@490
   300
                       _dual_node_list.size(), minimum.value);
deba@490
   301
      _dual_variables.push_back(var);
deba@490
   302
      for (int i = 0; i < int(nodes.size()); ++i) {
deba@490
   303
        (*_cost_arcs)[nodes[i]].value -= minimum.value;
deba@490
   304
        level.arcs.push_back((*_cost_arcs)[nodes[i]]);
deba@490
   305
        (*_cost_arcs)[nodes[i]].arc = INVALID;
deba@490
   306
      }
deba@490
   307
      level_stack.push_back(level);
deba@490
   308
      return minimum.arc;
deba@490
   309
    }
deba@490
   310
deba@490
   311
    Arc contract(Node node) {
deba@490
   312
      int node_bottom = bottom(node);
deba@490
   313
      std::vector<Node> nodes;
deba@490
   314
      while (!level_stack.empty() &&
deba@490
   315
             level_stack.back().node_level >= node_bottom) {
deba@490
   316
        for (int i = 0; i < int(level_stack.back().arcs.size()); ++i) {
deba@490
   317
          Arc arc = level_stack.back().arcs[i].arc;
deba@490
   318
          Node source = _digraph->source(arc);
deba@490
   319
          Value value = level_stack.back().arcs[i].value;
deba@490
   320
          if ((*_node_order)[source] >= node_bottom) continue;
deba@490
   321
          if ((*_cost_arcs)[source].arc == INVALID) {
deba@490
   322
            (*_cost_arcs)[source].arc = arc;
deba@490
   323
            (*_cost_arcs)[source].value = value;
deba@490
   324
            nodes.push_back(source);
deba@490
   325
          } else {
deba@490
   326
            if ((*_cost_arcs)[source].value > value) {
deba@490
   327
              (*_cost_arcs)[source].arc = arc;
deba@490
   328
              (*_cost_arcs)[source].value = value;
deba@490
   329
            }
deba@490
   330
          }
deba@490
   331
        }
deba@490
   332
        level_stack.pop_back();
deba@490
   333
      }
deba@490
   334
      CostArc minimum = (*_cost_arcs)[nodes[0]];
deba@490
   335
      for (int i = 1; i < int(nodes.size()); ++i) {
deba@490
   336
        if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
deba@490
   337
          minimum = (*_cost_arcs)[nodes[i]];
deba@490
   338
        }
deba@490
   339
      }
kpeter@581
   340
      (*_arc_order)[minimum.arc] = _dual_variables.size();
deba@490
   341
      DualVariable var(node_bottom, _dual_node_list.size(), minimum.value);
deba@490
   342
      _dual_variables.push_back(var);
deba@490
   343
      StackLevel level;
deba@490
   344
      level.node_level = node_bottom;
deba@490
   345
      for (int i = 0; i < int(nodes.size()); ++i) {
deba@490
   346
        (*_cost_arcs)[nodes[i]].value -= minimum.value;
deba@490
   347
        level.arcs.push_back((*_cost_arcs)[nodes[i]]);
deba@490
   348
        (*_cost_arcs)[nodes[i]].arc = INVALID;
deba@490
   349
      }
deba@490
   350
      level_stack.push_back(level);
deba@490
   351
      return minimum.arc;
deba@490
   352
    }
deba@490
   353
deba@490
   354
    int bottom(Node node) {
deba@490
   355
      int k = level_stack.size() - 1;
deba@490
   356
      while (level_stack[k].node_level > (*_node_order)[node]) {
deba@490
   357
        --k;
deba@490
   358
      }
deba@490
   359
      return level_stack[k].node_level;
deba@490
   360
    }
deba@490
   361
deba@490
   362
    void finalize(Arc arc) {
deba@490
   363
      Node node = _digraph->target(arc);
deba@490
   364
      _heap->push(node, (*_arc_order)[arc]);
deba@490
   365
      _pred->set(node, arc);
deba@490
   366
      while (!_heap->empty()) {
deba@490
   367
        Node source = _heap->top();
deba@490
   368
        _heap->pop();
kpeter@581
   369
        (*_node_order)[source] = -1;
deba@490
   370
        for (OutArcIt it(*_digraph, source); it != INVALID; ++it) {
deba@490
   371
          if ((*_arc_order)[it] < 0) continue;
deba@490
   372
          Node target = _digraph->target(it);
deba@490
   373
          switch(_heap->state(target)) {
deba@490
   374
          case Heap::PRE_HEAP:
deba@490
   375
            _heap->push(target, (*_arc_order)[it]);
deba@490
   376
            _pred->set(target, it);
deba@490
   377
            break;
deba@490
   378
          case Heap::IN_HEAP:
deba@490
   379
            if ((*_arc_order)[it] < (*_heap)[target]) {
deba@490
   380
              _heap->decrease(target, (*_arc_order)[it]);
deba@490
   381
              _pred->set(target, it);
deba@490
   382
            }
deba@490
   383
            break;
deba@490
   384
          case Heap::POST_HEAP:
deba@490
   385
            break;
deba@490
   386
          }
deba@490
   387
        }
deba@490
   388
        _arborescence->set((*_pred)[source], true);
deba@490
   389
      }
deba@490
   390
    }
deba@490
   391
deba@490
   392
deba@490
   393
  public:
deba@490
   394
kpeter@584
   395
    /// \name Named Template Parameters
deba@490
   396
deba@490
   397
    /// @{
deba@490
   398
deba@490
   399
    template <class T>
kpeter@625
   400
    struct SetArborescenceMapTraits : public Traits {
deba@490
   401
      typedef T ArborescenceMap;
deba@490
   402
      static ArborescenceMap *createArborescenceMap(const Digraph &)
deba@490
   403
      {
deba@490
   404
        LEMON_ASSERT(false, "ArborescenceMap is not initialized");
deba@490
   405
        return 0; // ignore warnings
deba@490
   406
      }
deba@490
   407
    };
deba@490
   408
deba@490
   409
    /// \brief \ref named-templ-param "Named parameter" for
kpeter@625
   410
    /// setting \c ArborescenceMap type
deba@490
   411
    ///
deba@490
   412
    /// \ref named-templ-param "Named parameter" for setting
kpeter@625
   413
    /// \c ArborescenceMap type.
kpeter@625
   414
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept,
kpeter@625
   415
    /// and its value type must be \c bool (or convertible).
kpeter@625
   416
    /// Initially it will be set to \c false on each arc,
kpeter@625
   417
    /// then it will be set on each arborescence arc once.
deba@490
   418
    template <class T>
kpeter@625
   419
    struct SetArborescenceMap
deba@490
   420
      : public MinCostArborescence<Digraph, CostMap,
kpeter@625
   421
                                   SetArborescenceMapTraits<T> > {
deba@490
   422
    };
deba@490
   423
deba@490
   424
    template <class T>
kpeter@625
   425
    struct SetPredMapTraits : public Traits {
deba@490
   426
      typedef T PredMap;
deba@490
   427
      static PredMap *createPredMap(const Digraph &)
deba@490
   428
      {
deba@490
   429
        LEMON_ASSERT(false, "PredMap is not initialized");
kpeter@625
   430
        return 0; // ignore warnings
deba@490
   431
      }
deba@490
   432
    };
deba@490
   433
deba@490
   434
    /// \brief \ref named-templ-param "Named parameter" for
kpeter@625
   435
    /// setting \c PredMap type
deba@490
   436
    ///
deba@490
   437
    /// \ref named-templ-param "Named parameter" for setting
kpeter@625
   438
    /// \c PredMap type.
kpeter@625
   439
    /// It must meet the \ref concepts::WriteMap "WriteMap" concept, 
kpeter@625
   440
    /// and its value type must be the \c Arc type of the digraph.
deba@490
   441
    template <class T>
kpeter@625
   442
    struct SetPredMap
kpeter@625
   443
      : public MinCostArborescence<Digraph, CostMap, SetPredMapTraits<T> > {
deba@490
   444
    };
deba@490
   445
deba@490
   446
    /// @}
deba@490
   447
deba@490
   448
    /// \brief Constructor.
deba@490
   449
    ///
kpeter@559
   450
    /// \param digraph The digraph the algorithm will run on.
kpeter@559
   451
    /// \param cost The cost map used by the algorithm.
deba@490
   452
    MinCostArborescence(const Digraph& digraph, const CostMap& cost)
deba@490
   453
      : _digraph(&digraph), _cost(&cost), _pred(0), local_pred(false),
deba@490
   454
        _arborescence(0), local_arborescence(false),
deba@490
   455
        _arc_order(0), _node_order(0), _cost_arcs(0),
deba@490
   456
        _heap_cross_ref(0), _heap(0) {}
deba@490
   457
deba@490
   458
    /// \brief Destructor.
deba@490
   459
    ~MinCostArborescence() {
deba@490
   460
      destroyStructures();
deba@490
   461
    }
deba@490
   462
deba@490
   463
    /// \brief Sets the arborescence map.
deba@490
   464
    ///
deba@490
   465
    /// Sets the arborescence map.
kpeter@559
   466
    /// \return <tt>(*this)</tt>
deba@490
   467
    MinCostArborescence& arborescenceMap(ArborescenceMap& m) {
deba@490
   468
      if (local_arborescence) {
deba@490
   469
        delete _arborescence;
deba@490
   470
      }
deba@490
   471
      local_arborescence = false;
deba@490
   472
      _arborescence = &m;
deba@490
   473
      return *this;
deba@490
   474
    }
deba@490
   475
kpeter@625
   476
    /// \brief Sets the predecessor map.
deba@490
   477
    ///
kpeter@625
   478
    /// Sets the predecessor map.
kpeter@559
   479
    /// \return <tt>(*this)</tt>
deba@490
   480
    MinCostArborescence& predMap(PredMap& m) {
deba@490
   481
      if (local_pred) {
deba@490
   482
        delete _pred;
deba@490
   483
      }
deba@490
   484
      local_pred = false;
deba@490
   485
      _pred = &m;
deba@490
   486
      return *this;
deba@490
   487
    }
deba@490
   488
kpeter@584
   489
    /// \name Execution Control
deba@490
   490
    /// The simplest way to execute the algorithm is to use
deba@490
   491
    /// one of the member functions called \c run(...). \n
kpeter@713
   492
    /// If you need better control on the execution,
kpeter@713
   493
    /// you have to call \ref init() first, then you can add several
deba@490
   494
    /// source nodes with \ref addSource().
deba@490
   495
    /// Finally \ref start() will perform the arborescence
deba@490
   496
    /// computation.
deba@490
   497
deba@490
   498
    ///@{
deba@490
   499
deba@490
   500
    /// \brief Initializes the internal data structures.
deba@490
   501
    ///
deba@490
   502
    /// Initializes the internal data structures.
deba@490
   503
    ///
deba@490
   504
    void init() {
deba@490
   505
      createStructures();
deba@490
   506
      _heap->clear();
deba@490
   507
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
deba@490
   508
        (*_cost_arcs)[it].arc = INVALID;
kpeter@581
   509
        (*_node_order)[it] = -3;
kpeter@581
   510
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
deba@490
   511
        _pred->set(it, INVALID);
deba@490
   512
      }
deba@490
   513
      for (ArcIt it(*_digraph); it != INVALID; ++it) {
deba@490
   514
        _arborescence->set(it, false);
kpeter@581
   515
        (*_arc_order)[it] = -1;
deba@490
   516
      }
deba@490
   517
      _dual_node_list.clear();
deba@490
   518
      _dual_variables.clear();
deba@490
   519
    }
deba@490
   520
deba@490
   521
    /// \brief Adds a new source node.
deba@490
   522
    ///
deba@490
   523
    /// Adds a new source node to the algorithm.
deba@490
   524
    void addSource(Node source) {
deba@490
   525
      std::vector<Node> nodes;
deba@490
   526
      nodes.push_back(source);
deba@490
   527
      while (!nodes.empty()) {
deba@490
   528
        Node node = nodes.back();
deba@490
   529
        nodes.pop_back();
deba@490
   530
        for (OutArcIt it(*_digraph, node); it != INVALID; ++it) {
deba@490
   531
          Node target = _digraph->target(it);
deba@490
   532
          if ((*_node_order)[target] == -3) {
deba@490
   533
            (*_node_order)[target] = -2;
deba@490
   534
            nodes.push_back(target);
deba@490
   535
            queue.push_back(target);
deba@490
   536
          }
deba@490
   537
        }
deba@490
   538
      }
deba@490
   539
      (*_node_order)[source] = -1;
deba@490
   540
    }
deba@490
   541
deba@490
   542
    /// \brief Processes the next node in the priority queue.
deba@490
   543
    ///
deba@490
   544
    /// Processes the next node in the priority queue.
deba@490
   545
    ///
deba@490
   546
    /// \return The processed node.
deba@490
   547
    ///
kpeter@625
   548
    /// \warning The queue must not be empty.
deba@490
   549
    Node processNextNode() {
deba@490
   550
      Node node = queue.back();
deba@490
   551
      queue.pop_back();
deba@490
   552
      if ((*_node_order)[node] == -2) {
deba@490
   553
        Arc arc = prepare(node);
deba@490
   554
        Node source = _digraph->source(arc);
deba@490
   555
        while ((*_node_order)[source] != -1) {
deba@490
   556
          if ((*_node_order)[source] >= 0) {
deba@490
   557
            arc = contract(source);
deba@490
   558
          } else {
deba@490
   559
            arc = prepare(source);
deba@490
   560
          }
deba@490
   561
          source = _digraph->source(arc);
deba@490
   562
        }
deba@490
   563
        finalize(arc);
deba@490
   564
        level_stack.clear();
deba@490
   565
      }
deba@490
   566
      return node;
deba@490
   567
    }
deba@490
   568
deba@490
   569
    /// \brief Returns the number of the nodes to be processed.
deba@490
   570
    ///
kpeter@625
   571
    /// Returns the number of the nodes to be processed in the priority
kpeter@625
   572
    /// queue.
deba@490
   573
    int queueSize() const {
deba@490
   574
      return queue.size();
deba@490
   575
    }
deba@490
   576
deba@490
   577
    /// \brief Returns \c false if there are nodes to be processed.
deba@490
   578
    ///
deba@490
   579
    /// Returns \c false if there are nodes to be processed.
deba@490
   580
    bool emptyQueue() const {
deba@490
   581
      return queue.empty();
deba@490
   582
    }
deba@490
   583
deba@490
   584
    /// \brief Executes the algorithm.
deba@490
   585
    ///
deba@490
   586
    /// Executes the algorithm.
deba@490
   587
    ///
deba@490
   588
    /// \pre init() must be called and at least one node should be added
deba@490
   589
    /// with addSource() before using this function.
deba@490
   590
    ///
deba@490
   591
    ///\note mca.start() is just a shortcut of the following code.
deba@490
   592
    ///\code
deba@490
   593
    ///while (!mca.emptyQueue()) {
deba@490
   594
    ///  mca.processNextNode();
deba@490
   595
    ///}
deba@490
   596
    ///\endcode
deba@490
   597
    void start() {
deba@490
   598
      while (!emptyQueue()) {
deba@490
   599
        processNextNode();
deba@490
   600
      }
deba@490
   601
    }
deba@490
   602
deba@490
   603
    /// \brief Runs %MinCostArborescence algorithm from node \c s.
deba@490
   604
    ///
deba@490
   605
    /// This method runs the %MinCostArborescence algorithm from
deba@490
   606
    /// a root node \c s.
deba@490
   607
    ///
deba@490
   608
    /// \note mca.run(s) is just a shortcut of the following code.
deba@490
   609
    /// \code
deba@490
   610
    /// mca.init();
deba@490
   611
    /// mca.addSource(s);
deba@490
   612
    /// mca.start();
deba@490
   613
    /// \endcode
kpeter@625
   614
    void run(Node s) {
deba@490
   615
      init();
kpeter@625
   616
      addSource(s);
deba@490
   617
      start();
deba@490
   618
    }
deba@490
   619
deba@490
   620
    ///@}
deba@490
   621
kpeter@625
   622
    /// \name Query Functions
kpeter@625
   623
    /// The result of the %MinCostArborescence algorithm can be obtained
kpeter@625
   624
    /// using these functions.\n
kpeter@625
   625
    /// Either run() or start() must be called before using them.
kpeter@625
   626
kpeter@625
   627
    /// @{
kpeter@625
   628
kpeter@625
   629
    /// \brief Returns the cost of the arborescence.
kpeter@625
   630
    ///
kpeter@625
   631
    /// Returns the cost of the arborescence.
kpeter@625
   632
    Value arborescenceCost() const {
kpeter@625
   633
      Value sum = 0;
kpeter@625
   634
      for (ArcIt it(*_digraph); it != INVALID; ++it) {
kpeter@625
   635
        if (arborescence(it)) {
kpeter@625
   636
          sum += (*_cost)[it];
kpeter@625
   637
        }
kpeter@625
   638
      }
kpeter@625
   639
      return sum;
kpeter@625
   640
    }
kpeter@625
   641
kpeter@625
   642
    /// \brief Returns \c true if the arc is in the arborescence.
kpeter@625
   643
    ///
kpeter@625
   644
    /// Returns \c true if the given arc is in the arborescence.
kpeter@625
   645
    /// \param arc An arc of the digraph.
kpeter@625
   646
    /// \pre \ref run() must be called before using this function.
kpeter@625
   647
    bool arborescence(Arc arc) const {
kpeter@625
   648
      return (*_pred)[_digraph->target(arc)] == arc;
kpeter@625
   649
    }
kpeter@625
   650
kpeter@625
   651
    /// \brief Returns a const reference to the arborescence map.
kpeter@625
   652
    ///
kpeter@625
   653
    /// Returns a const reference to the arborescence map.
kpeter@625
   654
    /// \pre \ref run() must be called before using this function.
kpeter@625
   655
    const ArborescenceMap& arborescenceMap() const {
kpeter@625
   656
      return *_arborescence;
kpeter@625
   657
    }
kpeter@625
   658
kpeter@625
   659
    /// \brief Returns the predecessor arc of the given node.
kpeter@625
   660
    ///
kpeter@625
   661
    /// Returns the predecessor arc of the given node.
kpeter@625
   662
    /// \pre \ref run() must be called before using this function.
kpeter@625
   663
    Arc pred(Node node) const {
kpeter@625
   664
      return (*_pred)[node];
kpeter@625
   665
    }
kpeter@625
   666
kpeter@625
   667
    /// \brief Returns a const reference to the pred map.
kpeter@625
   668
    ///
kpeter@625
   669
    /// Returns a const reference to the pred map.
kpeter@625
   670
    /// \pre \ref run() must be called before using this function.
kpeter@625
   671
    const PredMap& predMap() const {
kpeter@625
   672
      return *_pred;
kpeter@625
   673
    }
kpeter@625
   674
kpeter@625
   675
    /// \brief Indicates that a node is reachable from the sources.
kpeter@625
   676
    ///
kpeter@625
   677
    /// Indicates that a node is reachable from the sources.
kpeter@625
   678
    bool reached(Node node) const {
kpeter@625
   679
      return (*_node_order)[node] != -3;
kpeter@625
   680
    }
kpeter@625
   681
kpeter@625
   682
    /// \brief Indicates that a node is processed.
kpeter@625
   683
    ///
kpeter@625
   684
    /// Indicates that a node is processed. The arborescence path exists
kpeter@625
   685
    /// from the source to the given node.
kpeter@625
   686
    bool processed(Node node) const {
kpeter@625
   687
      return (*_node_order)[node] == -1;
kpeter@625
   688
    }
kpeter@625
   689
kpeter@625
   690
    /// \brief Returns the number of the dual variables in basis.
kpeter@625
   691
    ///
kpeter@625
   692
    /// Returns the number of the dual variables in basis.
kpeter@625
   693
    int dualNum() const {
kpeter@625
   694
      return _dual_variables.size();
kpeter@625
   695
    }
kpeter@625
   696
kpeter@625
   697
    /// \brief Returns the value of the dual solution.
kpeter@625
   698
    ///
kpeter@625
   699
    /// Returns the value of the dual solution. It should be
kpeter@625
   700
    /// equal to the arborescence value.
kpeter@625
   701
    Value dualValue() const {
kpeter@625
   702
      Value sum = 0;
kpeter@625
   703
      for (int i = 0; i < int(_dual_variables.size()); ++i) {
kpeter@625
   704
        sum += _dual_variables[i].value;
kpeter@625
   705
      }
kpeter@625
   706
      return sum;
kpeter@625
   707
    }
kpeter@625
   708
kpeter@625
   709
    /// \brief Returns the number of the nodes in the dual variable.
kpeter@625
   710
    ///
kpeter@625
   711
    /// Returns the number of the nodes in the dual variable.
kpeter@625
   712
    int dualSize(int k) const {
kpeter@625
   713
      return _dual_variables[k].end - _dual_variables[k].begin;
kpeter@625
   714
    }
kpeter@625
   715
kpeter@625
   716
    /// \brief Returns the value of the dual variable.
kpeter@625
   717
    ///
kpeter@625
   718
    /// Returns the the value of the dual variable.
kpeter@625
   719
    Value dualValue(int k) const {
kpeter@625
   720
      return _dual_variables[k].value;
kpeter@625
   721
    }
kpeter@625
   722
kpeter@625
   723
    /// \brief LEMON iterator for getting a dual variable.
kpeter@625
   724
    ///
kpeter@625
   725
    /// This class provides a common style LEMON iterator for getting a
kpeter@625
   726
    /// dual variable of \ref MinCostArborescence algorithm.
kpeter@625
   727
    /// It iterates over a subset of the nodes.
kpeter@625
   728
    class DualIt {
kpeter@625
   729
    public:
kpeter@625
   730
kpeter@625
   731
      /// \brief Constructor.
kpeter@625
   732
      ///
kpeter@625
   733
      /// Constructor for getting the nodeset of the dual variable
kpeter@625
   734
      /// of \ref MinCostArborescence algorithm.
kpeter@625
   735
      DualIt(const MinCostArborescence& algorithm, int variable)
kpeter@625
   736
        : _algorithm(&algorithm)
kpeter@625
   737
      {
kpeter@625
   738
        _index = _algorithm->_dual_variables[variable].begin;
kpeter@625
   739
        _last = _algorithm->_dual_variables[variable].end;
kpeter@625
   740
      }
kpeter@625
   741
kpeter@625
   742
      /// \brief Conversion to \c Node.
kpeter@625
   743
      ///
kpeter@625
   744
      /// Conversion to \c Node.
kpeter@625
   745
      operator Node() const {
kpeter@625
   746
        return _algorithm->_dual_node_list[_index];
kpeter@625
   747
      }
kpeter@625
   748
kpeter@625
   749
      /// \brief Increment operator.
kpeter@625
   750
      ///
kpeter@625
   751
      /// Increment operator.
kpeter@625
   752
      DualIt& operator++() {
kpeter@625
   753
        ++_index;
kpeter@625
   754
        return *this;
kpeter@625
   755
      }
kpeter@625
   756
kpeter@625
   757
      /// \brief Validity checking
kpeter@625
   758
      ///
kpeter@625
   759
      /// Checks whether the iterator is invalid.
kpeter@625
   760
      bool operator==(Invalid) const {
kpeter@625
   761
        return _index == _last;
kpeter@625
   762
      }
kpeter@625
   763
kpeter@625
   764
      /// \brief Validity checking
kpeter@625
   765
      ///
kpeter@625
   766
      /// Checks whether the iterator is valid.
kpeter@625
   767
      bool operator!=(Invalid) const {
kpeter@625
   768
        return _index != _last;
kpeter@625
   769
      }
kpeter@625
   770
kpeter@625
   771
    private:
kpeter@625
   772
      const MinCostArborescence* _algorithm;
kpeter@625
   773
      int _index, _last;
kpeter@625
   774
    };
kpeter@625
   775
kpeter@625
   776
    /// @}
kpeter@625
   777
deba@490
   778
  };
deba@490
   779
deba@490
   780
  /// \ingroup spantree
deba@490
   781
  ///
deba@490
   782
  /// \brief Function type interface for MinCostArborescence algorithm.
deba@490
   783
  ///
deba@490
   784
  /// Function type interface for MinCostArborescence algorithm.
kpeter@625
   785
  /// \param digraph The digraph the algorithm runs on.
kpeter@625
   786
  /// \param cost An arc map storing the costs.
kpeter@625
   787
  /// \param source The source node of the arborescence.
kpeter@625
   788
  /// \retval arborescence An arc map with \c bool (or convertible) value
kpeter@625
   789
  /// type that stores the arborescence.
kpeter@625
   790
  /// \return The total cost of the arborescence.
deba@490
   791
  ///
deba@490
   792
  /// \sa MinCostArborescence
deba@490
   793
  template <typename Digraph, typename CostMap, typename ArborescenceMap>
deba@490
   794
  typename CostMap::Value minCostArborescence(const Digraph& digraph,
deba@490
   795
                                              const CostMap& cost,
deba@490
   796
                                              typename Digraph::Node source,
deba@490
   797
                                              ArborescenceMap& arborescence) {
deba@490
   798
    typename MinCostArborescence<Digraph, CostMap>
kpeter@625
   799
      ::template SetArborescenceMap<ArborescenceMap>
deba@490
   800
      ::Create mca(digraph, cost);
deba@490
   801
    mca.arborescenceMap(arborescence);
deba@490
   802
    mca.run(source);
kpeter@625
   803
    return mca.arborescenceCost();
deba@490
   804
  }
deba@490
   805
deba@490
   806
}
deba@490
   807
deba@490
   808
#endif