1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2013
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_MAX_CARDINALITY_SEARCH_H
20 #define LEMON_MAX_CARDINALITY_SEARCH_H
25 /// \brief Maximum cardinality search in undirected digraphs.
27 #include <lemon/bin_heap.h>
28 #include <lemon/bucket_heap.h>
30 #include <lemon/error.h>
31 #include <lemon/maps.h>
37 /// \brief Default traits class of MaxCardinalitySearch class.
39 /// Default traits class of MaxCardinalitySearch class.
40 /// \param Digraph Digraph type.
41 /// \param CapacityMap Type of capacity map.
42 template <typename GR, typename CAP>
43 struct MaxCardinalitySearchDefaultTraits {
44 /// The digraph type the algorithm runs on.
47 template <typename CM>
48 struct CapMapSelector {
50 typedef CM CapacityMap;
52 static CapacityMap *createCapacityMap(const Digraph& g) {
53 return new CapacityMap(g);
57 template <typename CM>
58 struct CapMapSelector<ConstMap<CM, Const<int, 1> > > {
60 typedef ConstMap<CM, Const<int, 1> > CapacityMap;
62 static CapacityMap *createCapacityMap(const Digraph&) {
63 return new CapacityMap;
67 /// \brief The type of the map that stores the arc capacities.
69 /// The type of the map that stores the arc capacities.
70 /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
71 typedef typename CapMapSelector<CAP>::CapacityMap CapacityMap;
73 /// \brief The type of the capacity of the arcs.
74 typedef typename CapacityMap::Value Value;
76 /// \brief Instantiates a CapacityMap.
78 /// This function instantiates a \ref CapacityMap.
79 /// \param digraph is the digraph, to which we would like to define
81 static CapacityMap *createCapacityMap(const Digraph& digraph) {
82 return CapMapSelector<CapacityMap>::createCapacityMap(digraph);
85 /// \brief The cross reference type used by heap.
87 /// The cross reference type used by heap.
88 /// Usually it is \c Digraph::NodeMap<int>.
89 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
91 /// \brief Instantiates a HeapCrossRef.
93 /// This function instantiates a \ref HeapCrossRef.
94 /// \param digraph is the digraph, to which we would like to define the
96 static HeapCrossRef *createHeapCrossRef(const Digraph &digraph) {
97 return new HeapCrossRef(digraph);
100 template <typename CapacityMap>
101 struct HeapSelector {
102 template <typename Value, typename Ref>
104 typedef BinHeap<Value, Ref, std::greater<Value> > Heap;
108 template <typename CapacityKey>
109 struct HeapSelector<ConstMap<CapacityKey, Const<int, 1> > > {
110 template <typename Value, typename Ref>
112 typedef BucketHeap<Ref, false > Heap;
116 /// \brief The heap type used by MaxCardinalitySearch algorithm.
118 /// The heap type used by MaxCardinalitySearch algorithm. It should
119 /// maximalize the priorities. The default heap type is
120 /// the \ref BinHeap, but it is specialized when the
121 /// CapacityMap is ConstMap<Digraph::Node, Const<int, 1> >
124 /// \sa MaxCardinalitySearch
125 typedef typename HeapSelector<CapacityMap>
126 ::template Selector<Value, HeapCrossRef>
129 /// \brief Instantiates a Heap.
131 /// This function instantiates a \ref Heap.
132 /// \param crossref The cross reference of the heap.
133 static Heap *createHeap(HeapCrossRef& crossref) {
134 return new Heap(crossref);
137 /// \brief The type of the map that stores whether a node is processed.
139 /// The type of the map that stores whether a node is processed.
140 /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
141 /// By default it is a NullMap.
142 typedef NullMap<typename Digraph::Node, bool> ProcessedMap;
144 /// \brief Instantiates a ProcessedMap.
146 /// This function instantiates a \ref ProcessedMap.
147 /// \param digraph is the digraph, to which
148 /// we would like to define the \ref ProcessedMap
150 static ProcessedMap *createProcessedMap(const Digraph &digraph)
152 static ProcessedMap *createProcessedMap(const Digraph &)
155 return new ProcessedMap();
158 /// \brief The type of the map that stores the cardinalities of the nodes.
160 /// The type of the map that stores the cardinalities of the nodes.
161 /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
162 typedef typename Digraph::template NodeMap<Value> CardinalityMap;
164 /// \brief Instantiates a CardinalityMap.
166 /// This function instantiates a \ref CardinalityMap.
167 /// \param digraph is the digraph, to which we would like to define the \ref
169 static CardinalityMap *createCardinalityMap(const Digraph &digraph) {
170 return new CardinalityMap(digraph);
178 /// \brief Maximum Cardinality Search algorithm class.
180 /// This class provides an efficient implementation of Maximum Cardinality
181 /// Search algorithm. The maximum cardinality search first chooses any
182 /// node of the digraph. Then every time it chooses one unprocessed node
183 /// with maximum cardinality, i.e the sum of capacities on out arcs to the nodes
184 /// which were previusly processed.
185 /// If there is a cut in the digraph the algorithm should choose
186 /// again any unprocessed node of the digraph.
188 /// The arc capacities are passed to the algorithm using a
189 /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
190 /// kind of capacity.
192 /// The type of the capacity is determined by the \ref
193 /// concepts::ReadMap::Value "Value" of the capacity map.
195 /// It is also possible to change the underlying priority heap.
198 /// \param GR The digraph type the algorithm runs on. The value of
199 /// Digraph is not used directly by the search algorithm, it
200 /// is only passed to \ref MaxCardinalitySearchDefaultTraits.
201 /// \param CAP This read-only ArcMap determines the capacities of
202 /// the arcs. It is read once for each arc, so the map may involve in
203 /// relatively time consuming process to compute the arc capacity if
204 /// it is necessary. The default map type is \ref
205 /// ConstMap "ConstMap<concepts::Digraph::Arc, Const<int,1> >". The value
206 /// of CapacityMap is not used directly by search algorithm, it is only
207 /// passed to \ref MaxCardinalitySearchDefaultTraits.
208 /// \param TR Traits class to set various data types used by the
209 /// algorithm. The default traits class is
210 /// \ref MaxCardinalitySearchDefaultTraits
211 /// "MaxCardinalitySearchDefaultTraits<GR, CAP>".
212 /// See \ref MaxCardinalitySearchDefaultTraits
213 /// for the documentation of a MaxCardinalitySearch traits class.
216 template <typename GR, typename CAP, typename TR>
218 template <typename GR, typename CAP =
219 ConstMap<typename GR::Arc, Const<int,1> >,
221 MaxCardinalitySearchDefaultTraits<GR, CAP> >
223 class MaxCardinalitySearch {
227 ///The type of the underlying digraph.
228 typedef typename Traits::Digraph Digraph;
230 ///The type of the capacity of the arcs.
231 typedef typename Traits::CapacityMap::Value Value;
232 ///The type of the map that stores the arc capacities.
233 typedef typename Traits::CapacityMap CapacityMap;
234 ///The type of the map indicating if a node is processed.
235 typedef typename Traits::ProcessedMap ProcessedMap;
236 ///The type of the map that stores the cardinalities of the nodes.
237 typedef typename Traits::CardinalityMap CardinalityMap;
238 ///The cross reference type used for the current heap.
239 typedef typename Traits::HeapCrossRef HeapCrossRef;
240 ///The heap type used by the algorithm. It maximizes the priorities.
241 typedef typename Traits::Heap Heap;
243 // Pointer to the underlying digraph.
244 const Digraph *_graph;
245 // Pointer to the capacity map
246 const CapacityMap *_capacity;
247 // Indicates if \ref _capacity is locally allocated (\c true) or not.
249 // Pointer to the map of cardinality.
250 CardinalityMap *_cardinality;
251 // Indicates if \ref _cardinality is locally allocated (\c true) or not.
252 bool local_cardinality;
253 // Pointer to the map of processed status of the nodes.
254 ProcessedMap *_processed;
255 // Indicates if \ref _processed is locally allocated (\c true) or not.
256 bool local_processed;
257 // Pointer to the heap cross references.
258 HeapCrossRef *_heap_cross_ref;
259 // Indicates if \ref _heap_cross_ref is locally allocated (\c true) or not.
260 bool local_heap_cross_ref;
261 // Pointer to the heap.
263 // Indicates if \ref _heap is locally allocated (\c true) or not.
268 typedef MaxCardinalitySearch Create;
270 ///\name Named template parameters
275 struct DefCapacityMapTraits : public Traits {
276 typedef T CapacityMap;
277 static CapacityMap *createCapacityMap(const Digraph &) {
278 LEMON_ASSERT(false,"Uninitialized parameter.");
282 /// \brief \ref named-templ-param "Named parameter" for setting
285 /// \ref named-templ-param "Named parameter" for setting CapacityMap type
286 /// for the algorithm.
288 struct SetCapacityMap
289 : public MaxCardinalitySearch<Digraph, CapacityMap,
290 DefCapacityMapTraits<T> > {
291 typedef MaxCardinalitySearch<Digraph, CapacityMap,
292 DefCapacityMapTraits<T> > Create;
296 struct DefCardinalityMapTraits : public Traits {
297 typedef T CardinalityMap;
298 static CardinalityMap *createCardinalityMap(const Digraph &)
300 LEMON_ASSERT(false,"Uninitialized parameter.");
304 /// \brief \ref named-templ-param "Named parameter" for setting
305 /// CardinalityMap type
307 /// \ref named-templ-param "Named parameter" for setting CardinalityMap
308 /// type for the algorithm.
310 struct SetCardinalityMap
311 : public MaxCardinalitySearch<Digraph, CapacityMap,
312 DefCardinalityMapTraits<T> > {
313 typedef MaxCardinalitySearch<Digraph, CapacityMap,
314 DefCardinalityMapTraits<T> > Create;
318 struct DefProcessedMapTraits : public Traits {
319 typedef T ProcessedMap;
320 static ProcessedMap *createProcessedMap(const Digraph &) {
321 LEMON_ASSERT(false,"Uninitialized parameter.");
325 /// \brief \ref named-templ-param "Named parameter" for setting
326 /// ProcessedMap type
328 /// \ref named-templ-param "Named parameter" for setting ProcessedMap type
329 /// for the algorithm.
331 struct SetProcessedMap
332 : public MaxCardinalitySearch<Digraph, CapacityMap,
333 DefProcessedMapTraits<T> > {
334 typedef MaxCardinalitySearch<Digraph, CapacityMap,
335 DefProcessedMapTraits<T> > Create;
338 template <class H, class CR>
339 struct DefHeapTraits : public Traits {
340 typedef CR HeapCrossRef;
342 static HeapCrossRef *createHeapCrossRef(const Digraph &) {
343 LEMON_ASSERT(false,"Uninitialized parameter.");
346 static Heap *createHeap(HeapCrossRef &) {
347 LEMON_ASSERT(false,"Uninitialized parameter.");
351 /// \brief \ref named-templ-param "Named parameter" for setting heap
352 /// and cross reference type
354 /// \ref named-templ-param "Named parameter" for setting heap and cross
355 /// reference type for the algorithm.
356 template <class H, class CR = typename Digraph::template NodeMap<int> >
358 : public MaxCardinalitySearch<Digraph, CapacityMap,
359 DefHeapTraits<H, CR> > {
360 typedef MaxCardinalitySearch< Digraph, CapacityMap,
361 DefHeapTraits<H, CR> > Create;
364 template <class H, class CR>
365 struct DefStandardHeapTraits : public Traits {
366 typedef CR HeapCrossRef;
368 static HeapCrossRef *createHeapCrossRef(const Digraph &digraph) {
369 return new HeapCrossRef(digraph);
371 static Heap *createHeap(HeapCrossRef &crossref) {
372 return new Heap(crossref);
376 /// \brief \ref named-templ-param "Named parameter" for setting heap and
377 /// cross reference type with automatic allocation
379 /// \ref named-templ-param "Named parameter" for setting heap and cross
380 /// reference type. It can allocate the heap and the cross reference
381 /// object if the cross reference's constructor waits for the digraph as
382 /// parameter and the heap's constructor waits for the cross reference.
383 template <class H, class CR = typename Digraph::template NodeMap<int> >
384 struct SetStandardHeap
385 : public MaxCardinalitySearch<Digraph, CapacityMap,
386 DefStandardHeapTraits<H, CR> > {
387 typedef MaxCardinalitySearch<Digraph, CapacityMap,
388 DefStandardHeapTraits<H, CR> >
397 MaxCardinalitySearch() {}
401 /// \brief Constructor.
403 ///\param digraph the digraph the algorithm will run on.
404 ///\param capacity the capacity map used by the algorithm.
405 MaxCardinalitySearch(const Digraph& digraph,
406 const CapacityMap& capacity) :
408 _capacity(&capacity), local_capacity(false),
409 _cardinality(0), local_cardinality(false),
410 _processed(0), local_processed(false),
411 _heap_cross_ref(0), local_heap_cross_ref(false),
412 _heap(0), local_heap(false)
415 /// \brief Constructor.
417 ///\param digraph the digraph the algorithm will run on.
419 ///A constant 1 capacity map will be allocated.
420 MaxCardinalitySearch(const Digraph& digraph) :
422 _capacity(0), local_capacity(false),
423 _cardinality(0), local_cardinality(false),
424 _processed(0), local_processed(false),
425 _heap_cross_ref(0), local_heap_cross_ref(false),
426 _heap(0), local_heap(false)
429 /// \brief Destructor.
430 ~MaxCardinalitySearch() {
431 if(local_capacity) delete _capacity;
432 if(local_cardinality) delete _cardinality;
433 if(local_processed) delete _processed;
434 if(local_heap_cross_ref) delete _heap_cross_ref;
435 if(local_heap) delete _heap;
438 /// \brief Sets the capacity map.
440 /// Sets the capacity map.
441 /// \return <tt> (*this) </tt>
442 MaxCardinalitySearch &capacityMap(const CapacityMap &m) {
443 if (local_capacity) {
445 local_capacity=false;
451 /// \brief Returns a const reference to the capacity map.
453 /// Returns a const reference to the capacity map used by
455 const CapacityMap &capacityMap() const {
459 /// \brief Sets the map storing the cardinalities calculated by the
462 /// Sets the map storing the cardinalities calculated by the algorithm.
463 /// If you don't use this function before calling \ref run(),
464 /// it will allocate one. The destuctor deallocates this
465 /// automatically allocated map, of course.
466 /// \return <tt> (*this) </tt>
467 MaxCardinalitySearch &cardinalityMap(CardinalityMap &m) {
468 if(local_cardinality) {
470 local_cardinality=false;
476 /// \brief Sets the map storing the processed nodes.
478 /// Sets the map storing the processed nodes.
479 /// If you don't use this function before calling \ref run(),
480 /// it will allocate one. The destuctor deallocates this
481 /// automatically allocated map, of course.
482 /// \return <tt> (*this) </tt>
483 MaxCardinalitySearch &processedMap(ProcessedMap &m)
485 if(local_processed) {
487 local_processed=false;
493 /// \brief Returns a const reference to the cardinality map.
495 /// Returns a const reference to the cardinality map used by
497 const ProcessedMap &processedMap() const {
501 /// \brief Sets the heap and the cross reference used by algorithm.
503 /// Sets the heap and the cross reference used by algorithm.
504 /// If you don't use this function before calling \ref run(),
505 /// it will allocate one. The destuctor deallocates this
506 /// automatically allocated map, of course.
507 /// \return <tt> (*this) </tt>
508 MaxCardinalitySearch &heap(Heap& hp, HeapCrossRef &cr) {
509 if(local_heap_cross_ref) {
510 delete _heap_cross_ref;
511 local_heap_cross_ref = false;
513 _heap_cross_ref = &cr;
522 /// \brief Returns a const reference to the heap.
524 /// Returns a const reference to the heap used by
526 const Heap &heap() const {
530 /// \brief Returns a const reference to the cross reference.
532 /// Returns a const reference to the cross reference
534 const HeapCrossRef &heapCrossRef() const {
535 return *_heap_cross_ref;
540 typedef typename Digraph::Node Node;
541 typedef typename Digraph::NodeIt NodeIt;
542 typedef typename Digraph::Arc Arc;
543 typedef typename Digraph::InArcIt InArcIt;
547 local_capacity = true;
548 _capacity = Traits::createCapacityMap(*_graph);
551 local_cardinality = true;
552 _cardinality = Traits::createCardinalityMap(*_graph);
555 local_processed = true;
556 _processed = Traits::createProcessedMap(*_graph);
558 if (!_heap_cross_ref) {
559 local_heap_cross_ref = true;
560 _heap_cross_ref = Traits::createHeapCrossRef(*_graph);
564 _heap = Traits::createHeap(*_heap_cross_ref);
568 void finalizeNodeData(Node node, Value capacity) {
569 _processed->set(node, true);
570 _cardinality->set(node, capacity);
574 /// \name Execution control
575 /// The simplest way to execute the algorithm is to use
576 /// one of the member functions called \ref run().
578 /// If you need more control on the execution,
579 /// first you must call \ref init(), then you can add several source nodes
580 /// with \ref addSource().
581 /// Finally \ref start() will perform the computation.
585 /// \brief Initializes the internal data structures.
587 /// Initializes the internal data structures, and clears the heap.
591 for (NodeIt it(*_graph) ; it != INVALID ; ++it) {
592 _processed->set(it, false);
593 _heap_cross_ref->set(it, Heap::PRE_HEAP);
597 /// \brief Adds a new source node.
599 /// Adds a new source node to the priority heap.
601 /// It checks if the node has not yet been added to the heap.
602 void addSource(Node source, Value capacity = 0) {
603 if(_heap->state(source) == Heap::PRE_HEAP) {
604 _heap->push(source, capacity);
608 /// \brief Processes the next node in the priority heap
610 /// Processes the next node in the priority heap.
612 /// \return The processed node.
614 /// \warning The priority heap must not be empty!
615 Node processNextNode() {
616 Node node = _heap->top();
617 finalizeNodeData(node, _heap->prio());
620 for (InArcIt it(*_graph, node); it != INVALID; ++it) {
621 Node source = _graph->source(it);
622 switch (_heap->state(source)) {
624 _heap->push(source, (*_capacity)[it]);
627 _heap->decrease(source, (*_heap)[source] + (*_capacity)[it]);
629 case Heap::POST_HEAP:
636 /// \brief Next node to be processed.
638 /// Next node to be processed.
640 /// \return The next node to be processed or INVALID if the
641 /// priority heap is empty.
643 return !_heap->empty() ? _heap->top() : INVALID;
646 /// \brief Returns \c false if there are nodes
647 /// to be processed in the priority heap
649 /// Returns \c false if there are nodes
650 /// to be processed in the priority heap
651 bool emptyQueue() { return _heap->empty(); }
652 /// \brief Returns the number of the nodes to be processed
653 /// in the priority heap
655 /// Returns the number of the nodes to be processed in the priority heap
656 int emptySize() { return _heap->size(); }
658 /// \brief Executes the algorithm.
660 /// Executes the algorithm.
662 ///\pre init() must be called and at least one node should be added
663 /// with addSource() before using this function.
665 /// This method runs the Maximum Cardinality Search algorithm from the
668 while ( !_heap->empty() ) processNextNode();
671 /// \brief Executes the algorithm until \c dest is reached.
673 /// Executes the algorithm until \c dest is reached.
675 /// \pre init() must be called and at least one node should be added
676 /// with addSource() before using this function.
678 /// This method runs the %MaxCardinalitySearch algorithm from the source
680 void start(Node dest) {
681 while ( !_heap->empty() && _heap->top()!=dest ) processNextNode();
682 if ( !_heap->empty() ) finalizeNodeData(_heap->top(), _heap->prio());
685 /// \brief Executes the algorithm until a condition is met.
687 /// Executes the algorithm until a condition is met.
689 /// \pre init() must be called and at least one node should be added
690 /// with addSource() before using this function.
692 /// \param nm must be a bool (or convertible) node map. The algorithm
693 /// will stop when it reaches a node \c v with <tt>nm[v]==true</tt>.
694 template <typename NodeBoolMap>
695 void start(const NodeBoolMap &nm) {
696 while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
697 if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio());
700 /// \brief Runs the maximum cardinality search algorithm from node \c s.
702 /// This method runs the %MaxCardinalitySearch algorithm from a root
705 ///\note d.run(s) is just a shortcut of the following code.
717 /// \brief Runs the maximum cardinality search algorithm for the
720 /// This method runs the %MaxCardinalitySearch algorithm from all
721 /// unprocessed node of the digraph.
723 ///\note d.run(s) is just a shortcut of the following code.
726 /// for (NodeIt it(digraph); it != INVALID; ++it) {
727 /// if (!d.reached(it)) {
735 for (NodeIt it(*_graph); it != INVALID; ++it) {
745 /// \name Query Functions
746 /// The results of the maximum cardinality search algorithm can be
747 /// obtained using these functions.
749 /// Before the use of these functions, either run() or start() must be
754 /// \brief The cardinality of a node.
756 /// Returns the cardinality of a node.
757 /// \pre \ref run() must be called before using this function.
758 /// \warning If node \c v in unreachable from the root the return value
759 /// of this funcion is undefined.
760 Value cardinality(Node node) const { return (*_cardinality)[node]; }
762 /// \brief The current cardinality of a node.
764 /// Returns the current cardinality of a node.
765 /// \pre the given node should be reached but not processed
766 Value currentCardinality(Node node) const { return (*_heap)[node]; }
768 /// \brief Returns a reference to the NodeMap of cardinalities.
770 /// Returns a reference to the NodeMap of cardinalities. \pre \ref run()
771 /// must be called before using this function.
772 const CardinalityMap &cardinalityMap() const { return *_cardinality;}
774 /// \brief Checks if a node is reachable from the root.
776 /// Returns \c true if \c v is reachable from the root.
777 /// \warning The source nodes are initated as unreached.
778 /// \pre \ref run() must be called before using this function.
779 bool reached(Node v) { return (*_heap_cross_ref)[v] != Heap::PRE_HEAP; }
781 /// \brief Checks if a node is processed.
783 /// Returns \c true if \c v is processed, i.e. the shortest
784 /// path to \c v has already found.
785 /// \pre \ref run() must be called before using this function.
786 bool processed(Node v) { return (*_heap_cross_ref)[v] == Heap::POST_HEAP; }