lemon/min_cost_arborescence.h
author Alpar Juttner <alpar@cs.elte.hu>
Thu, 17 Oct 2013 15:08:41 +0200
changeset 1104 a78e5b779b69
parent 1080 c5cd8960df74
permissions -rw-r--r--
Merge bugfix #478
deba@501
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
deba@501
     2
 *
deba@501
     3
 * This file is a part of LEMON, a generic C++ optimization library.
deba@501
     4
 *
alpar@1092
     5
 * Copyright (C) 2003-2013
deba@501
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
deba@501
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
deba@501
     8
 *
deba@501
     9
 * Permission to use, modify and distribute this software is granted
deba@501
    10
 * provided that this copyright notice appears in all copies. For
deba@501
    11
 * precise terms see the accompanying LICENSE file.
deba@501
    12
 *
deba@501
    13
 * This software is provided "AS IS" with no warranty of any kind,
deba@501
    14
 * express or implied, and with no claim as to its suitability for any
deba@501
    15
 * purpose.
deba@501
    16
 *
deba@501
    17
 */
deba@501
    18
deba@501
    19
#ifndef LEMON_MIN_COST_ARBORESCENCE_H
deba@501
    20
#define LEMON_MIN_COST_ARBORESCENCE_H
deba@501
    21
deba@501
    22
///\ingroup spantree
deba@501
    23
///\file
deba@501
    24
///\brief Minimum Cost Arborescence algorithm.
deba@501
    25
deba@501
    26
#include <vector>
deba@501
    27
deba@501
    28
#include <lemon/list_graph.h>
deba@501
    29
#include <lemon/bin_heap.h>
deba@501
    30
#include <lemon/assert.h>
deba@501
    31
deba@501
    32
