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