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_CAPACITY_SCALING_H
20 #define LEMON_CAPACITY_SCALING_H
22 /// \ingroup min_cost_flow_algs
25 /// \brief Capacity Scaling algorithm for finding a minimum cost flow.
29 #include <lemon/core.h>
30 #include <lemon/bin_heap.h>
34 /// \brief Default traits class of CapacityScaling algorithm.
36 /// Default traits class of CapacityScaling algorithm.
37 /// \tparam GR Digraph type.
38 /// \tparam V The value type used for flow amounts, capacity bounds
39 /// and supply values. By default it is \c int.
40 /// \tparam C The value type used for costs and potentials.
41 /// By default it is the same as \c V.
42 template <typename GR, typename V = int, typename C = V>
43 struct CapacityScalingDefaultTraits
45 /// The type of the digraph
47 /// The type of the flow amounts, capacity bounds and supply values
49 /// The type of the arc costs
52 /// \brief The type of the heap used for internal Dijkstra computations.
54 /// The type of the heap used for internal Dijkstra computations.
55 /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
56 /// its priority type must be \c Cost and its cross reference type
57 /// must be \ref RangeMap "RangeMap<int>".
58 typedef BinHeap<Cost, RangeMap<int> > Heap;
61 /// \addtogroup min_cost_flow_algs
64 /// \brief Implementation of the Capacity Scaling algorithm for
65 /// finding a \ref min_cost_flow "minimum cost flow".
67 /// \ref CapacityScaling implements the capacity scaling version
68 /// of the successive shortest path algorithm for finding a
69 /// \ref min_cost_flow "minimum cost flow". It is an efficient dual
72 /// Most of the parameters of the problem (except for the digraph)
73 /// can be given using separate functions, and the algorithm can be
74 /// executed using the \ref run() function. If some parameters are not
75 /// specified, then default values will be used.
77 /// \tparam GR The digraph type the algorithm runs on.
78 /// \tparam V The value type used for flow amounts, capacity bounds
79 /// and supply values in the algorithm. By default it is \c int.
80 /// \tparam C The value type used for costs and potentials in the
81 /// algorithm. By default it is the same as \c V.
83 /// \warning Both value types must be signed and all input data must
85 /// \warning This algorithm does not support negative costs for such
86 /// arcs that have infinite upper bound.
88 template <typename GR, typename V, typename C, typename TR>
90 template < typename GR, typename V = int, typename C = V,
91 typename TR = CapacityScalingDefaultTraits<GR, V, C> >
97 /// The type of the digraph
98 typedef typename TR::Digraph Digraph;
99 /// The type of the flow amounts, capacity bounds and supply values
100 typedef typename TR::Value Value;
101 /// The type of the arc costs
102 typedef typename TR::Cost Cost;
104 /// The type of the heap used for internal Dijkstra computations
105 typedef typename TR::Heap Heap;
107 /// The \ref CapacityScalingDefaultTraits "traits class" of the algorithm
112 /// \brief Problem type constants for the \c run() function.
114 /// Enum type containing the problem type constants that can be
115 /// returned by the \ref run() function of the algorithm.
117 /// The problem has no feasible solution (flow).
119 /// The problem has optimal solution (i.e. it is feasible and
120 /// bounded), and the algorithm has found optimal flow and node
121 /// potentials (primal and dual solutions).
123 /// The digraph contains an arc of negative cost and infinite
124 /// upper bound. It means that the objective function is unbounded
125 /// on that arc, however note that it could actually be bounded
126 /// over the feasible flows, but this algroithm cannot handle
133 TEMPLATE_DIGRAPH_TYPEDEFS(GR);
135 typedef std::vector<int> IntVector;
136 typedef std::vector<bool> BoolVector;
137 typedef std::vector<Value> ValueVector;
138 typedef std::vector<Cost> CostVector;
142 // Data related to the underlying digraph
149 // Parameters of the problem
153 // Data structures for storing the digraph
157 IntVector _first_out;
169 ValueVector _res_cap;
172 IntVector _excess_nodes;
173 IntVector _deficit_nodes;
181 /// \brief Constant for infinite upper bounds (capacities).
183 /// Constant for infinite upper bounds (capacities).
184 /// It is \c std::numeric_limits<Value>::infinity() if available,
185 /// \c std::numeric_limits<Value>::max() otherwise.
190 // Special implementation of the Dijkstra algorithm for finding
191 // shortest paths in the residual network of the digraph with
192 // respect to the reduced arc costs and modifying the node
193 // potentials according to the found distance labels.
194 class ResidualDijkstra
199 const IntVector &_first_out;
200 const IntVector &_target;
201 const CostVector &_cost;
202 const ValueVector &_res_cap;
203 const ValueVector &_excess;
207 IntVector _proc_nodes;
212 ResidualDijkstra(CapacityScaling& cs) :
213 _node_num(cs._node_num), _first_out(cs._first_out),
214 _target(cs._target), _cost(cs._cost), _res_cap(cs._res_cap),
215 _excess(cs._excess), _pi(cs._pi), _pred(cs._pred),
219 int run(int s, Value delta = 1) {
220 RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
221 Heap heap(heap_cross_ref);
227 while (!heap.empty() && _excess[heap.top()] > -delta) {
228 int u = heap.top(), v;
229 Cost d = heap.prio() + _pi[u], dn;
230 _dist[u] = heap.prio();
231 _proc_nodes.push_back(u);
234 // Traverse outgoing residual arcs
235 for (int a = _first_out[u]; a != _first_out[u+1]; ++a) {
236 if (_res_cap[a] < delta) continue;
238 switch (heap.state(v)) {
240 heap.push(v, d + _cost[a] - _pi[v]);
244 dn = d + _cost[a] - _pi[v];
246 heap.decrease(v, dn);
250 case Heap::POST_HEAP:
255 if (heap.empty()) return -1;
257 // Update potentials of processed nodes
259 Cost dt = heap.prio();
260 for (int i = 0; i < int(_proc_nodes.size()); ++i) {
261 _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt;
267 }; //class ResidualDijkstra
271 /// \name Named Template Parameters
274 template <typename T>
275 struct SetHeapTraits : public Traits {
279 /// \brief \ref named-templ-param "Named parameter" for setting
282 /// \ref named-templ-param "Named parameter" for setting \c Heap
283 /// type, which is used for internal Dijkstra computations.
284 /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
285 /// its priority type must be \c Cost and its cross reference type
286 /// must be \ref RangeMap "RangeMap<int>".
287 template <typename T>
289 : public CapacityScaling<GR, V, C, SetHeapTraits<T> > {
290 typedef CapacityScaling<GR, V, C, SetHeapTraits<T> > Create;
297 /// \brief Constructor.
299 /// The constructor of the class.
301 /// \param graph The digraph the algorithm runs on.
302 CapacityScaling(const GR& graph) :
303 _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
304 INF(std::numeric_limits<Value>::has_infinity ?
305 std::numeric_limits<Value>::infinity() :
306 std::numeric_limits<Value>::max())
308 // Check the value types
309 LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
310 "The flow type of CapacityScaling must be signed");
311 LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
312 "The cost type of CapacityScaling must be signed");
315 _node_num = countNodes(_graph);
316 _arc_num = countArcs(_graph);
317 _res_arc_num = 2 * (_arc_num + _node_num);
321 _first_out.resize(_node_num + 1);
322 _forward.resize(_res_arc_num);
323 _source.resize(_res_arc_num);
324 _target.resize(_res_arc_num);
325 _reverse.resize(_res_arc_num);
327 _lower.resize(_res_arc_num);
328 _upper.resize(_res_arc_num);
329 _cost.resize(_res_arc_num);
330 _supply.resize(_node_num);
332 _res_cap.resize(_res_arc_num);
333 _pi.resize(_node_num);
334 _excess.resize(_node_num);
335 _pred.resize(_node_num);
338 int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1;
339 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
343 for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
345 for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
349 _target[j] = _node_id[_graph.runningNode(a)];
351 for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
355 _target[j] = _node_id[_graph.runningNode(a)];
368 _first_out[_node_num] = k;
369 for (ArcIt a(_graph); a != INVALID; ++a) {
370 int fi = _arc_idf[a];
371 int bi = _arc_idb[a];
381 /// The parameters of the algorithm can be specified using these
386 /// \brief Set the lower bounds on the arcs.
388 /// This function sets the lower bounds on the arcs.
389 /// If it is not used before calling \ref run(), the lower bounds
390 /// will be set to zero on all arcs.
392 /// \param map An arc map storing the lower bounds.
393 /// Its \c Value type must be convertible to the \c Value type
394 /// of the algorithm.
396 /// \return <tt>(*this)</tt>
397 template <typename LowerMap>
398 CapacityScaling& lowerMap(const LowerMap& map) {
400 for (ArcIt a(_graph); a != INVALID; ++a) {
401 _lower[_arc_idf[a]] = map[a];
402 _lower[_arc_idb[a]] = map[a];
407 /// \brief Set the upper bounds (capacities) on the arcs.
409 /// This function sets the upper bounds (capacities) on the arcs.
410 /// If it is not used before calling \ref run(), the upper bounds
411 /// will be set to \ref INF on all arcs (i.e. the flow value will be
412 /// unbounded from above on each arc).
414 /// \param map An arc map storing the upper bounds.
415 /// Its \c Value type must be convertible to the \c Value type
416 /// of the algorithm.
418 /// \return <tt>(*this)</tt>
419 template<typename UpperMap>
420 CapacityScaling& upperMap(const UpperMap& map) {
421 for (ArcIt a(_graph); a != INVALID; ++a) {
422 _upper[_arc_idf[a]] = map[a];
427 /// \brief Set the costs of the arcs.
429 /// This function sets the costs of the arcs.
430 /// If it is not used before calling \ref run(), the costs
431 /// will be set to \c 1 on all arcs.
433 /// \param map An arc map storing the costs.
434 /// Its \c Value type must be convertible to the \c Cost type
435 /// of the algorithm.
437 /// \return <tt>(*this)</tt>
438 template<typename CostMap>
439 CapacityScaling& costMap(const CostMap& map) {
440 for (ArcIt a(_graph); a != INVALID; ++a) {
441 _cost[_arc_idf[a]] = map[a];
442 _cost[_arc_idb[a]] = -map[a];
447 /// \brief Set the supply values of the nodes.
449 /// This function sets the supply values of the nodes.
450 /// If neither this function nor \ref stSupply() is used before
451 /// calling \ref run(), the supply of each node will be set to zero.
453 /// \param map A node map storing the supply values.
454 /// Its \c Value type must be convertible to the \c Value type
455 /// of the algorithm.
457 /// \return <tt>(*this)</tt>
458 template<typename SupplyMap>
459 CapacityScaling& supplyMap(const SupplyMap& map) {
460 for (NodeIt n(_graph); n != INVALID; ++n) {
461 _supply[_node_id[n]] = map[n];
466 /// \brief Set single source and target nodes and a supply value.
468 /// This function sets a single source node and a single target node
469 /// and the required flow value.
470 /// If neither this function nor \ref supplyMap() is used before
471 /// calling \ref run(), the supply of each node will be set to zero.
473 /// Using this function has the same effect as using \ref supplyMap()
474 /// with such a map in which \c k is assigned to \c s, \c -k is
475 /// assigned to \c t and all other nodes have zero supply value.
477 /// \param s The source node.
478 /// \param t The target node.
479 /// \param k The required amount of flow from node \c s to node \c t
480 /// (i.e. the supply of \c s and the demand of \c t).
482 /// \return <tt>(*this)</tt>
483 CapacityScaling& stSupply(const Node& s, const Node& t, Value k) {
484 for (int i = 0; i != _node_num; ++i) {
487 _supply[_node_id[s]] = k;
488 _supply[_node_id[t]] = -k;
494 /// \name Execution control
495 /// The algorithm can be executed using \ref run().
499 /// \brief Run the algorithm.
501 /// This function runs the algorithm.
502 /// The paramters can be specified using functions \ref lowerMap(),
503 /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
506 /// CapacityScaling<ListDigraph> cs(graph);
507 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
508 /// .supplyMap(sup).run();
511 /// This function can be called more than once. All the parameters
512 /// that have been given are kept for the next call, unless
513 /// \ref reset() is called, thus only the modified parameters
514 /// have to be set again. See \ref reset() for examples.
515 /// However the underlying digraph must not be modified after this
516 /// class have been constructed, since it copies the digraph.
518 /// \param scaling Enable or disable capacity scaling.
519 /// If the maximum upper bound and/or the amount of total supply
520 /// is rather small, the algorithm could be slightly faster without
523 /// \return \c INFEASIBLE if no feasible flow exists,
524 /// \n \c OPTIMAL if the problem has optimal solution
525 /// (i.e. it is feasible and bounded), and the algorithm has found
526 /// optimal flow and node potentials (primal and dual solutions),
527 /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
528 /// and infinite upper bound. It means that the objective function
529 /// is unbounded on that arc, however note that it could actually be
530 /// bounded over the feasible flows, but this algroithm cannot handle
534 ProblemType run(bool scaling = true) {
535 ProblemType pt = init(scaling);
536 if (pt != OPTIMAL) return pt;
540 /// \brief Reset all the parameters that have been given before.
542 /// This function resets all the paramaters that have been given
543 /// before using functions \ref lowerMap(), \ref upperMap(),
544 /// \ref costMap(), \ref supplyMap(), \ref stSupply().
546 /// It is useful for multiple run() calls. If this function is not
547 /// used, all the parameters given before are kept for the next
549 /// However the underlying digraph must not be modified after this
550 /// class have been constructed, since it copies and extends the graph.
554 /// CapacityScaling<ListDigraph> cs(graph);
557 /// cs.lowerMap(lower).upperMap(upper).costMap(cost)
558 /// .supplyMap(sup).run();
560 /// // Run again with modified cost map (reset() is not called,
561 /// // so only the cost map have to be set again)
563 /// cs.costMap(cost).run();
565 /// // Run again from scratch using reset()
566 /// // (the lower bounds will be set to zero on all arcs)
568 /// cs.upperMap(capacity).costMap(cost)
569 /// .supplyMap(sup).run();
572 /// \return <tt>(*this)</tt>
573 CapacityScaling& reset() {
574 for (int i = 0; i != _node_num; ++i) {
577 for (int j = 0; j != _res_arc_num; ++j) {
580 _cost[j] = _forward[j] ? 1 : -1;
588 /// \name Query Functions
589 /// The results of the algorithm can be obtained using these
591 /// The \ref run() function must be called before using them.
595 /// \brief Return the total cost of the found flow.
597 /// This function returns the total cost of the found flow.
598 /// Its complexity is O(e).
600 /// \note The return type of the function can be specified as a
601 /// template parameter. For example,
603 /// cs.totalCost<double>();
605 /// It is useful if the total cost cannot be stored in the \c Cost
606 /// type of the algorithm, which is the default return type of the
609 /// \pre \ref run() must be called before using this function.
610 template <typename Number>
611 Number totalCost() const {
613 for (ArcIt a(_graph); a != INVALID; ++a) {
615 c += static_cast<Number>(_res_cap[i]) *
616 (-static_cast<Number>(_cost[i]));
622 Cost totalCost() const {
623 return totalCost<Cost>();
627 /// \brief Return the flow on the given arc.
629 /// This function returns the flow on the given arc.
631 /// \pre \ref run() must be called before using this function.
632 Value flow(const Arc& a) const {
633 return _res_cap[_arc_idb[a]];
636 /// \brief Return the flow map (the primal solution).
638 /// This function copies the flow value on each arc into the given
639 /// map. The \c Value type of the algorithm must be convertible to
640 /// the \c Value type of the map.
642 /// \pre \ref run() must be called before using this function.
643 template <typename FlowMap>
644 void flowMap(FlowMap &map) const {
645 for (ArcIt a(_graph); a != INVALID; ++a) {
646 map.set(a, _res_cap[_arc_idb[a]]);
650 /// \brief Return the potential (dual value) of the given node.
652 /// This function returns the potential (dual value) of the
655 /// \pre \ref run() must be called before using this function.
656 Cost potential(const Node& n) const {
657 return _pi[_node_id[n]];
660 /// \brief Return the potential map (the dual solution).
662 /// This function copies the potential (dual value) of each node
663 /// into the given map.
664 /// The \c Cost type of the algorithm must be convertible to the
665 /// \c Value type of the map.
667 /// \pre \ref run() must be called before using this function.
668 template <typename PotentialMap>
669 void potentialMap(PotentialMap &map) const {
670 for (NodeIt n(_graph); n != INVALID; ++n) {
671 map.set(n, _pi[_node_id[n]]);
679 // Initialize the algorithm
680 ProblemType init(bool scaling) {
681 if (_node_num == 0) return INFEASIBLE;
683 // Check the sum of supply values
685 for (int i = 0; i != _root; ++i) {
686 _sum_supply += _supply[i];
688 if (_sum_supply > 0) return INFEASIBLE;
691 for (int i = 0; i != _root; ++i) {
693 _excess[i] = _supply[i];
696 // Remove non-zero lower bounds
698 for (int i = 0; i != _root; ++i) {
699 for (int j = _first_out[i]; j != _first_out[i+1]; ++j) {
703 _res_cap[j] = _upper[j] < INF ? _upper[j] - c : INF;
705 _res_cap[j] = _upper[j] < INF + c ? _upper[j] - c : INF;
708 _excess[_target[j]] += c;
715 for (int j = 0; j != _res_arc_num; ++j) {
716 _res_cap[j] = _forward[j] ? _upper[j] : 0;
720 // Handle negative costs
721 for (int u = 0; u != _root; ++u) {
722 for (int a = _first_out[u]; a != _first_out[u+1]; ++a) {
723 Value rc = _res_cap[a];
724 if (_cost[a] < 0 && rc > 0) {
725 if (rc == INF) return UNBOUNDED;
727 _excess[_target[a]] += rc;
729 _res_cap[_reverse[a]] += rc;
734 // Handle GEQ supply type
735 if (_sum_supply < 0) {
737 _excess[_root] = -_sum_supply;
738 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
740 if (_excess[u] < 0) {
741 _res_cap[a] = -_excess[u] + 1;
745 _res_cap[_reverse[a]] = 0;
747 _cost[_reverse[a]] = 0;
752 for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
754 _res_cap[_reverse[a]] = 0;
756 _cost[_reverse[a]] = 0;
760 // Initialize delta value
763 Value max_sup = 0, max_dem = 0;
764 for (int i = 0; i != _node_num; ++i) {
765 if ( _excess[i] > max_sup) max_sup = _excess[i];
766 if (-_excess[i] > max_dem) max_dem = -_excess[i];
769 for (int j = 0; j != _res_arc_num; ++j) {
770 if (_res_cap[j] > max_cap) max_cap = _res_cap[j];
772 max_sup = std::min(std::min(max_sup, max_dem), max_cap);
774 for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2)
784 ProblemType start() {
785 // Execute the algorithm
788 pt = startWithScaling();
790 pt = startWithoutScaling();
792 // Handle non-zero lower bounds
794 for (int j = 0; j != _res_arc_num - _node_num + 1; ++j) {
795 if (!_forward[j]) _res_cap[j] += _lower[j];
799 // Shift potentials if necessary
800 Cost pr = _pi[_root];
801 if (_sum_supply < 0 || pr > 0) {
802 for (int i = 0; i != _node_num; ++i) {
810 // Execute the capacity scaling algorithm
811 ProblemType startWithScaling() {
812 // Perform capacity scaling phases
816 ResidualDijkstra _dijkstra(*this);
818 // Saturate all arcs not satisfying the optimality condition
819 for (int u = 0; u != _node_num; ++u) {
820 for (int a = _first_out[u]; a != _first_out[u+1]; ++a) {
822 Cost c = _cost[a] + _pi[u] - _pi[v];
823 Value rc = _res_cap[a];
824 if (c < 0 && rc >= _delta) {
828 _res_cap[_reverse[a]] += rc;
833 // Find excess nodes and deficit nodes
834 _excess_nodes.clear();
835 _deficit_nodes.clear();
836 for (int u = 0; u != _node_num; ++u) {
837 if (_excess[u] >= _delta) _excess_nodes.push_back(u);
838 if (_excess[u] <= -_delta) _deficit_nodes.push_back(u);
840 int next_node = 0, next_def_node = 0;
842 // Find augmenting shortest paths
843 while (next_node < int(_excess_nodes.size())) {
844 // Check deficit nodes
846 bool delta_deficit = false;
847 for ( ; next_def_node < int(_deficit_nodes.size());
849 if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
850 delta_deficit = true;
854 if (!delta_deficit) break;
857 // Run Dijkstra in the residual network
858 s = _excess_nodes[next_node];
859 if ((t = _dijkstra.run(s, _delta)) == -1) {
867 // Augment along a shortest path from s to t
868 Value d = std::min(_excess[s], -_excess[t]);
872 while ((a = _pred[u]) != -1) {
873 if (_res_cap[a] < d) d = _res_cap[a];
878 while ((a = _pred[u]) != -1) {
880 _res_cap[_reverse[a]] += d;
886 if (_excess[s] < _delta) ++next_node;
889 if (_delta == 1) break;
890 if (++phase_cnt == _phase_num / 4) factor = 2;
891 _delta = _delta <= factor ? 1 : _delta / factor;
897 // Execute the successive shortest path algorithm
898 ProblemType startWithoutScaling() {
900 _excess_nodes.clear();
901 for (int i = 0; i != _node_num; ++i) {
902 if (_excess[i] > 0) _excess_nodes.push_back(i);
904 if (_excess_nodes.size() == 0) return OPTIMAL;
907 // Find shortest paths
909 ResidualDijkstra _dijkstra(*this);
910 while ( _excess[_excess_nodes[next_node]] > 0 ||
911 ++next_node < int(_excess_nodes.size()) )
913 // Run Dijkstra in the residual network
914 s = _excess_nodes[next_node];
915 if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
917 // Augment along a shortest path from s to t
918 Value d = std::min(_excess[s], -_excess[t]);
922 while ((a = _pred[u]) != -1) {
923 if (_res_cap[a] < d) d = _res_cap[a];
928 while ((a = _pred[u]) != -1) {
930 _res_cap[_reverse[a]] += d;
940 }; //class CapacityScaling
946 #endif //LEMON_CAPACITY_SCALING_H