namespace lemon {
deba@501
    33
deba@501
    34
deba@501
    35
  /// \brief Default traits class for MinCostArborescence class.
deba@501
    36
  ///
deba@501
    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@501
    41
  struct MinCostArborescenceDefaultTraits{
deba@501
    42
deba@501
    43
    /// \brief The digraph type the algorithm runs on.
kpeter@559
    44
    typedef GR Digraph;
deba@501
    45
deba@501
    46
    /// \brief The type of the map that stores the arc costs.
deba@501
    47
    ///
deba@501
    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@501
    51
deba@501
    52
    /// \brief The value type of the costs.
deba@501
    53
    ///
deba@501
    54
    /// The value type of the costs.
deba@501
    55
    typedef typename CostMap::Value Value;
deba@501
    56
deba@501
    57
    /// \brief The type of the map that stores which arcs are in the
deba@501
    58
    /// arborescence.
deba@501
    59
    ///
deba@501
    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@501
    65
    typedef typename Digraph::template ArcMap<bool> ArborescenceMap;
deba@501
    66
kpeter@559
    67
    /// \brief Instantiates a \c ArborescenceMap.
deba@501
    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@501
    72
    static ArborescenceMap *createArborescenceMap(const Digraph &digraph){
deba@501
    73
      return new ArborescenceMap(digraph);
deba@501
    74
    }
deba@501
    75
kpeter@559
    76
    /// \brief The type of the \c PredMap
deba@501
    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@501
    81
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
deba@501
    82
kpeter@559
    83
    /// \brief Instantiates a \c PredMap.
deba@501
    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@501
    88
    static PredMap *createPredMap(const Digraph &digraph){
deba@501
    89
      return new PredMap(digraph);
deba@501
    90
    }
deba@501
    91
deba@501
    92
  };
deba@501
    93
deba@501
    94
  /// \ingroup spantree
deba@501
    95
  ///
kpeter@584
    96
  /// \brief Minimum Cost Arborescence algorithm class.
deba@501
    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@501
   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@501
   103
  /// given sources and spans all the nodes which are reachable from the
kpeter@1080
   104
  /// sources. The time complexity of the algorithm is O(n<sup>2</sup>+m).
deba@501
   105
  ///
kpeter@625
   106
  /// The algorithm also provides an optimal dual solution, therefore
deba@501
   107
  /// the optimality of the solution can be checked.
deba@501
   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@501
   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@501
   113
  /// it is necessary. The default map type is \ref
deba@501
   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@501
   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@501
   125
#else
kpeter@825
   126
  template <typename GR, typename CM, typename TR>
deba@501
   127
#endif
deba@501
   128
  class MinCostArborescence {
deba@501
   129
  public:
deba@501
   130
alpar@1074
   131
    /// \brief The \ref lemon::MinCostArborescenceDefaultTraits "traits class"
alpar@877
   132
    /// of the algorithm.
kpeter@559
   133
    typedef TR Traits;
deba@501
   134
    /// The type of the underlying digraph.
deba@501
   135
    typedef typename Traits::Digraph Digraph;
deba@501
   136
    /// The type of the map that stores the arc costs.
deba@501
   137
    typedef typename Traits::CostMap CostMap;
deba@501
   138
    ///The type of the costs of the arcs.
deba@501
   139
    typedef typename Traits::Value Value;
deba@501
   140
    ///The type of the predecessor map.
deba@501
   141
    typedef typename Traits::PredMap PredMap;
deba@501
   142
    ///The type of the map that stores which arcs are in the arborescence.
deba@501
   143
    typedef typename Traits::ArborescenceMap ArborescenceMap;
deba@501
   144
deba@501
   145
    typedef MinCostArborescence Create;
deba@501
   146
deba@501
   147
  private:
deba@501
   148
deba@501
   149
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
deba@501
   150
deba@501
   151
    struct CostArc {
deba@501
   152
deba@501
   153
      Arc arc;
deba@501
   154
      Value value;
deba@501
   155
deba@501
   156
      CostArc() {}
deba@501
   157
      CostArc(Arc _arc, Value _value) : arc(_arc), value(_value) {}
deba@501
   158
deba@501
   159
    };
deba@501
   160
deba@501
   161
    const Digraph *_digraph;
deba@501
   162
    const CostMap *_cost;
deba@501
   163
deba@501
   164
    PredMap *_pred;
deba@501
   165
    bool local_pred;
deba@501
   166
deba@501
   167
    ArborescenceMap *_arborescence;
deba@501
   168
    bool local_arborescence;
deba@501
   169
deba@501
   170
    typedef typename Digraph::template ArcMap<int> ArcOrder;
deba@501
   171
    ArcOrder *_arc_order;
deba@501
   172
deba@501
   173
    typedef typename Digraph::template NodeMap<int> NodeOrder;
deba@501
   174
    NodeOrder *_node_order;
deba@501
   175
deba@501
   176
    typedef typename Digraph::template NodeMap<CostArc> CostArcMap;
deba@501
   177
    CostArcMap *_cost_arcs;
deba@501
   178
deba@501
   179
    struct StackLevel {
deba@501
   180
deba@501
   181
      std::vector<CostArc> arcs;
deba@501
   182
      int node_level;
deba@501
   183
deba@501
   184
    };
deba@501
   185
deba@501
   186
    std::vector<StackLevel> level_stack;
deba@501
   187
    std::vector<Node> queue;
deba@501
   188
deba@501
   189
    typedef std::vector<typename Digraph::Node> DualNodeList;
deba@501
   190
deba@501
   191
    DualNodeList _dual_node_list;
deba@501
   192
deba@501
   193
    struct DualVariable {
deba@501
   194
      int begin, end;
deba@501
   195
      Value value;
deba@501
   196
deba@501
   197
      DualVariable(int _begin, int _end, Value _value)
deba@501
   198
        : begin(_begin), end(_end), value(_value) {}
deba@501
   199
deba@501
   200
    };
deba@501
   201
deba@501
   202
    typedef std::vector<DualVariable> DualVariables;
deba@501
   203
deba@501
   204
    DualVariables _dual_variables;
deba@501
   205
deba@501
   206
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
deba@501
   207
deba@501
   208
    HeapCrossRef *_heap_cross_ref;
deba@501
   209
deba@501
   210
    typedef BinHeap<int, HeapCrossRef> Heap;
deba@501
   211
deba@501
   212
    Heap *_heap;
deba@501
   213
deba@501
   214
  protected:
deba@501
   215
deba@501
   216
    MinCostArborescence() {}
deba@501
   217
deba@501
   218
  private:
deba@501
   219
deba@501
   220
    void createStructures() {
deba@501
   221
      if (!_pred) {
deba@501
   222
        local_pred = true;
deba@501
   223
        _pred = Traits::createPredMap(*_digraph);
deba@501
   224
      }
deba@501
   225
      if (!_arborescence) {
deba@501
   226
        local_arborescence = true;
deba@501
   227
        _arborescence = Traits::createArborescenceMap(*_digraph);
deba@501
   228
      }
deba@501
   229
      if (!_arc_order) {
deba@501
   230
        _arc_order = new ArcOrder(*_digraph);
deba@501
   231
      }
deba@501
   232
      if (!_node_order) {
deba@501
   233
        _node_order = new NodeOrder(*_digraph);
deba@501
   234
      }
deba@501
   235
      if (!_cost_arcs) {
deba@501
   236
        _cost_arcs = new CostArcMap(*_digraph);
deba@501
   237
      }
deba@501
   238
      if (!_heap_cross_ref) {
deba@501
   239
        _heap_cross_ref = new HeapCrossRef(*_digraph, -1);
deba@501
   240
      }
deba@501
   241
      if (!_heap) {
deba@501
   242
        _heap = new Heap(*_heap_cross_ref);
deba@501
   243
      }
deba@501
   244
    }
deba@501
   245
deba@501
   246
    void destroyStructures() {
deba@501
   247
      if (local_arborescence) {
deba@501
   248
        delete _arborescence;
deba@501
   249
      }
deba@501
   250
      if (local_pred) {
deba@501
   251
        delete _pred;
deba@501
   252
      }
deba@501
   253
      if (_arc_order) {
deba@501
   254
        delete _arc_order;
deba@501
   255
      }
deba@501
   256
      if (_node_order) {
deba@501
   257
        delete _node_order;
deba@501
   258
      }
deba@501
   259
      if (_cost_arcs) {
deba@501
   260
        delete _cost_arcs;
deba@501
   261
      }
deba@501
   262
      if (_heap) {
deba@501
   263
        delete _heap;
deba@501
   264
      }
deba@501
   265
      if (_heap_cross_ref) {
deba@501
   266
        delete _heap_cross_ref;
deba@501
   267
      }
deba@501
   268
    }
deba@501
   269
deba@501
   270
    Arc prepare(Node node) {
deba@501
   271
      std::vector<Node> nodes;
deba@501
   272
      (*_node_order)[node] = _dual_node_list.size();
deba@501
   273
      StackLevel level;
deba@501
   274
      level.node_level = _dual_node_list.size();
deba@501
   275
      _dual_node_list.push_back(node);
deba@501
   276
      for (InArcIt it(*_digraph, node); it != INVALID; ++it) {
deba@501
   277
        Arc arc = it;
deba@501
   278
        Node source = _digraph->source(arc);
deba@501
   279
        Value value = (*_cost)[it];
deba@501
   280
        if (source == node || (*_node_order)[source] == -3) continue;
deba@501
   281
        if ((*_cost_arcs)[source].arc == INVALID) {
deba@501
   282
          (*_cost_arcs)[source].arc = arc;
deba@501
   283
          (*_cost_arcs)[source].value = value;
deba@501
   284
          nodes.push_back(source);
deba@501
   285
        } else {
deba@501
   286
          if ((*_cost_arcs)[source].value > value) {
deba@501
   287
            (*_cost_arcs)[source].arc = arc;
deba@501
   288
            (*_cost_arcs)[source].value = value;
deba@501
   289
          }
deba@501
   290
        }
deba@501
   291
      }
deba@501
   292
      CostArc minimum = (*_cost_arcs)[nodes[0]];
deba@501
   293
      for (int i = 1; i < int(nodes.size()); ++i) {
deba@501
   294
        if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
deba@501
   295
          minimum = (*_cost_arcs)[nodes[i]];
deba@501
   296
        }
deba@501
   297
      }
kpeter@581
   298
      (*_arc_order)[minimum.arc] = _dual_variables.size();
deba@501
   299
      DualVariable var(_dual_node_list.size() - 1,
deba@501
   300
                       _dual_node_list.size(), minimum.value);
deba@501
   301
      _dual_variables.push_back(var);
deba@501
   302
      for (int i = 0; i < int(nodes.size()); ++i) {
deba@501
   303
        (*_cost_arcs)[nodes[i]].value -= minimum.value;
deba@501
   304
        level.arcs.push_back((*_cost_arcs)[nodes[i]]);
deba@501
   305
        (*_cost_arcs)[nodes[i]].arc = INVALID;
deba@501
   306
      }
deba@501
   307
      level_stack.push_back(level);
deba@501
   308
      return minimum.arc;
deba@501
   309
    }
deba@501
   310
deba@501
   311
    Arc contract(Node node) {
deba@501
   312
      int node_bottom = bottom(node);
deba@501
   313
      std::vector<Node> nodes;
deba@501
   314
      while (!level_stack.empty() &&
deba@501
   315
             level_stack.back().node_level >= node_bottom) {
deba@501
   316
        for (int i = 0; i < int(level_stack.back().arcs.size()); ++i) {
deba@501
   317
          Arc arc = level_stack.back().arcs[i].arc;
deba@501
   318
          Node source = _digraph->source(arc);
deba@501
   319
          Value value = level_stack.back().arcs[i].value;
deba@501
   320
          if ((*_node_order)[source] >= node_bottom) continue;
deba@501
   321
          if ((*_cost_arcs)[source].arc == INVALID) {
deba@501
   322
            (*_cost_arcs)[source].arc = arc;
deba@501
   323
            (*_cost_arcs)[source].value = value;
deba@501
   324
            nodes.push_back(source);
deba@501
   325
          } else {
deba@501
   326
            if ((*_cost_arcs)[source].value > value) {
deba@501
   327
              (*_cost_arcs)[source].arc = arc;
deba@501
   328
              (*_cost_arcs)[source].value = value;
deba@501
   329
            }
deba@501
   330
          }
deba@501
   331
        }
deba@501
   332
        level_stack.pop_back();
deba@501
   333
      }
deba@501
   334
      CostArc minimum = (*_cost_arcs)[nodes[0]];
deba@501
   335
      for (int i = 1; i < int(nodes.size()); ++i) {
deba@501
   336
        if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
deba@501
   337
          minimum = (*_cost_arcs)[nodes[i]];
deba@501
   338
        }
deba@501
   339
      }
kpeter@581
   340
      (*_arc_order)[minimum.arc] = _dual_variables.size();
deba@501
   341
      DualVariable var(node_bottom, _dual_node_list.size(), minimum.value);
deba@501
   342
      _dual_variables.push_back(var);
deba@501
   343
      StackLevel level;
deba@501
   344
      level.node_level = node_bottom;
deba@501
   345
      for (int i = 0; i < int(nodes.size()); ++i) {
deba@501
   346
        (*_cost_arcs)[nodes[i]].value -= minimum.value;
deba@501
   347
        level.arcs.push_back((*_cost_arcs)[nodes[i]]);
deba@501
   348
        (*_cost_arcs)[nodes[i]].arc = INVALID;
deba@501
   349
      }
deba@501
   350
      level_stack.push_back(level);
deba@501
   351
      return minimum.arc;
deba@501
   352
    }
