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_COST_SCALING_H
20 #define LEMON_COST_SCALING_H
22 /// \ingroup min_cost_flow
25 /// \brief Cost scaling algorithm for finding a minimum cost flow.
28 #include <lemon/graph_adaptor.h>
29 #include <lemon/graph_utils.h>
30 #include <lemon/maps.h>
31 #include <lemon/math.h>
33 #include <lemon/circulation.h>
34 #include <lemon/bellman_ford.h>
38 /// \addtogroup min_cost_flow
41 /// \brief Implementation of the cost scaling algorithm for finding a
42 /// minimum cost flow.
44 /// \ref CostScaling implements the cost scaling algorithm performing
45 /// generalized push-relabel operations for finding a minimum cost
48 /// \tparam Graph The directed graph type the algorithm runs on.
49 /// \tparam LowerMap The type of the lower bound map.
50 /// \tparam CapacityMap The type of the capacity (upper bound) map.
51 /// \tparam CostMap The type of the cost (length) map.
52 /// \tparam SupplyMap The type of the supply map.
55 /// - Edge capacities and costs should be \e non-negative \e integers.
56 /// - Supply values should be \e signed \e integers.
57 /// - The value types of the maps should be convertible to each other.
58 /// - \c CostMap::Value must be signed type.
60 /// \note Edge costs are multiplied with the number of nodes during
61 /// the algorithm so overflow problems may arise more easily than with
62 /// other minimum cost flow algorithms.
63 /// If it is available, <tt>long long int</tt> type is used instead of
64 /// <tt>long int</tt> in the inside computations.
66 /// \author Peter Kovacs
68 template < typename Graph,
69 typename LowerMap = typename Graph::template EdgeMap<int>,
70 typename CapacityMap = typename Graph::template EdgeMap<int>,
71 typename CostMap = typename Graph::template EdgeMap<int>,
72 typename SupplyMap = typename Graph::template NodeMap<int> >
75 GRAPH_TYPEDEFS(typename Graph);
77 typedef typename CapacityMap::Value Capacity;
78 typedef typename CostMap::Value Cost;
79 typedef typename SupplyMap::Value Supply;
80 typedef typename Graph::template EdgeMap<Capacity> CapacityEdgeMap;
81 typedef typename Graph::template NodeMap<Supply> SupplyNodeMap;
83 typedef ResGraphAdaptor< const Graph, Capacity,
84 CapacityEdgeMap, CapacityEdgeMap > ResGraph;
85 typedef typename ResGraph::Edge ResEdge;
87 #if defined __GNUC__ && !defined __STRICT_ANSI__
88 typedef long long int LCost;
90 typedef long int LCost;
92 typedef typename Graph::template EdgeMap<LCost> LargeCostMap;
96 /// The type of the flow map.
97 typedef typename Graph::template EdgeMap<Capacity> FlowMap;
98 /// The type of the potential map.
99 typedef typename Graph::template NodeMap<LCost> PotentialMap;
103 /// \brief Map adaptor class for handling residual edge costs.
105 /// \ref ResidualCostMap is a map adaptor class for handling
106 /// residual edge costs.
107 template <typename Map>
108 class ResidualCostMap : public MapBase<ResEdge, typename Map::Value>
112 const Map &_cost_map;
117 ResidualCostMap(const Map &cost_map) :
118 _cost_map(cost_map) {}
121 typename Map::Value operator[](const ResEdge &e) const {
122 return ResGraph::forward(e) ? _cost_map[e] : -_cost_map[e];
125 }; //class ResidualCostMap
127 /// \brief Map adaptor class for handling reduced edge costs.
129 /// \ref ReducedCostMap is a map adaptor class for handling reduced
131 class ReducedCostMap : public MapBase<Edge, LCost>
136 const LargeCostMap &_cost_map;
137 const PotentialMap &_pot_map;
142 ReducedCostMap( const Graph &gr,
143 const LargeCostMap &cost_map,
144 const PotentialMap &pot_map ) :
145 _gr(gr), _cost_map(cost_map), _pot_map(pot_map) {}
148 LCost operator[](const Edge &e) const {
149 return _cost_map[e] + _pot_map[_gr.source(e)]
150 - _pot_map[_gr.target(e)];
153 }; //class ReducedCostMap
158 static const int ALPHA = 4;
160 // Paramters for heuristics
161 static const int BF_HEURISTIC_EPSILON_BOUND = 5000;
162 static const int BF_HEURISTIC_BOUND_FACTOR = 3;
166 // The directed graph the algorithm runs on
168 // The original lower bound map
169 const LowerMap *_lower;
170 // The modified capacity map
171 CapacityEdgeMap _capacity;
172 // The original cost map
173 const CostMap &_orig_cost;
174 // The scaled cost map
176 // The modified supply map
177 SupplyNodeMap _supply;
180 // Edge map of the current flow
183 // Node map of the current potentials
184 PotentialMap *_potential;
185 bool _local_potential;
187 // The residual graph
188 ResGraph *_res_graph;
189 // The residual cost map
190 ResidualCostMap<LargeCostMap> _res_cost;
191 // The reduced cost map
192 ReducedCostMap *_red_cost;
194 SupplyNodeMap _excess;
195 // The epsilon parameter used for cost scaling
200 /// \brief General constructor (with lower bounds).
202 /// General constructor (with lower bounds).
204 /// \param graph The directed graph the algorithm runs on.
205 /// \param lower The lower bounds of the edges.
206 /// \param capacity The capacities (upper bounds) of the edges.
207 /// \param cost The cost (length) values of the edges.
208 /// \param supply The supply values of the nodes (signed).
209 CostScaling( const Graph &graph,
210 const LowerMap &lower,
211 const CapacityMap &capacity,
213 const SupplyMap &supply ) :
214 _graph(graph), _lower(&lower), _capacity(graph), _orig_cost(cost),
215 _cost(graph), _supply(graph), _flow(0), _local_flow(false),
216 _potential(0), _local_potential(false), _res_cost(_cost),
219 // Removing non-zero lower bounds
220 _capacity = subMap(capacity, lower);
222 for (NodeIt n(_graph); n != INVALID; ++n) {
223 Supply s = supply[n];
224 for (InEdgeIt e(_graph, n); e != INVALID; ++e)
226 for (OutEdgeIt e(_graph, n); e != INVALID; ++e)
231 _valid_supply = sum == 0;
234 /// \brief General constructor (without lower bounds).
236 /// General constructor (without lower bounds).
238 /// \param graph The directed graph the algorithm runs on.
239 /// \param capacity The capacities (upper bounds) of the edges.
240 /// \param cost The cost (length) values of the edges.
241 /// \param supply The supply values of the nodes (signed).
242 CostScaling( const Graph &graph,
243 const CapacityMap &capacity,
245 const SupplyMap &supply ) :
246 _graph(graph), _lower(NULL), _capacity(capacity), _orig_cost(cost),
247 _cost(graph), _supply(supply), _flow(0), _local_flow(false),
248 _potential(0), _local_potential(false), _res_cost(_cost),
251 // Checking the sum of supply values
253 for (NodeIt n(_graph); n != INVALID; ++n) sum += _supply[n];
254 _valid_supply = sum == 0;
257 /// \brief Simple constructor (with lower bounds).
259 /// Simple constructor (with lower bounds).
261 /// \param graph The directed graph the algorithm runs on.
262 /// \param lower The lower bounds of the edges.
263 /// \param capacity The capacities (upper bounds) of the edges.
264 /// \param cost The cost (length) values of the edges.
265 /// \param s The source node.
266 /// \param t The target node.
267 /// \param flow_value The required amount of flow from node \c s
268 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
269 CostScaling( const Graph &graph,
270 const LowerMap &lower,
271 const CapacityMap &capacity,
274 Supply flow_value ) :
275 _graph(graph), _lower(&lower), _capacity(graph), _orig_cost(cost),
276 _cost(graph), _supply(graph), _flow(0), _local_flow(false),
277 _potential(0), _local_potential(false), _res_cost(_cost),
280 // Removing nonzero lower bounds
281 _capacity = subMap(capacity, lower);
282 for (NodeIt n(_graph); n != INVALID; ++n) {
284 if (n == s) sum = flow_value;
285 if (n == t) sum = -flow_value;
286 for (InEdgeIt e(_graph, n); e != INVALID; ++e)
288 for (OutEdgeIt e(_graph, n); e != INVALID; ++e)
292 _valid_supply = true;
295 /// \brief Simple constructor (without lower bounds).
297 /// Simple constructor (without lower bounds).
299 /// \param graph The directed graph the algorithm runs on.
300 /// \param capacity The capacities (upper bounds) of the edges.
301 /// \param cost The cost (length) values of the edges.
302 /// \param s The source node.
303 /// \param t The target node.
304 /// \param flow_value The required amount of flow from node \c s
305 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
306 CostScaling( const Graph &graph,
307 const CapacityMap &capacity,
310 Supply flow_value ) :
311 _graph(graph), _lower(NULL), _capacity(capacity), _orig_cost(cost),
312 _cost(graph), _supply(graph, 0), _flow(0), _local_flow(false),
313 _potential(0), _local_potential(false), _res_cost(_cost),
316 _supply[s] = flow_value;
317 _supply[t] = -flow_value;
318 _valid_supply = true;
323 if (_local_flow) delete _flow;
324 if (_local_potential) delete _potential;
329 /// \brief Sets the flow map.
331 /// Sets the flow map.
333 /// \return \c (*this)
334 CostScaling& flowMap(FlowMap &map) {
343 /// \brief Sets the potential map.
345 /// Sets the potential map.
347 /// \return \c (*this)
348 CostScaling& potentialMap(PotentialMap &map) {
349 if (_local_potential) {
351 _local_potential = false;
357 /// \name Execution control
358 /// The only way to execute the algorithm is to call the run()
363 /// \brief Runs the algorithm.
365 /// Runs the algorithm.
367 /// \return \c true if a feasible flow can be found.
369 return init() && start();
374 /// \name Query Functions
375 /// The result of the algorithm can be obtained using these
377 /// \n run() must be called before using them.
381 /// \brief Returns a const reference to the edge map storing the
384 /// Returns a const reference to the edge map storing the found flow.
386 /// \pre \ref run() must be called before using this function.
387 const FlowMap& flowMap() const {
391 /// \brief Returns a const reference to the node map storing the
392 /// found potentials (the dual solution).
394 /// Returns a const reference to the node map storing the found
395 /// potentials (the dual solution).
397 /// \pre \ref run() must be called before using this function.
398 const PotentialMap& potentialMap() const {
402 /// \brief Returns the flow on the given edge.
404 /// Returns the flow on the given edge.
406 /// \pre \ref run() must be called before using this function.
407 Capacity flow(const Edge& edge) const {
408 return (*_flow)[edge];
411 /// \brief Returns the potential of the given node.
413 /// Returns the potential of the given node.
415 /// \pre \ref run() must be called before using this function.
416 Cost potential(const Node& node) const {
417 return (*_potential)[node];
420 /// \brief Returns the total cost of the found flow.
422 /// Returns the total cost of the found flow. The complexity of the
423 /// function is \f$ O(e) \f$.
425 /// \pre \ref run() must be called before using this function.
426 Cost totalCost() const {
428 for (EdgeIt e(_graph); e != INVALID; ++e)
429 c += (*_flow)[e] * _orig_cost[e];
437 /// Initializes the algorithm.
439 if (!_valid_supply) return false;
441 // Initializing flow and potential maps
443 _flow = new FlowMap(_graph);
447 _potential = new PotentialMap(_graph);
448 _local_potential = true;
451 _red_cost = new ReducedCostMap(_graph, _cost, *_potential);
452 _res_graph = new ResGraph(_graph, _capacity, *_flow);
454 // Initializing the scaled cost map and the epsilon parameter
456 int node_num = countNodes(_graph);
457 for (EdgeIt e(_graph); e != INVALID; ++e) {
458 _cost[e] = LCost(_orig_cost[e]) * node_num * ALPHA;
459 if (_orig_cost[e] > max_cost) max_cost = _orig_cost[e];
461 _epsilon = max_cost * node_num;
463 // Finding a feasible flow using Circulation
464 Circulation< Graph, ConstMap<Edge, Capacity>, CapacityEdgeMap,
466 circulation( _graph, constMap<Edge>(Capacity(0)), _capacity,
468 return circulation.flowMap(*_flow).run();
472 /// Executes the algorithm.
474 std::deque<Node> active_nodes;
475 typename Graph::template NodeMap<bool> hyper(_graph, false);
477 int node_num = countNodes(_graph);
478 for ( ; _epsilon >= 1; _epsilon = _epsilon < ALPHA && _epsilon > 1 ?
479 1 : _epsilon / ALPHA )
481 // Performing price refinement heuristic using Bellman-Ford
483 if (_epsilon <= BF_HEURISTIC_EPSILON_BOUND) {
484 typedef ShiftMap< ResidualCostMap<LargeCostMap> > ShiftCostMap;
485 ShiftCostMap shift_cost(_res_cost, _epsilon);
486 BellmanFord<ResGraph, ShiftCostMap> bf(*_res_graph, shift_cost);
489 int K = int(BF_HEURISTIC_BOUND_FACTOR * sqrt(node_num));
490 for (int i = 0; i < K && !done; ++i)
491 done = bf.processNextWeakRound();
493 for (NodeIt n(_graph); n != INVALID; ++n)
494 (*_potential)[n] = bf.dist(n);
499 // Saturating edges not satisfying the optimality condition
501 for (EdgeIt e(_graph); e != INVALID; ++e) {
502 if (_capacity[e] - (*_flow)[e] > 0 && (*_red_cost)[e] < 0) {
503 delta = _capacity[e] - (*_flow)[e];
504 _excess[_graph.source(e)] -= delta;
505 _excess[_graph.target(e)] += delta;
506 (*_flow)[e] = _capacity[e];
508 if ((*_flow)[e] > 0 && -(*_red_cost)[e] < 0) {
509 _excess[_graph.target(e)] -= (*_flow)[e];
510 _excess[_graph.source(e)] += (*_flow)[e];
515 // Finding active nodes (i.e. nodes with positive excess)
516 for (NodeIt n(_graph); n != INVALID; ++n)
517 if (_excess[n] > 0) active_nodes.push_back(n);
519 // Performing push and relabel operations
520 while (active_nodes.size() > 0) {
521 Node n = active_nodes[0], t;
522 bool relabel_enabled = true;
524 // Performing push operations if there are admissible edges
525 if (_excess[n] > 0) {
526 for (OutEdgeIt e(_graph, n); e != INVALID; ++e) {
527 if (_capacity[e] - (*_flow)[e] > 0 && (*_red_cost)[e] < 0) {
528 delta = _capacity[e] - (*_flow)[e] <= _excess[n] ?
529 _capacity[e] - (*_flow)[e] : _excess[n];
530 t = _graph.target(e);
532 // Push-look-ahead heuristic
533 Capacity ahead = -_excess[t];
534 for (OutEdgeIt oe(_graph, t); oe != INVALID; ++oe) {
535 if (_capacity[oe] - (*_flow)[oe] > 0 && (*_red_cost)[oe] < 0)
536 ahead += _capacity[oe] - (*_flow)[oe];
538 for (InEdgeIt ie(_graph, t); ie != INVALID; ++ie) {
539 if ((*_flow)[ie] > 0 && -(*_red_cost)[ie] < 0)
540 ahead += (*_flow)[ie];
542 if (ahead < 0) ahead = 0;
544 // Pushing flow along the edge
546 (*_flow)[e] += ahead;
549 active_nodes.push_front(t);
551 relabel_enabled = false;
554 (*_flow)[e] += delta;
557 if (_excess[t] > 0 && _excess[t] <= delta)
558 active_nodes.push_back(t);
561 if (_excess[n] == 0) break;
566 if (_excess[n] > 0) {
567 for (InEdgeIt e(_graph, n); e != INVALID; ++e) {
568 if ((*_flow)[e] > 0 && -(*_red_cost)[e] < 0) {
569 delta = (*_flow)[e] <= _excess[n] ? (*_flow)[e] : _excess[n];
570 t = _graph.source(e);
572 // Push-look-ahead heuristic
573 Capacity ahead = -_excess[t];
574 for (OutEdgeIt oe(_graph, t); oe != INVALID; ++oe) {
575 if (_capacity[oe] - (*_flow)[oe] > 0 && (*_red_cost)[oe] < 0)
576 ahead += _capacity[oe] - (*_flow)[oe];
578 for (InEdgeIt ie(_graph, t); ie != INVALID; ++ie) {
579 if ((*_flow)[ie] > 0 && -(*_red_cost)[ie] < 0)
580 ahead += (*_flow)[ie];
582 if (ahead < 0) ahead = 0;
584 // Pushing flow along the edge
586 (*_flow)[e] -= ahead;
589 active_nodes.push_front(t);
591 relabel_enabled = false;
594 (*_flow)[e] -= delta;
597 if (_excess[t] > 0 && _excess[t] <= delta)
598 active_nodes.push_back(t);
601 if (_excess[n] == 0) break;
606 if (relabel_enabled && (_excess[n] > 0 || hyper[n])) {
607 // Performing relabel operation if the node is still active
608 LCost min_red_cost = std::numeric_limits<LCost>::max();
609 for (OutEdgeIt oe(_graph, n); oe != INVALID; ++oe) {
610 if ( _capacity[oe] - (*_flow)[oe] > 0 &&
611 (*_red_cost)[oe] < min_red_cost )
612 min_red_cost = (*_red_cost)[oe];
614 for (InEdgeIt ie(_graph, n); ie != INVALID; ++ie) {
615 if ((*_flow)[ie] > 0 && -(*_red_cost)[ie] < min_red_cost)
616 min_red_cost = -(*_red_cost)[ie];
618 (*_potential)[n] -= min_red_cost + _epsilon;
622 // Removing active nodes with non-positive excess
623 while ( active_nodes.size() > 0 &&
624 _excess[active_nodes[0]] <= 0 &&
625 !hyper[active_nodes[0]] ) {
626 active_nodes.pop_front();
631 // Computing node potentials for the original costs
632 ResidualCostMap<CostMap> res_cost(_orig_cost);
633 BellmanFord< ResGraph, ResidualCostMap<CostMap> >
634 bf(*_res_graph, res_cost);
635 bf.init(0); bf.start();
636 for (NodeIt n(_graph); n != INVALID; ++n)
637 (*_potential)[n] = bf.dist(n);
639 // Handling non-zero lower bounds
641 for (EdgeIt e(_graph); e != INVALID; ++e)
642 (*_flow)[e] += (*_lower)[e];
647 }; //class CostScaling
653 #endif //LEMON_COST_SCALING_H