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 /// \addtogroup shortest_path
40 /// \brief Algorithm for finding arc-disjoint paths between two nodes
41 /// having minimum total length.
43 /// \ref lemon::Suurballe "Suurballe" implements an algorithm for
44 /// finding arc-disjoint paths having minimum total length (cost)
45 /// from a given source node to a given target node in a digraph.
47 /// Note that this problem is a special case of the \ref min_cost_flow
48 /// "minimum cost flow problem". This implementation is actually an
49 /// efficient specialized version of the \ref CapacityScaling
50 /// "successive shortest path" algorithm directly for this problem.
51 /// Therefore this class provides query functions for flow values and
52 /// node potentials (the dual solution) just like the minimum cost flow
55 /// \tparam GR The digraph type the algorithm runs on.
56 /// \tparam LEN The type of the length map.
57 /// The default value is <tt>GR::ArcMap<int></tt>.
59 /// \warning Length values should be \e non-negative.
61 /// \note For finding \e node-disjoint paths, this algorithm can be used
62 /// along with the \ref SplitNodes adaptor.
64 template <typename GR, typename LEN>
66 template < typename GR,
67 typename LEN = typename GR::template ArcMap<int> >
71 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
73 typedef ConstMap<Arc, int> ConstArcMap;
74 typedef typename GR::template NodeMap<Arc> PredMap;
78 /// The type of the digraph the algorithm runs on.
80 /// The type of the length map.
81 typedef LEN LengthMap;
82 /// The type of the lengths.
83 typedef typename LengthMap::Value Length;
85 /// The type of the flow map.
86 typedef GR::ArcMap<int> FlowMap;
87 /// The type of the potential map.
88 typedef GR::NodeMap<Length> PotentialMap;
90 /// The type of the flow map.
91 typedef typename Digraph::template ArcMap<int> FlowMap;
92 /// The type of the potential map.
93 typedef typename Digraph::template NodeMap<Length> PotentialMap;
96 /// The type of the path structures.
97 typedef SimplePath<GR> Path;
101 typedef typename Digraph::template NodeMap<int> HeapCrossRef;
102 typedef BinHeap<Length, HeapCrossRef> Heap;
104 // ResidualDijkstra is a special implementation of the
105 // Dijkstra algorithm for finding shortest paths in the
106 // residual network with respect to the reduced arc lengths
107 // and modifying the node potentials according to the
108 // distance of the nodes.
109 class ResidualDijkstra
113 const Digraph &_graph;
114 const LengthMap &_length;
115 const FlowMap &_flow;
122 std::vector<Node> _proc_nodes;
127 ResidualDijkstra(Suurballe &srb) :
128 _graph(srb._graph), _length(srb._length),
129 _flow(*srb._flow), _pi(*srb._potential), _pred(srb._pred),
130 _s(srb._s), _t(srb._t), _dist(_graph) {}
132 // Run the algorithm and return true if a path is found
133 // from the source node to the target node.
135 return cnt == 0 ? startFirst() : start();
140 // Execute the algorithm for the first time (the flow and potential
141 // functions have to be identically zero).
143 HeapCrossRef heap_cross_ref(_graph, Heap::PRE_HEAP);
144 Heap heap(heap_cross_ref);
150 while (!heap.empty() && heap.top() != _t) {
151 Node u = heap.top(), v;
152 Length d = heap.prio(), dn;
153 _dist[u] = heap.prio();
154 _proc_nodes.push_back(u);
157 // Traverse outgoing arcs
158 for (OutArcIt e(_graph, u); e != INVALID; ++e) {
159 v = _graph.target(e);
160 switch(heap.state(v)) {
162 heap.push(v, d + _length[e]);
168 heap.decrease(v, dn);
172 case Heap::POST_HEAP:
177 if (heap.empty()) return false;
179 // Update potentials of processed nodes
180 Length t_dist = heap.prio();
181 for (int i = 0; i < int(_proc_nodes.size()); ++i)
182 _pi[_proc_nodes[i]] = _dist[_proc_nodes[i]] - t_dist;
186 // Execute the algorithm.
188 HeapCrossRef heap_cross_ref(_graph, Heap::PRE_HEAP);
189 Heap heap(heap_cross_ref);
195 while (!heap.empty() && heap.top() != _t) {
196 Node u = heap.top(), v;
197 Length d = heap.prio() + _pi[u], dn;
198 _dist[u] = heap.prio();
199 _proc_nodes.push_back(u);
202 // Traverse outgoing arcs
203 for (OutArcIt e(_graph, u); e != INVALID; ++e) {
205 v = _graph.target(e);
206 switch(heap.state(v)) {
208 heap.push(v, d + _length[e] - _pi[v]);
212 dn = d + _length[e] - _pi[v];
214 heap.decrease(v, dn);
218 case Heap::POST_HEAP:
224 // Traverse incoming arcs
225 for (InArcIt e(_graph, u); e != INVALID; ++e) {
227 v = _graph.source(e);
228 switch(heap.state(v)) {
230 heap.push(v, d - _length[e] - _pi[v]);
234 dn = d - _length[e] - _pi[v];
236 heap.decrease(v, dn);
240 case Heap::POST_HEAP:
246 if (heap.empty()) return false;
248 // Update potentials of processed nodes
249 Length t_dist = heap.prio();
250 for (int i = 0; i < int(_proc_nodes.size()); ++i)
251 _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - t_dist;
255 }; //class ResidualDijkstra
259 // The digraph the algorithm runs on
260 const Digraph &_graph;
262 const LengthMap &_length;
264 // Arc map of the current flow
267 // Node map of the current potentials
268 PotentialMap *_potential;
269 bool _local_potential;
276 // Container to store the found paths
277 std::vector<Path> _paths;
283 // Data for full init
284 PotentialMap *_init_dist;
290 /// \brief Constructor.
294 /// \param graph The digraph the algorithm runs on.
295 /// \param length The length (cost) values of the arcs.
296 Suurballe( const Digraph &graph,
297 const LengthMap &length ) :
298 _graph(graph), _length(length), _flow(0), _local_flow(false),
299 _potential(0), _local_potential(false), _pred(graph),
300 _init_dist(0), _init_pred(0)
305 if (_local_flow) delete _flow;
306 if (_local_potential) delete _potential;
311 /// \brief Set the flow map.
313 /// This function sets the flow map.
314 /// If it is not used before calling \ref run() or \ref init(),
315 /// an instance will be allocated automatically. The destructor
316 /// deallocates this automatically allocated map, of course.
318 /// The found flow contains only 0 and 1 values, since it is the
319 /// union of the found arc-disjoint paths.
321 /// \return <tt>(*this)</tt>
322 Suurballe& flowMap(FlowMap &map) {
331 /// \brief Set the potential map.
333 /// This function sets the potential map.
334 /// If it is not used before calling \ref run() or \ref init(),
335 /// an instance will be allocated automatically. The destructor
336 /// deallocates this automatically allocated map, of course.
338 /// The node potentials provide the dual solution of the underlying
339 /// \ref min_cost_flow "minimum cost flow problem".
341 /// \return <tt>(*this)</tt>
342 Suurballe& potentialMap(PotentialMap &map) {
343 if (_local_potential) {
345 _local_potential = false;
351 /// \name Execution Control
352 /// The simplest way to execute the algorithm is to call the run()
354 /// If you need to execute the algorithm many times using the same
355 /// source node, then you may call fullInit() once and start()
356 /// for each target node.\n
357 /// If you only need the flow that is the union of the found
358 /// arc-disjoint paths, then you may call findFlow() instead of
363 /// \brief Run the algorithm.
365 /// This function runs the algorithm.
367 /// \param s The source node.
368 /// \param t The target node.
369 /// \param k The number of paths to be found.
371 /// \return \c k if there are at least \c k arc-disjoint paths from
372 /// \c s to \c t in the digraph. Otherwise it returns the number of
373 /// arc-disjoint paths found.
375 /// \note Apart from the return value, <tt>s.run(s, t, k)</tt> is
376 /// just a shortcut of the following code.
381 int run(const Node& s, const Node& t, int k = 2) {
387 /// \brief Initialize the algorithm.
389 /// This function initializes the algorithm with the given source node.
391 /// \param s The source node.
392 void init(const Node& s) {
397 _flow = new FlowMap(_graph);
401 _potential = new PotentialMap(_graph);
402 _local_potential = true;
407 /// \brief Initialize the algorithm and perform Dijkstra.
409 /// This function initializes the algorithm and performs a full
410 /// Dijkstra search from the given source node. It makes consecutive
411 /// executions of \ref start() "start(t, k)" faster, since they
412 /// have to perform %Dijkstra only k-1 times.
414 /// This initialization is usually worth using instead of \ref init()
415 /// if the algorithm is executed many times using the same source node.
417 /// \param s The source node.
418 void fullInit(const Node& s) {
422 _init_dist = new PotentialMap(_graph);
425 _init_pred = new PredMap(_graph);
428 // Run a full Dijkstra
429 typename Dijkstra<Digraph, LengthMap>
430 ::template SetStandardHeap<Heap>
431 ::template SetDistMap<PotentialMap>
432 ::template SetPredMap<PredMap>
433 ::Create dijk(_graph, _length);
434 dijk.distMap(*_init_dist).predMap(*_init_pred);
440 /// \brief Execute the algorithm.
442 /// This function executes the algorithm.
444 /// \param t The target node.
445 /// \param k The number of paths to be found.
447 /// \return \c k if there are at least \c k arc-disjoint paths from
448 /// \c s to \c t in the digraph. Otherwise it returns the number of
449 /// arc-disjoint paths found.
451 /// \note Apart from the return value, <tt>s.start(t, k)</tt> is
452 /// just a shortcut of the following code.
454 /// s.findFlow(t, k);
457 int start(const Node& t, int k = 2) {
463 /// \brief Execute the algorithm to find an optimal flow.
465 /// This function executes the successive shortest path algorithm to
466 /// find a minimum cost flow, which is the union of \c k (or less)
467 /// arc-disjoint paths.
469 /// \param t The target node.
470 /// \param k The number of paths to be found.
472 /// \return \c k if there are at least \c k arc-disjoint paths from
473 /// the source node to the given node \c t in the digraph.
474 /// Otherwise it returns the number of arc-disjoint paths found.
476 /// \pre \ref init() must be called before using this function.
477 int findFlow(const Node& t, int k = 2) {
479 ResidualDijkstra dijkstra(*this);
482 for (ArcIt e(_graph); e != INVALID; ++e) {
486 for (NodeIt n(_graph); n != INVALID; ++n) {
487 (*_potential)[n] = (*_init_dist)[n];
491 while ((e = (*_init_pred)[u]) != INVALID) {
493 u = _graph.source(e);
497 for (NodeIt n(_graph); n != INVALID; ++n) {
498 (*_potential)[n] = 0;
503 // Find shortest paths
504 while (_path_num < k) {
506 if (!dijkstra.run(_path_num)) break;
509 // Set the flow along the found shortest path
512 while ((e = _pred[u]) != INVALID) {
513 if (u == _graph.target(e)) {
515 u = _graph.source(e);
518 u = _graph.target(e);
525 /// \brief Compute the paths from the flow.
527 /// This function computes arc-disjoint paths from the found minimum
528 /// cost flow, which is the union of them.
530 /// \pre \ref init() and \ref findFlow() must be called before using
533 FlowMap res_flow(_graph);
534 for(ArcIt a(_graph); a != INVALID; ++a) res_flow[a] = (*_flow)[a];
537 _paths.resize(_path_num);
538 for (int i = 0; i < _path_num; ++i) {
541 OutArcIt e(_graph, n);
542 for ( ; res_flow[e] == 0; ++e) ;
543 n = _graph.target(e);
544 _paths[i].addBack(e);
552 /// \name Query Functions
553 /// The results of the algorithm can be obtained using these
555 /// \n The algorithm should be executed before using them.
559 /// \brief Return the total length of the found paths.
561 /// This function returns the total length of the found paths, i.e.
562 /// the total cost of the found flow.
563 /// The complexity of the function is O(e).
565 /// \pre \ref run() or \ref findFlow() must be called before using
567 Length totalLength() const {
569 for (ArcIt e(_graph); e != INVALID; ++e)
570 c += (*_flow)[e] * _length[e];
574 /// \brief Return the flow value on the given arc.
576 /// This function returns the flow value on the given arc.
577 /// It is \c 1 if the arc is involved in one of the found arc-disjoint
578 /// paths, otherwise it is \c 0.
580 /// \pre \ref run() or \ref findFlow() must be called before using
582 int flow(const Arc& arc) const {
583 return (*_flow)[arc];
586 /// \brief Return a const reference to an arc map storing the
589 /// This function returns a const reference to an arc map storing
590 /// the flow that is the union of the found arc-disjoint paths.
592 /// \pre \ref run() or \ref findFlow() must be called before using
594 const FlowMap& flowMap() const {
598 /// \brief Return the potential of the given node.
600 /// This function returns the potential of the given node.
601 /// The node potentials provide the dual solution of the
602 /// underlying \ref min_cost_flow "minimum cost flow problem".
604 /// \pre \ref run() or \ref findFlow() must be called before using
606 Length potential(const Node& node) const {
607 return (*_potential)[node];
610 /// \brief Return a const reference to a node map storing the
611 /// found potentials (the dual solution).
613 /// This function returns a const reference to a node map storing
614 /// the found potentials that provide the dual solution of the
615 /// underlying \ref min_cost_flow "minimum cost flow problem".
617 /// \pre \ref run() or \ref findFlow() must be called before using
619 const PotentialMap& potentialMap() const {
623 /// \brief Return the number of the found paths.
625 /// This function returns the number of the found paths.
627 /// \pre \ref run() or \ref findFlow() must be called before using
629 int pathNum() const {
633 /// \brief Return a const reference to the specified path.
635 /// This function returns a const reference to the specified path.
637 /// \param i The function returns the <tt>i</tt>-th path.
638 /// \c i must be between \c 0 and <tt>%pathNum()-1</tt>.
640 /// \pre \ref run() or \ref findPaths() must be called before using
642 const Path& path(int i) const {
654 #endif //LEMON_SUURBALLE_H