deba@501
   353
deba@501
   354
    int bottom(Node node) {
deba@501
   355
      int k = level_stack.size() - 1;
deba@501
   356
      while (level_stack[k].node_level > (*_node_order)[node]) {
deba@501
   357
        --k;
deba@501
   358
      }
deba@501
   359
      return level_stack[k].node_level;
deba@501
   360
    }
deba@501
   361
deba@501
   362
    void finalize(Arc arc) {
deba@501
   363
      Node node = _digraph->target(arc);
deba@501
   364
      _heap->push(node, (*_arc_order)[arc]);
deba@501
   365
      _pred->set(node, arc);
deba@501
   366
      while (!_heap->empty()) {
deba@501
   367
        Node source = _heap->top();
deba@501
   368
        _heap->pop();
kpeter@581
   369
        (*_node_order)[source] = -1;
deba@501
   370
        for (OutArcIt it(*_digraph, source); it != INVALID; ++it) {
deba@501
   371
          if ((*_arc_order)[it] < 0) continue;
deba@501
   372
          Node target = _digraph->target(it);
deba@501
   373
          switch(_heap->state(target)) {
deba@501
   374
          case Heap::PRE_HEAP:
deba@501
   375
            _heap->push(target, (*_arc_order)[it]);
deba@501
   376
            _pred->set(target, it);
deba@501
   377
            break;
deba@501
   378
          case Heap::IN_HEAP:
deba@501
   379
            if ((*_arc_order)[it] < (*_heap)[target]) {
deba@501
   380
              _heap->decrease(target, (*_arc_order)[it]);
deba@501
   381
              _pred->set(target, it);
deba@501
   382
            }
deba@501
   383
            break;
deba@501
   384
          case Heap::POST_HEAP:
deba@501
   385
            break;
deba@501
   386
          }
deba@501
   387
        }
deba@501
   388
        _arborescence->set((*_pred)[source], true);
deba@501
   389
      }
deba@501
   390
    }
