1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2009
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_SUURBALLE_H
20 #define LEMON_SUURBALLE_H
22 ///\ingroup shortest_path
24 ///\brief An algorithm for finding arc-disjoint paths between two
25 /// nodes having minimum total length.
29 #include <lemon/bin_heap.h>
30 #include <lemon/path.h>
31 #include <lemon/list_graph.h>
32 #include <lemon/dijkstra.h>
33 #include <lemon/maps.h>
37 /// \brief Default traits class of Suurballe algorithm.
39 /// Default traits class of Suurballe algorithm.
40 /// \tparam GR The digraph type the algorithm runs on.
41 /// \tparam LEN The type of the length map.
42 /// The default value is <tt>GR::ArcMap<int></tt>.
44 template <typename GR, typename LEN>
46 template < typename GR,
47 typename LEN = typename GR::template ArcMap<int> >
49 struct SuurballeDefaultTraits
51 /// The type of the digraph.
53 /// The type of the length map.
54 typedef LEN LengthMap;
55 /// The type of the lengths.
56 typedef typename LEN::Value Length;
57 /// The type of the flow map.
58 typedef typename GR::template ArcMap<int> FlowMap;
59 /// The type of the potential map.
60 typedef typename GR::template NodeMap<Length> PotentialMap;
62 /// \brief The path type
64 /// The type used for storing the found arc-disjoint paths.
65 /// It must conform to the \ref lemon::concepts::Path "Path" concept
66 /// and it must have an \c addBack() function.
67 typedef lemon::Path<Digraph> Path;
69 /// The cross reference type used for the heap.
70 typedef typename GR::template NodeMap<int> HeapCrossRef;
72 /// \brief The heap type used for internal Dijkstra computations.
74 /// The type of the heap used for internal Dijkstra computations.
75 /// It must conform to the \ref lemon::concepts::Heap "Heap" concept
76 /// and its priority type must be \c Length.
77 typedef BinHeap<Length, HeapCrossRef> Heap;
80 /// \addtogroup shortest_path
83 /// \brief Algorithm for finding arc-disjoint paths between two nodes
84 /// having minimum total length.
86 /// \ref lemon::Suurballe "Suurballe" implements an algorithm for
87 /// finding arc-disjoint paths having minimum total length (cost)
88 /// from a given source node to a given target node in a digraph.
90 /// Note that this problem is a special case of the \ref min_cost_flow
91 /// "minimum cost flow problem". This implementation is actually an
92 /// efficient specialized version of the \ref CapacityScaling
93 /// "successive shortest path" algorithm directly for this problem.
94 /// Therefore this class provides query functions for flow values and
95 /// node potentials (the dual solution) just like the minimum cost flow
98 /// \tparam GR The digraph type the algorithm runs on.
99 /// \tparam LEN The type of the length map.
100 /// The default value is <tt>GR::ArcMap<int></tt>.
102 /// \warning Length values should be \e non-negative.
104 /// \note For finding \e node-disjoint paths, this algorithm can be used
105 /// along with the \ref SplitNodes adaptor.
107 template <typename GR, typename LEN, typename TR>
109 template < typename GR,
110 typename LEN = typename GR::template ArcMap<int>,
111 typename TR = SuurballeDefaultTraits<GR, LEN> >
115 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
117 typedef ConstMap<Arc, int> ConstArcMap;
118 typedef typename GR::template NodeMap<Arc> PredMap;
122 /// The type of the digraph.
123 typedef typename TR::Digraph Digraph;
124 /// The type of the length map.
125 typedef typename TR::LengthMap LengthMap;
126 /// The type of the lengths.
127 typedef typename TR::Length Length;
129 /// The type of the flow map.
130 typedef typename TR::FlowMap FlowMap;
131 /// The type of the potential map.
132 typedef typename TR::PotentialMap PotentialMap;
133 /// The type of the path structures.
134 typedef typename TR::Path Path;
135 /// The cross reference type used for the heap.
136 typedef typename TR::HeapCrossRef HeapCrossRef;
137 /// The heap type used for internal Dijkstra computations.
138 typedef typename TR::Heap Heap;
140 /// The \ref SuurballeDefaultTraits "traits class" of the algorithm.
145 // ResidualDijkstra is a special implementation of the
146 // Dijkstra algorithm for finding shortest paths in the
147 // residual network with respect to the reduced arc lengths
148 // and modifying the node potentials according to the
149 // distance of the nodes.
150 class ResidualDijkstra
154 const Digraph &_graph;
155 const LengthMap &_length;
156 const FlowMap &_flow;
163 std::vector<Node> _proc_nodes;
168 ResidualDijkstra(Suurballe &srb) :
169 _graph(srb._graph), _length(srb._length),
170 _flow(*srb._flow), _pi(*srb._potential), _pred(srb._pred),
171 _s(srb._s), _t(srb._t), _dist(_graph) {}
173 // Run the algorithm and return true if a path is found
174 // from the source node to the target node.
176 return cnt == 0 ? startFirst() : start();
181 // Execute the algorithm for the first time (the flow and potential
182 // functions have to be identically zero).
184 HeapCrossRef heap_cross_ref(_graph, Heap::PRE_HEAP);
185 Heap heap(heap_cross_ref);
191 while (!heap.empty() && heap.top() != _t) {
192 Node u = heap.top(), v;
193 Length d = heap.prio(), dn;
194 _dist[u] = heap.prio();
195 _proc_nodes.push_back(u);
198 // Traverse outgoing arcs
199 for (OutArcIt e(_graph, u); e != INVALID; ++e) {
200 v = _graph.target(e);
201 switch(heap.state(v)) {
203 heap.push(v, d + _length[e]);
209 heap.decrease(v, dn);
213 case Heap::POST_HEAP:
218 if (heap.empty()) return false;
220 // Update potentials of processed nodes
221 Length t_dist = heap.prio();
222 for (int i = 0; i < int(_proc_nodes.size()); ++i)
223 _pi[_proc_nodes[i]] = _dist[_proc_nodes[i]] - t_dist;
227 // Execute the algorithm.
229 HeapCrossRef heap_cross_ref(_graph, Heap::PRE_HEAP);
230 Heap heap(heap_cross_ref);
236 while (!heap.empty() && heap.top() != _t) {
237 Node u = heap.top(), v;
238 Length d = heap.prio() + _pi[u], dn;
239 _dist[u] = heap.prio();
240 _proc_nodes.push_back(u);
243 // Traverse outgoing arcs
244 for (OutArcIt e(_graph, u); e != INVALID; ++e) {
246 v = _graph.target(e);
247 switch(heap.state(v)) {
249 heap.push(v, d + _length[e] - _pi[v]);
253 dn = d + _length[e] - _pi[v];
255 heap.decrease(v, dn);
259 case Heap::POST_HEAP:
265 // Traverse incoming arcs
266 for (InArcIt e(_graph, u); e != INVALID; ++e) {
268 v = _graph.source(e);
269 switch(heap.state(v)) {
271 heap.push(v, d - _length[e] - _pi[v]);
275 dn = d - _length[e] - _pi[v];
277 heap.decrease(v, dn);
281 case Heap::POST_HEAP:
287 if (heap.empty()) return false;
289 // Update potentials of processed nodes
290 Length t_dist = heap.prio();
291 for (int i = 0; i < int(_proc_nodes.size()); ++i)
292 _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - t_dist;
296 }; //class ResidualDijkstra
300 /// \name Named Template Parameters
303 template <typename T>
304 struct SetFlowMapTraits : public Traits {
308 /// \brief \ref named-templ-param "Named parameter" for setting
311 /// \ref named-templ-param "Named parameter" for setting
313 template <typename T>
315 : public Suurballe<GR, LEN, SetFlowMapTraits<T> > {
316 typedef Suurballe<GR, LEN, SetFlowMapTraits<T> > Create;
319 template <typename T>
320 struct SetPotentialMapTraits : public Traits {
321 typedef T PotentialMap;
324 /// \brief \ref named-templ-param "Named parameter" for setting
325 /// \c PotentialMap type.
327 /// \ref named-templ-param "Named parameter" for setting
328 /// \c PotentialMap type.
329 template <typename T>
330 struct SetPotentialMap
331 : public Suurballe<GR, LEN, SetPotentialMapTraits<T> > {
332 typedef Suurballe<GR, LEN, SetPotentialMapTraits<T> > Create;
335 template <typename T>
336 struct SetPathTraits : public Traits {
340 /// \brief \ref named-templ-param "Named parameter" for setting
343 /// \ref named-templ-param "Named parameter" for setting \c %Path type.
344 /// It must conform to the \ref lemon::concepts::Path "Path" concept
345 /// and it must have an \c addBack() function.
346 template <typename T>
348 : public Suurballe<GR, LEN, SetPathTraits<T> > {
349 typedef Suurballe<GR, LEN, SetPathTraits<T> > Create;
352 template <typename H, typename CR>
353 struct SetHeapTraits : public Traits {
355 typedef CR HeapCrossRef;
358 /// \brief \ref named-templ-param "Named parameter" for setting
359 /// \c Heap and \c HeapCrossRef types.
361 /// \ref named-templ-param "Named parameter" for setting \c Heap
362 /// and \c HeapCrossRef types with automatic allocation.
363 /// They will be used for internal Dijkstra computations.
364 /// The heap type must conform to the \ref lemon::concepts::Heap "Heap"
365 /// concept and its priority type must be \c Length.
366 template <typename H,
367 typename CR = typename Digraph::template NodeMap<int> >
369 : public Suurballe<GR, LEN, SetHeapTraits<H, CR> > {
370 typedef Suurballe<GR, LEN, SetHeapTraits<H, CR> > Create;
377 // The digraph the algorithm runs on
378 const Digraph &_graph;
380 const LengthMap &_length;
382 // Arc map of the current flow
385 // Node map of the current potentials
386 PotentialMap *_potential;
387 bool _local_potential;
394 // Container to store the found paths
395 std::vector<Path> _paths;
401 // Data for full init
402 PotentialMap *_init_dist;
412 /// \brief Constructor.
416 /// \param graph The digraph the algorithm runs on.
417 /// \param length The length (cost) values of the arcs.
418 Suurballe( const Digraph &graph,
419 const LengthMap &length ) :
420 _graph(graph), _length(length), _flow(0), _local_flow(false),
421 _potential(0), _local_potential(false), _pred(graph),
422 _init_dist(0), _init_pred(0)
427 if (_local_flow) delete _flow;
428 if (_local_potential) delete _potential;
433 /// \brief Set the flow map.
435 /// This function sets the flow map.
436 /// If it is not used before calling \ref run() or \ref init(),
437 /// an instance will be allocated automatically. The destructor
438 /// deallocates this automatically allocated map, of course.
440 /// The found flow contains only 0 and 1 values, since it is the
441 /// union of the found arc-disjoint paths.
443 /// \return <tt>(*this)</tt>
444 Suurballe& flowMap(FlowMap &map) {
453 /// \brief Set the potential map.
455 /// This function sets the potential map.
456 /// If it is not used before calling \ref run() or \ref init(),
457 /// an instance will be allocated automatically. The destructor
458 /// deallocates this automatically allocated map, of course.
460 /// The node potentials provide the dual solution of the underlying
461 /// \ref min_cost_flow "minimum cost flow problem".
463 /// \return <tt>(*this)</tt>
464 Suurballe& potentialMap(PotentialMap &map) {
465 if (_local_potential) {
467 _local_potential = false;
473 /// \name Execution Control
474 /// The simplest way to execute the algorithm is to call the run()
476 /// If you need to execute the algorithm many times using the same
477 /// source node, then you may call fullInit() once and start()
478 /// for each target node.\n
479 /// If you only need the flow that is the union of the found
480 /// arc-disjoint paths, then you may call findFlow() instead of
485 /// \brief Run the algorithm.
487 /// This function runs the algorithm.
489 /// \param s The source node.
490 /// \param t The target node.
491 /// \param k The number of paths to be found.
493 /// \return \c k if there are at least \c k arc-disjoint paths from
494 /// \c s to \c t in the digraph. Otherwise it returns the number of
495 /// arc-disjoint paths found.
497 /// \note Apart from the return value, <tt>s.run(s, t, k)</tt> is
498 /// just a shortcut of the following code.
503 int run(const Node& s, const Node& t, int k = 2) {
509 /// \brief Initialize the algorithm.
511 /// This function initializes the algorithm with the given source node.
513 /// \param s The source node.
514 void init(const Node& s) {
519 _flow = new FlowMap(_graph);
523 _potential = new PotentialMap(_graph);
524 _local_potential = true;
529 /// \brief Initialize the algorithm and perform Dijkstra.
531 /// This function initializes the algorithm and performs a full
532 /// Dijkstra search from the given source node. It makes consecutive
533 /// executions of \ref start() "start(t, k)" faster, since they
534 /// have to perform %Dijkstra only k-1 times.
536 /// This initialization is usually worth using instead of \ref init()
537 /// if the algorithm is executed many times using the same source node.
539 /// \param s The source node.
540 void fullInit(const Node& s) {
544 _init_dist = new PotentialMap(_graph);
547 _init_pred = new PredMap(_graph);
550 // Run a full Dijkstra
551 typename Dijkstra<Digraph, LengthMap>
552 ::template SetStandardHeap<Heap>
553 ::template SetDistMap<PotentialMap>
554 ::template SetPredMap<PredMap>
555 ::Create dijk(_graph, _length);
556 dijk.distMap(*_init_dist).predMap(*_init_pred);
562 /// \brief Execute the algorithm.
564 /// This function executes the algorithm.
566 /// \param t The target node.
567 /// \param k The number of paths to be found.
569 /// \return \c k if there are at least \c k arc-disjoint paths from
570 /// \c s to \c t in the digraph. Otherwise it returns the number of
571 /// arc-disjoint paths found.
573 /// \note Apart from the return value, <tt>s.start(t, k)</tt> is
574 /// just a shortcut of the following code.
576 /// s.findFlow(t, k);
579 int start(const Node& t, int k = 2) {
585 /// \brief Execute the algorithm to find an optimal flow.
587 /// This function executes the successive shortest path algorithm to
588 /// find a minimum cost flow, which is the union of \c k (or less)
589 /// arc-disjoint paths.
591 /// \param t The target node.
592 /// \param k The number of paths to be found.
594 /// \return \c k if there are at least \c k arc-disjoint paths from
595 /// the source node to the given node \c t in the digraph.
596 /// Otherwise it returns the number of arc-disjoint paths found.
598 /// \pre \ref init() must be called before using this function.
599 int findFlow(const Node& t, int k = 2) {
601 ResidualDijkstra dijkstra(*this);
604 for (ArcIt e(_graph); e != INVALID; ++e) {
608 for (NodeIt n(_graph); n != INVALID; ++n) {
609 (*_potential)[n] = (*_init_dist)[n];
613 while ((e = (*_init_pred)[u]) != INVALID) {
615 u = _graph.source(e);
619 for (NodeIt n(_graph); n != INVALID; ++n) {
620 (*_potential)[n] = 0;
625 // Find shortest paths
626 while (_path_num < k) {
628 if (!dijkstra.run(_path_num)) break;
631 // Set the flow along the found shortest path
634 while ((e = _pred[u]) != INVALID) {
635 if (u == _graph.target(e)) {
637 u = _graph.source(e);
640 u = _graph.target(e);
647 /// \brief Compute the paths from the flow.
649 /// This function computes arc-disjoint paths from the found minimum
650 /// cost flow, which is the union of them.
652 /// \pre \ref init() and \ref findFlow() must be called before using
655 FlowMap res_flow(_graph);
656 for(ArcIt a(_graph); a != INVALID; ++a) res_flow[a] = (*_flow)[a];
659 _paths.resize(_path_num);
660 for (int i = 0; i < _path_num; ++i) {
663 OutArcIt e(_graph, n);
664 for ( ; res_flow[e] == 0; ++e) ;
665 n = _graph.target(e);
666 _paths[i].addBack(e);
674 /// \name Query Functions
675 /// The results of the algorithm can be obtained using these
677 /// \n The algorithm should be executed before using them.
681 /// \brief Return the total length of the found paths.
683 /// This function returns the total length of the found paths, i.e.
684 /// the total cost of the found flow.
685 /// The complexity of the function is O(e).
687 /// \pre \ref run() or \ref findFlow() must be called before using
689 Length totalLength() const {
691 for (ArcIt e(_graph); e != INVALID; ++e)
692 c += (*_flow)[e] * _length[e];
696 /// \brief Return the flow value on the given arc.
698 /// This function returns the flow value on the given arc.
699 /// It is \c 1 if the arc is involved in one of the found arc-disjoint
700 /// paths, otherwise it is \c 0.
702 /// \pre \ref run() or \ref findFlow() must be called before using
704 int flow(const Arc& arc) const {
705 return (*_flow)[arc];
708 /// \brief Return a const reference to an arc map storing the
711 /// This function returns a const reference to an arc map storing
712 /// the flow that is the union of the found arc-disjoint paths.
714 /// \pre \ref run() or \ref findFlow() must be called before using
716 const FlowMap& flowMap() const {
720 /// \brief Return the potential of the given node.
722 /// This function returns the potential of the given node.
723 /// The node potentials provide the dual solution of the
724 /// underlying \ref min_cost_flow "minimum cost flow problem".
726 /// \pre \ref run() or \ref findFlow() must be called before using
728 Length potential(const Node& node) const {
729 return (*_potential)[node];
732 /// \brief Return a const reference to a node map storing the
733 /// found potentials (the dual solution).
735 /// This function returns a const reference to a node map storing
736 /// the found potentials that provide the dual solution of the
737 /// underlying \ref min_cost_flow "minimum cost flow problem".
739 /// \pre \ref run() or \ref findFlow() must be called before using
741 const PotentialMap& potentialMap() const {
745 /// \brief Return the number of the found paths.
747 /// This function returns the number of the found paths.
749 /// \pre \ref run() or \ref findFlow() must be called before using
751 int pathNum() const {
755 /// \brief Return a const reference to the specified path.
757 /// This function returns a const reference to the specified path.
759 /// \param i The function returns the <tt>i</tt>-th path.
760 /// \c i must be between \c 0 and <tt>%pathNum()-1</tt>.
762 /// \pre \ref run() or \ref findPaths() must be called before using
764 const Path& path(int i) const {
776 #endif //LEMON_SUURBALLE_H