1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_MIN_COST_ARBORESCENCE_H
20 #define LEMON_MIN_COST_ARBORESCENCE_H
24 ///\brief Minimum Cost Arborescence algorithm.
28 #include <lemon/list_graph.h>
29 #include <lemon/bin_heap.h>
30 #include <lemon/assert.h>
35 /// \brief Default traits class for MinCostArborescence class.
37 /// Default traits class for MinCostArborescence class.
38 /// \param GR Digraph type.
39 /// \param CM Type of cost map.
40 template <class GR, class CM>
41 struct MinCostArborescenceDefaultTraits{
43 /// \brief The digraph type the algorithm runs on.
46 /// \brief The type of the map that stores the arc costs.
48 /// The type of the map that stores the arc costs.
49 /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
52 /// \brief The value type of the costs.
54 /// The value type of the costs.
55 typedef typename CostMap::Value Value;
57 /// \brief The type of the map that stores which arcs are in the
60 /// The type of the map that stores which arcs are in the
61 /// arborescence. It must meet the \ref concepts::WriteMap
62 /// "WriteMap" concept. Initially it will be set to false on each
63 /// arc. After it will set all arborescence arcs once.
64 typedef typename Digraph::template ArcMap<bool> ArborescenceMap;
66 /// \brief Instantiates a \c ArborescenceMap.
68 /// This function instantiates a \c ArborescenceMap.
69 /// \param digraph is the graph, to which we would like to
70 /// calculate the \c ArborescenceMap.
71 static ArborescenceMap *createArborescenceMap(const Digraph &digraph){
72 return new ArborescenceMap(digraph);
75 /// \brief The type of the \c PredMap
77 /// The type of the \c PredMap. It is a node map with an arc value type.
78 typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
80 /// \brief Instantiates a \c PredMap.
82 /// This function instantiates a \c PredMap.
83 /// \param digraph The digraph to which we would like to define the
85 static PredMap *createPredMap(const Digraph &digraph){
86 return new PredMap(digraph);
93 /// \brief %MinCostArborescence algorithm class.
95 /// This class provides an efficient implementation of
96 /// %MinCostArborescence algorithm. The arborescence is a tree
97 /// which is directed from a given source node of the digraph. One or
98 /// more sources should be given for the algorithm and it will calculate
99 /// the minimum cost subgraph which are union of arborescences with the
100 /// given sources and spans all the nodes which are reachable from the
101 /// sources. The time complexity of the algorithm is O(n<sup>2</sup>+e).
103 /// The algorithm provides also an optimal dual solution, therefore
104 /// the optimality of the solution can be checked.
106 /// \param GR The digraph type the algorithm runs on. The default value
107 /// is \ref ListDigraph.
108 /// \param CM This read-only ArcMap determines the costs of the
109 /// arcs. It is read once for each arc, so the map may involve in
110 /// relatively time consuming process to compute the arc cost if
111 /// it is necessary. The default map type is \ref
112 /// concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
113 /// \param TR Traits class to set various data types used
114 /// by the algorithm. The default traits class is
115 /// \ref MinCostArborescenceDefaultTraits
116 /// "MinCostArborescenceDefaultTraits<GR, CM>". See \ref
117 /// MinCostArborescenceDefaultTraits for the documentation of a
118 /// MinCostArborescence traits class.
120 template <typename GR = ListDigraph,
121 typename CM = typename GR::template ArcMap<int>,
123 MinCostArborescenceDefaultTraits<GR, CM> >
125 template <typename GR, typename CM, typedef TR>
127 class MinCostArborescence {
132 /// The type of the underlying digraph.
133 typedef typename Traits::Digraph Digraph;
134 /// The type of the map that stores the arc costs.
135 typedef typename Traits::CostMap CostMap;
136 ///The type of the costs of the arcs.
137 typedef typename Traits::Value Value;
138 ///The type of the predecessor map.
139 typedef typename Traits::PredMap PredMap;
140 ///The type of the map that stores which arcs are in the arborescence.
141 typedef typename Traits::ArborescenceMap ArborescenceMap;
143 typedef MinCostArborescence Create;
147 TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
155 CostArc(Arc _arc, Value _value) : arc(_arc), value(_value) {}
159 const Digraph *_digraph;
160 const CostMap *_cost;
165 ArborescenceMap *_arborescence;
166 bool local_arborescence;
168 typedef typename Digraph::template ArcMap<int> ArcOrder;
169 ArcOrder *_arc_order;
171 typedef typename Digraph::template NodeMap<int> NodeOrder;
172 NodeOrder *_node_order;
174 typedef typename Digraph::template NodeMap<CostArc> CostArcMap;
175 CostArcMap *_cost_arcs;
179 std::vector<CostArc> arcs;
184 std::vector<StackLevel> level_stack;
185 std::vector<Node> queue;
187 typedef std::vector<typename Digraph::Node> DualNodeList;
189 DualNodeList _dual_node_list;
191 struct DualVariable {
195 DualVariable(int _begin, int _end, Value _value)
196 : begin(_begin), end(_end), value(_value) {}
200 typedef std::vector<DualVariable> DualVariables;
202 DualVariables _dual_variables;
204 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
206 HeapCrossRef *_heap_cross_ref;
208 typedef BinHeap<int, HeapCrossRef> Heap;
214 MinCostArborescence() {}
218 void createStructures() {
221 _pred = Traits::createPredMap(*_digraph);
223 if (!_arborescence) {
224 local_arborescence = true;
225 _arborescence = Traits::createArborescenceMap(*_digraph);
228 _arc_order = new ArcOrder(*_digraph);
231 _node_order = new NodeOrder(*_digraph);
234 _cost_arcs = new CostArcMap(*_digraph);
236 if (!_heap_cross_ref) {
237 _heap_cross_ref = new HeapCrossRef(*_digraph, -1);
240 _heap = new Heap(*_heap_cross_ref);
244 void destroyStructures() {
245 if (local_arborescence) {
246 delete _arborescence;
263 if (_heap_cross_ref) {
264 delete _heap_cross_ref;
268 Arc prepare(Node node) {
269 std::vector<Node> nodes;
270 (*_node_order)[node] = _dual_node_list.size();
272 level.node_level = _dual_node_list.size();
273 _dual_node_list.push_back(node);
274 for (InArcIt it(*_digraph, node); it != INVALID; ++it) {
276 Node source = _digraph->source(arc);
277 Value value = (*_cost)[it];
278 if (source == node || (*_node_order)[source] == -3) continue;
279 if ((*_cost_arcs)[source].arc == INVALID) {
280 (*_cost_arcs)[source].arc = arc;
281 (*_cost_arcs)[source].value = value;
282 nodes.push_back(source);
284 if ((*_cost_arcs)[source].value > value) {
285 (*_cost_arcs)[source].arc = arc;
286 (*_cost_arcs)[source].value = value;
290 CostArc minimum = (*_cost_arcs)[nodes[0]];
291 for (int i = 1; i < int(nodes.size()); ++i) {
292 if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
293 minimum = (*_cost_arcs)[nodes[i]];
296 _arc_order->set(minimum.arc, _dual_variables.size());
297 DualVariable var(_dual_node_list.size() - 1,
298 _dual_node_list.size(), minimum.value);
299 _dual_variables.push_back(var);
300 for (int i = 0; i < int(nodes.size()); ++i) {
301 (*_cost_arcs)[nodes[i]].value -= minimum.value;
302 level.arcs.push_back((*_cost_arcs)[nodes[i]]);
303 (*_cost_arcs)[nodes[i]].arc = INVALID;
305 level_stack.push_back(level);
309 Arc contract(Node node) {
310 int node_bottom = bottom(node);
311 std::vector<Node> nodes;
312 while (!level_stack.empty() &&
313 level_stack.back().node_level >= node_bottom) {
314 for (int i = 0; i < int(level_stack.back().arcs.size()); ++i) {
315 Arc arc = level_stack.back().arcs[i].arc;
316 Node source = _digraph->source(arc);
317 Value value = level_stack.back().arcs[i].value;
318 if ((*_node_order)[source] >= node_bottom) continue;
319 if ((*_cost_arcs)[source].arc == INVALID) {
320 (*_cost_arcs)[source].arc = arc;
321 (*_cost_arcs)[source].value = value;
322 nodes.push_back(source);
324 if ((*_cost_arcs)[source].value > value) {
325 (*_cost_arcs)[source].arc = arc;
326 (*_cost_arcs)[source].value = value;
330 level_stack.pop_back();
332 CostArc minimum = (*_cost_arcs)[nodes[0]];
333 for (int i = 1; i < int(nodes.size()); ++i) {
334 if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
335 minimum = (*_cost_arcs)[nodes[i]];
338 _arc_order->set(minimum.arc, _dual_variables.size());
339 DualVariable var(node_bottom, _dual_node_list.size(), minimum.value);
340 _dual_variables.push_back(var);
342 level.node_level = node_bottom;
343 for (int i = 0; i < int(nodes.size()); ++i) {
344 (*_cost_arcs)[nodes[i]].value -= minimum.value;
345 level.arcs.push_back((*_cost_arcs)[nodes[i]]);
346 (*_cost_arcs)[nodes[i]].arc = INVALID;
348 level_stack.push_back(level);
352 int bottom(Node node) {
353 int k = level_stack.size() - 1;
354 while (level_stack[k].node_level > (*_node_order)[node]) {
357 return level_stack[k].node_level;
360 void finalize(Arc arc) {
361 Node node = _digraph->target(arc);
362 _heap->push(node, (*_arc_order)[arc]);
363 _pred->set(node, arc);
364 while (!_heap->empty()) {
365 Node source = _heap->top();
367 _node_order->set(source, -1);
368 for (OutArcIt it(*_digraph, source); it != INVALID; ++it) {
369 if ((*_arc_order)[it] < 0) continue;
370 Node target = _digraph->target(it);
371 switch(_heap->state(target)) {
373 _heap->push(target, (*_arc_order)[it]);
374 _pred->set(target, it);
377 if ((*_arc_order)[it] < (*_heap)[target]) {
378 _heap->decrease(target, (*_arc_order)[it]);
379 _pred->set(target, it);
382 case Heap::POST_HEAP:
386 _arborescence->set((*_pred)[source], true);
393 /// \name Named template parameters
398 struct DefArborescenceMapTraits : public Traits {
399 typedef T ArborescenceMap;
400 static ArborescenceMap *createArborescenceMap(const Digraph &)
402 LEMON_ASSERT(false, "ArborescenceMap is not initialized");
403 return 0; // ignore warnings
407 /// \brief \ref named-templ-param "Named parameter" for
408 /// setting ArborescenceMap type
410 /// \ref named-templ-param "Named parameter" for setting
411 /// ArborescenceMap type
413 struct DefArborescenceMap
414 : public MinCostArborescence<Digraph, CostMap,
415 DefArborescenceMapTraits<T> > {
419 struct DefPredMapTraits : public Traits {
421 static PredMap *createPredMap(const Digraph &)
423 LEMON_ASSERT(false, "PredMap is not initialized");
427 /// \brief \ref named-templ-param "Named parameter" for
428 /// setting PredMap type
430 /// \ref named-templ-param "Named parameter" for setting
434 : public MinCostArborescence<Digraph, CostMap, DefPredMapTraits<T> > {
439 /// \brief Constructor.
441 /// \param digraph The digraph the algorithm will run on.
442 /// \param cost The cost map used by the algorithm.
443 MinCostArborescence(const Digraph& digraph, const CostMap& cost)
444 : _digraph(&digraph), _cost(&cost), _pred(0), local_pred(false),
445 _arborescence(0), local_arborescence(false),
446 _arc_order(0), _node_order(0), _cost_arcs(0),
447 _heap_cross_ref(0), _heap(0) {}
449 /// \brief Destructor.
450 ~MinCostArborescence() {
454 /// \brief Sets the arborescence map.
456 /// Sets the arborescence map.
457 /// \return <tt>(*this)</tt>
458 MinCostArborescence& arborescenceMap(ArborescenceMap& m) {
459 if (local_arborescence) {
460 delete _arborescence;
462 local_arborescence = false;
467 /// \brief Sets the arborescence map.
469 /// Sets the arborescence map.
470 /// \return <tt>(*this)</tt>
471 MinCostArborescence& predMap(PredMap& m) {
480 /// \name Query Functions
481 /// The result of the %MinCostArborescence algorithm can be obtained
482 /// using these functions.\n
483 /// Before the use of these functions,
484 /// either run() or start() must be called.
488 /// \brief Returns a reference to the arborescence map.
490 /// Returns a reference to the arborescence map.
491 const ArborescenceMap& arborescenceMap() const {
492 return *_arborescence;
495 /// \brief Returns true if the arc is in the arborescence.
497 /// Returns true if the arc is in the arborescence.
498 /// \param arc The arc of the digraph.
499 /// \pre \ref run() must be called before using this function.
500 bool arborescence(Arc arc) const {
501 return (*_pred)[_digraph->target(arc)] == arc;
504 /// \brief Returns a reference to the pred map.
506 /// Returns a reference to the pred map.
507 const PredMap& predMap() const {
511 /// \brief Returns the predecessor arc of the given node.
513 /// Returns the predecessor arc of the given node.
514 Arc pred(Node node) const {
515 return (*_pred)[node];
518 /// \brief Returns the cost of the arborescence.
520 /// Returns the cost of the arborescence.
521 Value arborescenceValue() const {
523 for (ArcIt it(*_digraph); it != INVALID; ++it) {
524 if (arborescence(it)) {
531 /// \brief Indicates that a node is reachable from the sources.
533 /// Indicates that a node is reachable from the sources.
534 bool reached(Node node) const {
535 return (*_node_order)[node] != -3;
538 /// \brief Indicates that a node is processed.
540 /// Indicates that a node is processed. The arborescence path exists
541 /// from the source to the given node.
542 bool processed(Node node) const {
543 return (*_node_order)[node] == -1;
546 /// \brief Returns the number of the dual variables in basis.
548 /// Returns the number of the dual variables in basis.
549 int dualNum() const {
550 return _dual_variables.size();
553 /// \brief Returns the value of the dual solution.
555 /// Returns the value of the dual solution. It should be
556 /// equal to the arborescence value.
557 Value dualValue() const {
559 for (int i = 0; i < int(_dual_variables.size()); ++i) {
560 sum += _dual_variables[i].value;
565 /// \brief Returns the number of the nodes in the dual variable.
567 /// Returns the number of the nodes in the dual variable.
568 int dualSize(int k) const {
569 return _dual_variables[k].end - _dual_variables[k].begin;
572 /// \brief Returns the value of the dual variable.
574 /// Returns the the value of the dual variable.
575 const Value& dualValue(int k) const {
576 return _dual_variables[k].value;
579 /// \brief Lemon iterator for get a dual variable.
581 /// Lemon iterator for get a dual variable. This class provides
582 /// a common style lemon iterator which gives back a subset of
587 /// \brief Constructor.
589 /// Constructor for get the nodeset of the variable.
590 DualIt(const MinCostArborescence& algorithm, int variable)
591 : _algorithm(&algorithm)
593 _index = _algorithm->_dual_variables[variable].begin;
594 _last = _algorithm->_dual_variables[variable].end;
597 /// \brief Conversion to node.
599 /// Conversion to node.
600 operator Node() const {
601 return _algorithm->_dual_node_list[_index];
604 /// \brief Increment operator.
606 /// Increment operator.
607 DualIt& operator++() {
612 /// \brief Validity checking
614 /// Checks whether the iterator is invalid.
615 bool operator==(Invalid) const {
616 return _index == _last;
619 /// \brief Validity checking
621 /// Checks whether the iterator is valid.
622 bool operator!=(Invalid) const {
623 return _index != _last;
627 const MinCostArborescence* _algorithm;
633 /// \name Execution control
634 /// The simplest way to execute the algorithm is to use
635 /// one of the member functions called \c run(...). \n
636 /// If you need more control on the execution,
637 /// first you must call \ref init(), then you can add several
638 /// source nodes with \ref addSource().
639 /// Finally \ref start() will perform the arborescence
644 /// \brief Initializes the internal data structures.
646 /// Initializes the internal data structures.
651 for (NodeIt it(*_digraph); it != INVALID; ++it) {
652 (*_cost_arcs)[it].arc = INVALID;
653 _node_order->set(it, -3);
654 _heap_cross_ref->set(it, Heap::PRE_HEAP);
655 _pred->set(it, INVALID);
657 for (ArcIt it(*_digraph); it != INVALID; ++it) {
658 _arborescence->set(it, false);
659 _arc_order->set(it, -1);
661 _dual_node_list.clear();
662 _dual_variables.clear();
665 /// \brief Adds a new source node.
667 /// Adds a new source node to the algorithm.
668 void addSource(Node source) {
669 std::vector<Node> nodes;
670 nodes.push_back(source);
671 while (!nodes.empty()) {
672 Node node = nodes.back();
674 for (OutArcIt it(*_digraph, node); it != INVALID; ++it) {
675 Node target = _digraph->target(it);
676 if ((*_node_order)[target] == -3) {
677 (*_node_order)[target] = -2;
678 nodes.push_back(target);
679 queue.push_back(target);
683 (*_node_order)[source] = -1;
686 /// \brief Processes the next node in the priority queue.
688 /// Processes the next node in the priority queue.
690 /// \return The processed node.
692 /// \warning The queue must not be empty!
693 Node processNextNode() {
694 Node node = queue.back();
696 if ((*_node_order)[node] == -2) {
697 Arc arc = prepare(node);
698 Node source = _digraph->source(arc);
699 while ((*_node_order)[source] != -1) {
700 if ((*_node_order)[source] >= 0) {
701 arc = contract(source);
703 arc = prepare(source);
705 source = _digraph->source(arc);
713 /// \brief Returns the number of the nodes to be processed.
715 /// Returns the number of the nodes to be processed.
716 int queueSize() const {
720 /// \brief Returns \c false if there are nodes to be processed.
722 /// Returns \c false if there are nodes to be processed.
723 bool emptyQueue() const {
724 return queue.empty();
727 /// \brief Executes the algorithm.
729 /// Executes the algorithm.
731 /// \pre init() must be called and at least one node should be added
732 /// with addSource() before using this function.
734 ///\note mca.start() is just a shortcut of the following code.
736 ///while (!mca.emptyQueue()) {
737 /// mca.processNextNode();
741 while (!emptyQueue()) {
746 /// \brief Runs %MinCostArborescence algorithm from node \c s.
748 /// This method runs the %MinCostArborescence algorithm from
749 /// a root node \c s.
751 /// \note mca.run(s) is just a shortcut of the following code.
754 /// mca.addSource(s);
757 void run(Node node) {
767 /// \ingroup spantree
769 /// \brief Function type interface for MinCostArborescence algorithm.
771 /// Function type interface for MinCostArborescence algorithm.
772 /// \param digraph The Digraph that the algorithm runs on.
773 /// \param cost The CostMap of the arcs.
774 /// \param source The source of the arborescence.
775 /// \retval arborescence The bool ArcMap which stores the arborescence.
776 /// \return The cost of the arborescence.
778 /// \sa MinCostArborescence
779 template <typename Digraph, typename CostMap, typename ArborescenceMap>
780 typename CostMap::Value minCostArborescence(const Digraph& digraph,
782 typename Digraph::Node source,
783 ArborescenceMap& arborescence) {
784 typename MinCostArborescence<Digraph, CostMap>
785 ::template DefArborescenceMap<ArborescenceMap>
786 ::Create mca(digraph, cost);
787 mca.arborescenceMap(arborescence);
789 return mca.arborescenceValue();