deba@501
   391
deba@501
   392
deba@501
   393
  public:
deba@501
   394
kpeter@584
   395
    /// \name Named Template Parameters
deba@501
   396
deba@501
   397
    /// @{
deba@501
   398
deba@501
   399
    template <class T>
kpeter@625
   400
    struct SetArborescenceMapTraits : public Traits {
deba@501
   401
      typedef T ArborescenceMap;
deba@501
   402
      static ArborescenceMap *createArborescenceMap(const Digraph &)
deba@501
   403
      {
deba@501
   404
        LEMON_ASSERT(false, "ArborescenceMap is not initialized");
deba@501
   405
        return 0; // ignore warnings
deba@501
   406
      }
deba@501
   407
    };
deba@501
   408
deba@501
   409
    /// \brief \ref named-templ-param "Named parameter" for
kpeter@625
   410
    /// setting \c ArborescenceMap type
deba@501
   411
    ///
deba@501
   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@501
   418
    template <class T>
kpeter@625
   419
    struct SetArborescenceMap
deba@501
   420
      : public MinCostArborescence<Digraph, CostMap,
kpeter@625
   421
                                   SetArborescenceMapTraits<T> > {
deba@501
   422
    };
deba@501
   423
deba@501
   424
    template <class T>
kpeter@625
   425
    struct SetPredMapTraits : public Traits {
deba@501
   426
      typedef T PredMap;
deba@501
   427
      static PredMap *createPredMap(const Digraph &)
deba@501
   428
      {
deba@501
   429
        LEMON_ASSERT(false, "PredMap is not initialized");
kpeter@625
   430
        return 0; // ignore warnings
deba@501
   431
      }
deba@501
   432
    };
