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