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