deba@501
   433
deba@501
   434
    /// \brief \ref named-templ-param "Named parameter" for
kpeter@625
   435
    /// setting \c PredMap type
deba@501
   436
    ///
deba@501
   437
    /// \ref named-templ-param "Named parameter" for setting
kpeter@625
   438
    /// \c PredMap type.
alpar@877
   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@501
   441
    template <class T>
kpeter@625
   442
    struct SetPredMap
kpeter@625
   443
      : public MinCostArborescence<Digraph, CostMap, SetPredMapTraits<T> > {
deba@501
   444
    };
deba@501
   445
deba@501
   446
    /// @}
deba@501
   447
deba@501
   448
    /// \brief Constructor.
deba@501
   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@501
   452
    MinCostArborescence(const Digraph& digraph, const CostMap& cost)
deba@501
   453
      : _digraph(&digraph), _cost(&cost), _pred(0), local_pred(false),
deba@501
   454
        _arborescence(0), local_arborescence(false),
deba@501
   455
        _arc_order(0), _node_order(0), _cost_arcs(0),
deba@501
   456
        _heap_cross_ref(0), _heap(0) {}
deba@501
   457
deba@501
   458
    /// \brief Destructor.
deba@501
   459
    ~MinCostArborescence() {
deba@501
   460
      destroyStructures();
deba@501
   461
    }
deba@501
   462
deba@501
   463
    /// \brief Sets the arborescence map.
deba@501
   464
    ///
