Rel.07 NEWS - 3. round
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
25 /// \brief Capacity scaling algorithm for finding a minimum cost flow.
28 #include <lemon/bin_heap.h>
32 /// \addtogroup min_cost_flow
35 /// \brief Implementation of the capacity scaling algorithm for
36 /// finding a minimum cost flow.
38 /// \ref CapacityScaling implements the capacity scaling version
39 /// of the successive shortest path algorithm for finding a minimum
42 /// \tparam Graph The directed graph type the algorithm runs on.
43 /// \tparam LowerMap The type of the lower bound map.
44 /// \tparam CapacityMap The type of the capacity (upper bound) map.
45 /// \tparam CostMap The type of the cost (length) map.
46 /// \tparam SupplyMap The type of the supply map.
49 /// - Edge capacities and costs should be \e non-negative \e integers.
50 /// - Supply values should be \e signed \e integers.
51 /// - The value types of the maps should be convertible to each other.
52 /// - \c CostMap::Value must be signed type.
54 /// \author Peter Kovacs
56 template < typename Graph,
57 typename LowerMap = typename Graph::template EdgeMap<int>,
58 typename CapacityMap = typename Graph::template EdgeMap<int>,
59 typename CostMap = typename Graph::template EdgeMap<int>,
60 typename SupplyMap = typename Graph::template NodeMap<int> >
63 GRAPH_TYPEDEFS(typename Graph);
65 typedef typename CapacityMap::Value Capacity;
66 typedef typename CostMap::Value Cost;
67 typedef typename SupplyMap::Value Supply;
68 typedef typename Graph::template EdgeMap<Capacity> CapacityEdgeMap;
69 typedef typename Graph::template NodeMap<Supply> SupplyNodeMap;
70 typedef typename Graph::template NodeMap<Edge> PredMap;
74 /// The type of the flow map.
75 typedef typename Graph::template EdgeMap<Capacity> FlowMap;
76 /// The type of the potential map.
77 typedef typename Graph::template NodeMap<Cost> PotentialMap;
81 /// \brief Special implementation of the \ref Dijkstra algorithm
82 /// for finding shortest paths in the residual network.
84 /// \ref ResidualDijkstra is a special implementation of the
85 /// \ref Dijkstra algorithm for finding shortest paths in the
86 /// residual network of the graph with respect to the reduced edge
87 /// costs and modifying the node potentials according to the
88 /// distance of the nodes.
89 class ResidualDijkstra
91 typedef typename Graph::template NodeMap<int> HeapCrossRef;
92 typedef BinHeap<Cost, HeapCrossRef> Heap;
96 // The directed graph the algorithm runs on
100 const FlowMap &_flow;
101 const CapacityEdgeMap &_res_cap;
102 const CostMap &_cost;
103 const SupplyNodeMap &_excess;
104 PotentialMap &_potential;
110 // The processed (i.e. permanently labeled) nodes
111 std::vector<Node> _proc_nodes;
116 ResidualDijkstra( const Graph &graph,
118 const CapacityEdgeMap &res_cap,
120 const SupplyMap &excess,
121 PotentialMap &potential,
123 _graph(graph), _flow(flow), _res_cap(res_cap), _cost(cost),
124 _excess(excess), _potential(potential), _dist(graph),
128 /// Runs the algorithm from the given source node.
129 Node run(Node s, Capacity delta = 1) {
130 HeapCrossRef heap_cross_ref(_graph, Heap::PRE_HEAP);
131 Heap heap(heap_cross_ref);
137 while (!heap.empty() && _excess[heap.top()] > -delta) {
138 Node u = heap.top(), v;
139 Cost d = heap.prio() + _potential[u], nd;
140 _dist[u] = heap.prio();
142 _proc_nodes.push_back(u);
144 // Traversing outgoing edges
145 for (OutEdgeIt e(_graph, u); e != INVALID; ++e) {
146 if (_res_cap[e] >= delta) {
147 v = _graph.target(e);
148 switch(heap.state(v)) {
150 heap.push(v, d + _cost[e] - _potential[v]);
154 nd = d + _cost[e] - _potential[v];
156 heap.decrease(v, nd);
160 case Heap::POST_HEAP:
166 // Traversing incoming edges
167 for (InEdgeIt e(_graph, u); e != INVALID; ++e) {
168 if (_flow[e] >= delta) {
169 v = _graph.source(e);
170 switch(heap.state(v)) {
172 heap.push(v, d - _cost[e] - _potential[v]);
176 nd = d - _cost[e] - _potential[v];
178 heap.decrease(v, nd);
182 case Heap::POST_HEAP:
188 if (heap.empty()) return INVALID;
190 // Updating potentials of processed nodes
192 Cost t_dist = heap.prio();
193 for (int i = 0; i < int(_proc_nodes.size()); ++i)
194 _potential[_proc_nodes[i]] += _dist[_proc_nodes[i]] - t_dist;
199 }; //class ResidualDijkstra
203 // The directed graph the algorithm runs on
205 // The original lower bound map
206 const LowerMap *_lower;
207 // The modified capacity map
208 CapacityEdgeMap _capacity;
209 // The original cost map
210 const CostMap &_cost;
211 // The modified supply map
212 SupplyNodeMap _supply;
215 // Edge map of the current flow
218 // Node map of the current potentials
219 PotentialMap *_potential;
220 bool _local_potential;
222 // The residual capacity map
223 CapacityEdgeMap _res_cap;
225 SupplyNodeMap _excess;
226 // The excess nodes (i.e. nodes with positive excess)
227 std::vector<Node> _excess_nodes;
228 // The deficit nodes (i.e. nodes with negative excess)
229 std::vector<Node> _deficit_nodes;
231 // The delta parameter used for capacity scaling
233 // The maximum number of phases
238 // Implementation of the Dijkstra algorithm for finding augmenting
239 // shortest paths in the residual network
240 ResidualDijkstra *_dijkstra;
244 /// \brief General constructor (with lower bounds).
246 /// General constructor (with lower bounds).
248 /// \param graph The directed graph the algorithm runs on.
249 /// \param lower The lower bounds of the edges.
250 /// \param capacity The capacities (upper bounds) of the edges.
251 /// \param cost The cost (length) values of the edges.
252 /// \param supply The supply values of the nodes (signed).
253 CapacityScaling( const Graph &graph,
254 const LowerMap &lower,
255 const CapacityMap &capacity,
257 const SupplyMap &supply ) :
258 _graph(graph), _lower(&lower), _capacity(graph), _cost(cost),
259 _supply(graph), _flow(0), _local_flow(false),
260 _potential(0), _local_potential(false),
261 _res_cap(graph), _excess(graph), _pred(graph)
263 // Removing non-zero lower bounds
264 _capacity = subMap(capacity, lower);
265 _res_cap = _capacity;
267 for (NodeIt n(_graph); n != INVALID; ++n) {
268 Supply s = supply[n];
269 for (InEdgeIt e(_graph, n); e != INVALID; ++e)
271 for (OutEdgeIt e(_graph, n); e != INVALID; ++e)
276 _valid_supply = sum == 0;
279 /// \brief General constructor (without lower bounds).
281 /// General constructor (without lower bounds).
283 /// \param graph The directed graph the algorithm runs on.
284 /// \param capacity The capacities (upper bounds) of the edges.
285 /// \param cost The cost (length) values of the edges.
286 /// \param supply The supply values of the nodes (signed).
287 CapacityScaling( const Graph &graph,
288 const CapacityMap &capacity,
290 const SupplyMap &supply ) :
291 _graph(graph), _lower(NULL), _capacity(capacity), _cost(cost),
292 _supply(supply), _flow(0), _local_flow(false),
293 _potential(0), _local_potential(false),
294 _res_cap(capacity), _excess(graph), _pred(graph)
296 // Checking the sum of supply values
298 for (NodeIt n(_graph); n != INVALID; ++n) sum += _supply[n];
299 _valid_supply = sum == 0;
302 /// \brief Simple constructor (with lower bounds).
304 /// Simple constructor (with lower bounds).
306 /// \param graph The directed graph the algorithm runs on.
307 /// \param lower The lower bounds of the edges.
308 /// \param capacity The capacities (upper bounds) of the edges.
309 /// \param cost The cost (length) values of the edges.
310 /// \param s The source node.
311 /// \param t The target node.
312 /// \param flow_value The required amount of flow from node \c s
313 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
314 CapacityScaling( const Graph &graph,
315 const LowerMap &lower,
316 const CapacityMap &capacity,
319 Supply flow_value ) :
320 _graph(graph), _lower(&lower), _capacity(graph), _cost(cost),
321 _supply(graph), _flow(0), _local_flow(false),
322 _potential(0), _local_potential(false),
323 _res_cap(graph), _excess(graph), _pred(graph)
325 // Removing non-zero lower bounds
326 _capacity = subMap(capacity, lower);
327 _res_cap = _capacity;
328 for (NodeIt n(_graph); n != INVALID; ++n) {
330 if (n == s) sum = flow_value;
331 if (n == t) sum = -flow_value;
332 for (InEdgeIt e(_graph, n); e != INVALID; ++e)
334 for (OutEdgeIt e(_graph, n); e != INVALID; ++e)
338 _valid_supply = true;
341 /// \brief Simple constructor (without lower bounds).
343 /// Simple constructor (without lower bounds).
345 /// \param graph The directed graph the algorithm runs on.
346 /// \param capacity The capacities (upper bounds) of the edges.
347 /// \param cost The cost (length) values of the edges.
348 /// \param s The source node.
349 /// \param t The target node.
350 /// \param flow_value The required amount of flow from node \c s
351 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
352 CapacityScaling( const Graph &graph,
353 const CapacityMap &capacity,
356 Supply flow_value ) :
357 _graph(graph), _lower(NULL), _capacity(capacity), _cost(cost),
358 _supply(graph, 0), _flow(0), _local_flow(false),
359 _potential(0), _local_potential(false),
360 _res_cap(capacity), _excess(graph), _pred(graph)
362 _supply[s] = flow_value;
363 _supply[t] = -flow_value;
364 _valid_supply = true;
369 if (_local_flow) delete _flow;
370 if (_local_potential) delete _potential;
374 /// \brief Sets the flow map.
376 /// Sets the flow map.
378 /// \return \c (*this)
379 CapacityScaling& flowMap(FlowMap &map) {
388 /// \brief Sets the potential map.
390 /// Sets the potential map.
392 /// \return \c (*this)
393 CapacityScaling& potentialMap(PotentialMap &map) {
394 if (_local_potential) {
396 _local_potential = false;
402 /// \name Execution control
403 /// The only way to execute the algorithm is to call the run()
408 /// \brief Runs the algorithm.
410 /// Runs the algorithm.
412 /// \param scaling Enable or disable capacity scaling.
413 /// If the maximum edge capacity and/or the amount of total supply
414 /// is rather small, the algorithm could be slightly faster without
417 /// \return \c true if a feasible flow can be found.
418 bool run(bool scaling = true) {
419 return init(scaling) && start();
424 /// \name Query Functions
425 /// The result of the algorithm can be obtained using these
427 /// \n run() must be called before using them.
431 /// \brief Returns a const reference to the edge map storing the
434 /// Returns a const reference to the edge map storing the found flow.
436 /// \pre \ref run() must be called before using this function.
437 const FlowMap& flowMap() const {
441 /// \brief Returns a const reference to the node map storing the
442 /// found potentials (the dual solution).
444 /// Returns a const reference to the node map storing the found
445 /// potentials (the dual solution).
447 /// \pre \ref run() must be called before using this function.
448 const PotentialMap& potentialMap() const {
452 /// \brief Returns the flow on the given edge.
454 /// Returns the flow on the given edge.
456 /// \pre \ref run() must be called before using this function.
457 Capacity flow(const Edge& edge) const {
458 return (*_flow)[edge];
461 /// \brief Returns the potential of the given node.
463 /// Returns the potential of the given node.
465 /// \pre \ref run() must be called before using this function.
466 Cost potential(const Node& node) const {
467 return (*_potential)[node];
470 /// \brief Returns the total cost of the found flow.
472 /// Returns the total cost of the found flow. The complexity of the
473 /// function is \f$ O(e) \f$.
475 /// \pre \ref run() must be called before using this function.
476 Cost totalCost() const {
478 for (EdgeIt e(_graph); e != INVALID; ++e)
479 c += (*_flow)[e] * _cost[e];
487 /// Initializes the algorithm.
488 bool init(bool scaling) {
489 if (!_valid_supply) return false;
493 _flow = new FlowMap(_graph);
497 _potential = new PotentialMap(_graph);
498 _local_potential = true;
500 for (EdgeIt e(_graph); e != INVALID; ++e) (*_flow)[e] = 0;
501 for (NodeIt n(_graph); n != INVALID; ++n) (*_potential)[n] = 0;
504 _dijkstra = new ResidualDijkstra( _graph, *_flow, _res_cap, _cost,
505 _excess, *_potential, _pred );
507 // Initializing delta value
510 Supply max_sup = 0, max_dem = 0;
511 for (NodeIt n(_graph); n != INVALID; ++n) {
512 if ( _supply[n] > max_sup) max_sup = _supply[n];
513 if (-_supply[n] > max_dem) max_dem = -_supply[n];
515 Capacity max_cap = 0;
516 for (EdgeIt e(_graph); e != INVALID; ++e) {
517 if (_capacity[e] > max_cap) max_cap = _capacity[e];
519 max_sup = std::min(std::min(max_sup, max_dem), max_cap);
521 for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2)
533 return startWithScaling();
535 return startWithoutScaling();
538 /// Executes the capacity scaling algorithm.
539 bool startWithScaling() {
540 // Processing capacity scaling phases
545 // Saturating all edges not satisfying the optimality condition
546 for (EdgeIt e(_graph); e != INVALID; ++e) {
547 Node u = _graph.source(e), v = _graph.target(e);
548 Cost c = _cost[e] + (*_potential)[u] - (*_potential)[v];
549 if (c < 0 && _res_cap[e] >= _delta) {
550 _excess[u] -= _res_cap[e];
551 _excess[v] += _res_cap[e];
552 (*_flow)[e] = _capacity[e];
555 else if (c > 0 && (*_flow)[e] >= _delta) {
556 _excess[u] += (*_flow)[e];
557 _excess[v] -= (*_flow)[e];
559 _res_cap[e] = _capacity[e];
563 // Finding excess nodes and deficit nodes
564 _excess_nodes.clear();
565 _deficit_nodes.clear();
566 for (NodeIt n(_graph); n != INVALID; ++n) {
567 if (_excess[n] >= _delta) _excess_nodes.push_back(n);
568 if (_excess[n] <= -_delta) _deficit_nodes.push_back(n);
572 // Finding augmenting shortest paths
573 while (next_node < int(_excess_nodes.size())) {
574 // Checking deficit nodes
576 bool delta_deficit = false;
577 for (int i = 0; i < int(_deficit_nodes.size()); ++i) {
578 if (_excess[_deficit_nodes[i]] <= -_delta) {
579 delta_deficit = true;
583 if (!delta_deficit) break;
587 s = _excess_nodes[next_node];
588 if ((t = _dijkstra->run(s, _delta)) == INVALID) {
596 // Augmenting along a shortest path from s to t.
597 Capacity d = std::min(_excess[s], -_excess[t]);
601 while ((e = _pred[u]) != INVALID) {
603 if (u == _graph.target(e)) {
605 u = _graph.source(e);
608 u = _graph.target(e);
614 while ((e = _pred[u]) != INVALID) {
615 if (u == _graph.target(e)) {
618 u = _graph.source(e);
622 u = _graph.target(e);
628 if (_excess[s] < _delta) ++next_node;
631 if (_delta == 1) break;
632 if (++phase_cnt > _phase_num / 4) factor = 2;
633 _delta = _delta <= factor ? 1 : _delta / factor;
636 // Handling non-zero lower bounds
638 for (EdgeIt e(_graph); e != INVALID; ++e)
639 (*_flow)[e] += (*_lower)[e];
644 /// Executes the successive shortest path algorithm.
645 bool startWithoutScaling() {
646 // Finding excess nodes
647 for (NodeIt n(_graph); n != INVALID; ++n)
648 if (_excess[n] > 0) _excess_nodes.push_back(n);
649 if (_excess_nodes.size() == 0) return true;
652 // Finding shortest paths
654 while ( _excess[_excess_nodes[next_node]] > 0 ||
655 ++next_node < int(_excess_nodes.size()) )
658 s = _excess_nodes[next_node];
659 if ((t = _dijkstra->run(s)) == INVALID) return false;
661 // Augmenting along a shortest path from s to t
662 Capacity d = std::min(_excess[s], -_excess[t]);
666 while ((e = _pred[u]) != INVALID) {
668 if (u == _graph.target(e)) {
670 u = _graph.source(e);
673 u = _graph.target(e);
679 while ((e = _pred[u]) != INVALID) {
680 if (u == _graph.target(e)) {
683 u = _graph.source(e);
687 u = _graph.target(e);
694 // Handling non-zero lower bounds
696 for (EdgeIt e(_graph); e != INVALID; ++e)
697 (*_flow)[e] += (*_lower)[e];
702 }; //class CapacityScaling
708 #endif //LEMON_CAPACITY_SCALING_H