deba@501
   465
    /// Sets the arborescence map.
kpeter@559
   466
    /// \return <tt>(*this)</tt>
deba@501
   467
    MinCostArborescence& arborescenceMap(ArborescenceMap& m) {
deba@501
   468
      if (local_arborescence) {
deba@501
   469
        delete _arborescence;
deba@501
   470
      }
deba@501
   471
      local_arborescence = false;
deba@501
   472
      _arborescence = &m;
deba@501
   473
      return *this;
deba@501
   474
    }
deba@501
   475
kpeter@625
   476
    /// \brief Sets the predecessor map.
deba@501
   477
    ///
kpeter@625
   478
    /// Sets the predecessor map.
kpeter@559
   479
    /// \return <tt>(*this)</tt>
deba@501
   480
    MinCostArborescence& predMap(PredMap& m) {
deba@501
   481
      if (local_pred) {
deba@501
   482
        delete _pred;
deba@501
   483
      }
deba@501
   484
      local_pred = false;
deba@501
   485
      _pred = &m;
deba@501
   486
      return *this;
deba@501
   487
    }
deba@501
   488
kpeter@584
   489
    /// \name Execution Control
deba@501
   490
    /// The simplest way to execute the algorithm is to use
deba@501
   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@501
   494
    /// source nodes with \ref addSource().
deba@501
   495
    /// Finally \ref start() will perform the arborescence
deba@501
   496
    /// computation.
deba@501
   497
deba@501
   498
    ///@{
deba@501
   499
deba@501
   500
    /// \brief Initializes the internal data structures.
deba@501
   501
    ///
deba@501
   502
    /// Initializes the internal data structures.
deba@501
   503
    ///
deba@501
   504
    void init() {
deba@501
   505
      createStructures();
deba@501
   506
      _heap->clear();
deba@501
   507
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
deba@501
   508
        (*_cost_arcs)[it].arc = INVALID;
kpeter@581
   509
        (*_node_order)[it] = -3;
kpeter@581
   510
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
deba@501
   511
        _pred->set(it, INVALID);
deba@501
   512
      }
deba@501
   513
      for (ArcIt it(*_digraph); it != INVALID; ++it) {
deba@501
   514
        _arborescence->set(it, false);
kpeter@581
   515
        (*_arc_order)[it] = -1;
deba@501
   516
      }
deba@501
   517
      _dual_node_list.clear();
deba@501
   518
      _dual_variables.clear();
deba@501
   519
    }
deba@501
   520
deba@501
   521
    /// \brief Adds a new source node.
deba@501
   522
    ///
deba@501
   523
    /// Adds a new source node to the algorithm.
deba@501
   524
    void addSource(Node source) {
deba@501
   525
      std::vector<Node> nodes;
deba@501
   526
      nodes.push_back(source);
deba@501
   527
      while (!nodes.empty()) {
deba@501
   528
        Node node = nodes.back();
deba@501
   529
        nodes.pop_back();
deba@501
   530
        for (OutArcIt it(*_digraph, node); it != INVALID; ++it) {
deba@501
   531
          Node target = _digraph->target(it);
deba@501
   532
          if ((*_node_order)[target] == -3) {
deba@501
   533
            (*_node_order)[target] = -2;
deba@501
   534
            nodes.push_back(target);
deba@501
   535
            queue.push_back(target);
deba@501
   536
          }
deba@501
   537
        }
deba@501
   538
      }
deba@501
   539
      (*_node_order)[source] = -1;
deba@501
   540
    }
deba@501
   541
deba@501
   542
    /// \brief Processes the next node in the priority queue.
deba@501
   543
    ///
deba@501
   544
    /// Processes the next node in the priority queue.
deba@501
   545
    ///
deba@501
   546
    /// \return The processed node.
deba@501
   547
    ///
kpeter@625
   548
    /// \warning The queue must not be empty.
deba@501
   549
    Node processNextNode() {
deba@501
   550
      Node node = queue.back();
deba@501
   551
      queue.pop_back();
deba@501
   552
      if ((*_node_order)[node] == -2) {
deba@501
   553
        Arc arc = prepare(node);
deba@501
   554
        Node source = _digraph->source(arc);
deba@501
   555
        while ((*_node_order)[source] != -1) {
deba@501
   556
          if ((*_node_order)[source] >= 0) {
deba@501
   557
            arc = contract(source);
deba@501
   558
          } else {
deba@501
   559
            arc = prepare(source);
deba@501
   560
          }
deba@501
   561
          source = _digraph->source(arc);
deba@501
   562
        }
deba@501
   563
        finalize(arc);
deba@501
   564
        level_stack.clear();
deba@501
   565
      }
deba@501
   566
      return node;
deba@501
   567
    }
deba@501
   568
deba@501
   569
    /// \brief Returns the number of the nodes to be processed.
deba@501
   570
    ///
kpeter@625
   571
    /// Returns the number of the nodes to be processed in the priority
kpeter@625
   572
    /// queue.
deba@501
   573
    int queueSize() const {
deba@501
   574
      return queue.size();
deba@501
   575
    }
deba@501
   576
deba@501
   577
    /// \brief Returns \c false if there are nodes to be processed.
deba@501
   578
    ///
deba@501
   579
    /// Returns \c false if there are nodes to be processed.
deba@501
   580
    bool emptyQueue() const {
deba@501
   581
      return queue.empty();
deba@501
   582
    }
deba@501
   583
deba@501
   584
    /// \brief Executes the algorithm.
deba@501
   585
    ///
deba@501
   586
    /// Executes the algorithm.
deba@501
   587
    ///
deba@501
   588
    /// \pre init() must be called and at least one node should be added
deba@501
   589
    /// with addSource() before using this function.
deba@501
   590
    ///
deba@501
   591
    ///\note mca.start() is just a shortcut of the following code.
deba@501
   592
    ///\code
deba@501
   593
    ///while (!mca.emptyQueue()) {
deba@501
   594
    ///  mca.processNextNode();
deba@501
   595
    ///}
deba@501
   596
    ///\endcode
deba@501
   597
    void start() {
deba@501
   598
      while (!emptyQueue()) {
deba@501
   599
        processNextNode();
deba@501
   600
      }
deba@501
   601
    }
deba@501
   602
deba@501
   603
    /// \brief Runs %MinCostArborescence algorithm from node \c s.
deba@501
   604
    ///
deba@501
   605
    /// This method runs the %MinCostArborescence algorithm from
deba@501
   606
    /// a root node \c s.
deba@501
   607
    ///
deba@501
   608
    /// \note mca.run(s) is just a shortcut of the following code.
deba@501
   609
    /// \code
deba@501
   610
    /// mca.init();
deba@501
   611
    /// mca.addSource(s);
deba@501
   612
    /// mca.start();
deba@501
   613
    /// \endcode
kpeter@625
   614
    void run(Node s) {
deba@501
   615
      init();
kpeter@625
   616
      addSource(s);
deba@501
   617
      start();
deba@501
   618
    }
deba@501
   619
deba@501
   620
    ///@}
deba@501
   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@501
   778
  };
deba@501
   779
deba@501
   780
  /// \ingroup spantree
deba@501
   781
  ///
deba@501
   782
  /// \brief Function type interface for MinCostArborescence algorithm.
deba@501
   783
  ///
deba@501
   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@501
   791
  ///
deba@501
   792
  /// \sa MinCostArborescence
deba@501
   793
  template <typename Digraph, typename CostMap, typename ArborescenceMap>
deba@501
   794
  typename CostMap::Value minCostArborescence(const Digraph& digraph,
deba@501
   795
                                              const CostMap& cost,
deba@501
   796
                                              typename Digraph::Node source,
deba@501
   797
                                              ArborescenceMap& arborescence) {
deba@501
   798
    typename MinCostArborescence<Digraph, CostMap>
kpeter@625
   799
      ::template SetArborescenceMap<ArborescenceMap>
deba@501
   800
      ::Create mca(digraph, cost);
deba@501
   801
    mca.arborescenceMap(arborescence);
deba@501
   802
    mca.run(source);
kpeter@625
   803
    return mca.arborescenceCost();
deba@501
   804
  }
deba@501
   805
deba@501
   806
}
deba@501
   807
deba@501
   808
#endif