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_CANCEL_AND_TIGHTEN_H
20 #define LEMON_CANCEL_AND_TIGHTEN_H
22 /// \ingroup min_cost_flow
25 /// \brief Cancel and Tighten algorithm for finding a minimum cost flow.
29 #include <lemon/circulation.h>
30 #include <lemon/bellman_ford.h>
31 #include <lemon/min_mean_cycle.h>
32 #include <lemon/graph_adaptor.h>
33 #include <lemon/tolerance.h>
34 #include <lemon/math.h>
36 #include <lemon/static_graph.h>
40 /// \addtogroup min_cost_flow
43 /// \brief Implementation of the Cancel and Tighten algorithm for
44 /// finding a minimum cost flow.
46 /// \ref CancelAndTighten implements the Cancel and Tighten algorithm for
47 /// finding a minimum cost flow.
49 /// \tparam Graph The directed graph type the algorithm runs on.
50 /// \tparam LowerMap The type of the lower bound map.
51 /// \tparam CapacityMap The type of the capacity (upper bound) map.
52 /// \tparam CostMap The type of the cost (length) map.
53 /// \tparam SupplyMap The type of the supply map.
56 /// - Edge capacities and costs should be \e non-negative \e integers.
57 /// - Supply values should be \e signed \e integers.
58 /// - The value types of the maps should be convertible to each other.
59 /// - \c CostMap::Value must be signed type.
61 /// \author Peter Kovacs
62 template < typename Graph,
63 typename LowerMap = typename Graph::template EdgeMap<int>,
64 typename CapacityMap = typename Graph::template EdgeMap<int>,
65 typename CostMap = typename Graph::template EdgeMap<int>,
66 typename SupplyMap = typename Graph::template NodeMap<int> >
67 class CancelAndTighten
69 GRAPH_TYPEDEFS(typename Graph);
71 typedef typename CapacityMap::Value Capacity;
72 typedef typename CostMap::Value Cost;
73 typedef typename SupplyMap::Value Supply;
74 typedef typename Graph::template EdgeMap<Capacity> CapacityEdgeMap;
75 typedef typename Graph::template NodeMap<Supply> SupplyNodeMap;
77 typedef ResGraphAdaptor< const Graph, Capacity,
78 CapacityEdgeMap, CapacityEdgeMap > ResGraph;
82 /// The type of the flow map.
83 typedef typename Graph::template EdgeMap<Capacity> FlowMap;
84 /// The type of the potential map.
85 typedef typename Graph::template NodeMap<Cost> PotentialMap;
89 /// \brief Map adaptor class for handling residual edge costs.
91 /// Map adaptor class for handling residual edge costs.
92 class ResidualCostMap : public MapBase<typename ResGraph::Edge, Cost>
94 typedef typename ResGraph::Edge Edge;
98 const CostMap &_cost_map;
103 ResidualCostMap(const CostMap &cost_map) : _cost_map(cost_map) {}
106 Cost operator[](const Edge &e) const {
107 return ResGraph::forward(e) ? _cost_map[e] : -_cost_map[e];
110 }; //class ResidualCostMap
112 /// \brief Map adaptor class for handling reduced edge costs.
114 /// Map adaptor class for handling reduced edge costs.
115 class ReducedCostMap : public MapBase<Edge, Cost>
120 const CostMap &_cost_map;
121 const PotentialMap &_pot_map;
126 ReducedCostMap( const Graph &gr,
127 const CostMap &cost_map,
128 const PotentialMap &pot_map ) :
129 _gr(gr), _cost_map(cost_map), _pot_map(pot_map) {}
132 inline Cost operator[](const Edge &e) const {
133 return _cost_map[e] + _pot_map[_gr.source(e)]
134 - _pot_map[_gr.target(e)];
137 }; //class ReducedCostMap
139 struct BFOperationTraits {
140 static double zero() { return 0; }
142 static double infinity() {
143 return std::numeric_limits<double>::infinity();
146 static double plus(const double& left, const double& right) {
150 static bool less(const double& left, const double& right) {
151 return left + 1e-6 < right;
153 }; // class BFOperationTraits
157 // The directed graph the algorithm runs on
159 // The original lower bound map
160 const LowerMap *_lower;
161 // The modified capacity map
162 CapacityEdgeMap _capacity;
163 // The original cost map
164 const CostMap &_cost;
165 // The modified supply map
166 SupplyNodeMap _supply;
169 // Edge map of the current flow
172 // Node map of the current potentials
173 PotentialMap *_potential;
174 bool _local_potential;
176 // The residual graph
177 ResGraph *_res_graph;
178 // The residual cost map
179 ResidualCostMap _res_cost;
183 /// \brief General constructor (with lower bounds).
185 /// General constructor (with lower bounds).
187 /// \param graph The directed graph the algorithm runs on.
188 /// \param lower The lower bounds of the edges.
189 /// \param capacity The capacities (upper bounds) of the edges.
190 /// \param cost The cost (length) values of the edges.
191 /// \param supply The supply values of the nodes (signed).
192 CancelAndTighten( const Graph &graph,
193 const LowerMap &lower,
194 const CapacityMap &capacity,
196 const SupplyMap &supply ) :
197 _graph(graph), _lower(&lower), _capacity(capacity), _cost(cost),
198 _supply(supply), _flow(NULL), _local_flow(false),
199 _potential(NULL), _local_potential(false),
200 _res_graph(NULL), _res_cost(_cost)
202 // Check the sum of supply values
204 for (NodeIt n(_graph); n != INVALID; ++n) sum += _supply[n];
205 _valid_supply = sum == 0;
207 // Remove non-zero lower bounds
208 for (EdgeIt e(_graph); e != INVALID; ++e) {
210 _capacity[e] -= lower[e];
211 _supply[_graph.source(e)] -= lower[e];
212 _supply[_graph.target(e)] += lower[e];
217 /// \brief General constructor (without lower bounds).
219 /// General constructor (without lower bounds).
221 /// \param graph The directed graph the algorithm runs on.
222 /// \param capacity The capacities (upper bounds) of the edges.
223 /// \param cost The cost (length) values of the edges.
224 /// \param supply The supply values of the nodes (signed).
225 CancelAndTighten( const Graph &graph,
226 const CapacityMap &capacity,
228 const SupplyMap &supply ) :
229 _graph(graph), _lower(NULL), _capacity(capacity), _cost(cost),
230 _supply(supply), _flow(NULL), _local_flow(false),
231 _potential(NULL), _local_potential(false),
232 _res_graph(NULL), _res_cost(_cost)
234 // Check the sum of supply values
236 for (NodeIt n(_graph); n != INVALID; ++n) sum += _supply[n];
237 _valid_supply = sum == 0;
240 /// \brief Simple constructor (with lower bounds).
242 /// Simple constructor (with lower bounds).
244 /// \param graph The directed graph the algorithm runs on.
245 /// \param lower The lower bounds of the edges.
246 /// \param capacity The capacities (upper bounds) of the edges.
247 /// \param cost The cost (length) values of the edges.
248 /// \param s The source node.
249 /// \param t The target node.
250 /// \param flow_value The required amount of flow from node \c s
251 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
252 CancelAndTighten( const Graph &graph,
253 const LowerMap &lower,
254 const CapacityMap &capacity,
257 Supply flow_value ) :
258 _graph(graph), _lower(&lower), _capacity(capacity), _cost(cost),
259 _supply(graph, 0), _flow(NULL), _local_flow(false),
260 _potential(NULL), _local_potential(false),
261 _res_graph(NULL), _res_cost(_cost)
263 // Remove non-zero lower bounds
264 _supply[s] = flow_value;
265 _supply[t] = -flow_value;
266 for (EdgeIt e(_graph); e != INVALID; ++e) {
268 _capacity[e] -= lower[e];
269 _supply[_graph.source(e)] -= lower[e];
270 _supply[_graph.target(e)] += lower[e];
273 _valid_supply = true;
276 /// \brief Simple constructor (without lower bounds).
278 /// Simple constructor (without lower bounds).
280 /// \param graph The directed graph the algorithm runs on.
281 /// \param capacity The capacities (upper bounds) of the edges.
282 /// \param cost The cost (length) values of the edges.
283 /// \param s The source node.
284 /// \param t The target node.
285 /// \param flow_value The required amount of flow from node \c s
286 /// to node \c t (i.e. the supply of \c s and the demand of \c t).
287 CancelAndTighten( const Graph &graph,
288 const CapacityMap &capacity,
291 Supply flow_value ) :
292 _graph(graph), _lower(NULL), _capacity(capacity), _cost(cost),
293 _supply(graph, 0), _flow(NULL), _local_flow(false),
294 _potential(NULL), _local_potential(false),
295 _res_graph(NULL), _res_cost(_cost)
297 _supply[s] = flow_value;
298 _supply[t] = -flow_value;
299 _valid_supply = true;
303 ~CancelAndTighten() {
304 if (_local_flow) delete _flow;
305 if (_local_potential) delete _potential;
309 /// \brief Set the flow map.
311 /// Set the flow map.
313 /// \return \c (*this)
314 CancelAndTighten& flowMap(FlowMap &map) {
323 /// \brief Set the potential map.
325 /// Set the potential map.
327 /// \return \c (*this)
328 CancelAndTighten& potentialMap(PotentialMap &map) {
329 if (_local_potential) {
331 _local_potential = false;
337 /// \name Execution control
341 /// \brief Run the algorithm.
343 /// Run the algorithm.
345 /// \return \c true if a feasible flow can be found.
347 return init() && start();
352 /// \name Query Functions
353 /// The result of the algorithm can be obtained using these
355 /// \ref lemon::CancelAndTighten::run() "run()" must be called before
360 /// \brief Return a const reference to the edge map storing the
363 /// Return a const reference to the edge map storing the found flow.
365 /// \pre \ref run() must be called before using this function.
366 const FlowMap& flowMap() const {
370 /// \brief Return a const reference to the node map storing the
371 /// found potentials (the dual solution).
373 /// Return a const reference to the node map storing the found
374 /// potentials (the dual solution).
376 /// \pre \ref run() must be called before using this function.
377 const PotentialMap& potentialMap() const {
381 /// \brief Return the flow on the given edge.
383 /// Return the flow on the given edge.
385 /// \pre \ref run() must be called before using this function.
386 Capacity flow(const Edge& edge) const {
387 return (*_flow)[edge];
390 /// \brief Return the potential of the given node.
392 /// Return the potential of the given node.
394 /// \pre \ref run() must be called before using this function.
395 Cost potential(const Node& node) const {
396 return (*_potential)[node];
399 /// \brief Return the total cost of the found flow.
401 /// Return the total cost of the found flow. The complexity of the
402 /// function is \f$ O(e) \f$.
404 /// \pre \ref run() must be called before using this function.
405 Cost totalCost() const {
407 for (EdgeIt e(_graph); e != INVALID; ++e)
408 c += (*_flow)[e] * _cost[e];
416 /// Initialize the algorithm.
418 if (!_valid_supply) return false;
420 // Initialize flow and potential maps
422 _flow = new FlowMap(_graph);
426 _potential = new PotentialMap(_graph);
427 _local_potential = true;
430 _res_graph = new ResGraph(_graph, _capacity, *_flow);
432 // Find a feasible flow using Circulation
433 Circulation< Graph, ConstMap<Edge, Capacity>,
434 CapacityEdgeMap, SupplyMap >
435 circulation( _graph, constMap<Edge>(Capacity(0)),
436 _capacity, _supply );
437 return circulation.flowMap(*_flow).run();
441 const double LIMIT_FACTOR = 0.01;
442 const int MIN_LIMIT = 3;
444 typedef typename Graph::template NodeMap<double> FloatPotentialMap;
445 typedef typename Graph::template NodeMap<int> LevelMap;
446 typedef typename Graph::template NodeMap<bool> BoolNodeMap;
447 typedef typename Graph::template NodeMap<Node> PredNodeMap;
448 typedef typename Graph::template NodeMap<Edge> PredEdgeMap;
449 typedef typename ResGraph::template EdgeMap<double> ResShiftCostMap;
450 FloatPotentialMap pi(_graph);
451 LevelMap level(_graph);
452 BoolNodeMap reached(_graph);
453 BoolNodeMap processed(_graph);
454 PredNodeMap pred_node(_graph);
455 PredEdgeMap pred_edge(_graph);
456 int node_num = countNodes(_graph);
457 typedef std::pair<Edge, bool> pair;
458 std::vector<pair> stack(node_num);
459 std::vector<Node> proc_vector(node_num);
460 ResShiftCostMap shift_cost(*_res_graph);
462 Tolerance<double> tol;
470 // Initialize epsilon and the node potentials
472 for (EdgeIt e(_graph); e != INVALID; ++e) {
473 if (_capacity[e] - (*_flow)[e] > 0 && _cost[e] < -epsilon)
475 else if ((*_flow)[e] > 0 && _cost[e] > epsilon)
478 for (NodeIt v(_graph); v != INVALID; ++v) {
483 int limit = int(LIMIT_FACTOR * node_num);
484 if (limit < MIN_LIMIT) limit = MIN_LIMIT;
486 while (epsilon * node_num >= 1) {
488 // Find and cancel cycles in the admissible graph using DFS
489 for (NodeIt n(_graph); n != INVALID; ++n) {
491 processed[n] = false;
496 for (NodeIt start(_graph); start != INVALID; ++start) {
497 if (reached[start]) continue;
500 reached[start] = true;
501 pred_edge[start] = INVALID;
502 pred_node[start] = INVALID;
504 // Find the first admissible residual outgoing edge
505 double p = pi[start];
507 _graph.firstOut(e, start);
508 while ( e != INVALID && (_capacity[e] - (*_flow)[e] == 0 ||
509 !tol.negative(_cost[e] + p - pi[_graph.target(e)])) )
512 stack[++stack_head] = pair(e, true);
515 _graph.firstIn(e, start);
516 while ( e != INVALID && ((*_flow)[e] == 0 ||
517 !tol.negative(-_cost[e] + p - pi[_graph.source(e)])) )
520 stack[++stack_head] = pair(e, false);
523 processed[start] = true;
524 proc_vector[++proc_head] = start;
528 while (stack_head >= 0) {
529 Edge se = stack[stack_head].first;
530 bool sf = stack[stack_head].second;
533 u = _graph.source(se);
534 v = _graph.target(se);
536 u = _graph.target(se);
537 v = _graph.source(se);
541 // A new node is reached
545 // Find the first admissible residual outgoing edge
548 _graph.firstOut(e, v);
549 while ( e != INVALID && (_capacity[e] - (*_flow)[e] == 0 ||
550 !tol.negative(_cost[e] + p - pi[_graph.target(e)])) )
553 stack[++stack_head] = pair(e, true);
556 _graph.firstIn(e, v);
557 while ( e != INVALID && ((*_flow)[e] == 0 ||
558 !tol.negative(-_cost[e] + p - pi[_graph.source(e)])) )
560 stack[++stack_head] = pair(e, false);
566 Capacity d, delta = sf ? _capacity[se] - (*_flow)[se] :
568 for (n = u; n != v; n = pred_node[n]) {
569 d = _graph.target(pred_edge[n]) == n ?
570 _capacity[pred_edge[n]] - (*_flow)[pred_edge[n]] :
571 (*_flow)[pred_edge[n]];
579 std::cout << "CYCLE FOUND: ";
581 std::cout << _cost[se] + pi[_graph.source(se)] - pi[_graph.target(se)];
583 std::cout << _graph.id(se) << ":" << -(_cost[se] + pi[_graph.source(se)] - pi[_graph.target(se)]);
584 for (n = u; n != v; n = pred_node[n]) {
585 if (_graph.target(pred_edge[n]) == n)
586 std::cout << " " << _cost[pred_edge[n]] + pi[_graph.source(pred_edge[n])] - pi[_graph.target(pred_edge[n])];
588 std::cout << " " << -(_cost[pred_edge[n]] + pi[_graph.source(pred_edge[n])] - pi[_graph.target(pred_edge[n])]);
592 // Augment along the cycle
593 (*_flow)[se] = sf ? (*_flow)[se] + delta :
594 (*_flow)[se] - delta;
595 for (n = u; n != v; n = pred_node[n]) {
596 if (_graph.target(pred_edge[n]) == n)
597 (*_flow)[pred_edge[n]] += delta;
599 (*_flow)[pred_edge[n]] -= delta;
601 for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
609 // Find the next admissible residual outgoing edge
611 Edge e = stack[stack_head].first;
612 if (!stack[stack_head].second) {
617 while ( e != INVALID && (_capacity[e] - (*_flow)[e] == 0 ||
618 !tol.negative(_cost[e] + p - pi[_graph.target(e)])) )
621 stack[stack_head] = pair(e, true);
624 _graph.firstIn(e, v);
626 while ( e != INVALID && ((*_flow)[e] == 0 ||
627 !tol.negative(-_cost[e] + p - pi[_graph.source(e)])) )
629 stack[stack_head] = pair(e, false);
633 while (stack_head >= 0 && stack[stack_head].first == INVALID) {
635 proc_vector[++proc_head] = v;
636 if (--stack_head >= 0) {
637 v = stack[stack_head].second ?
638 _graph.source(stack[stack_head].first) :
639 _graph.target(stack[stack_head].first);
640 // Find the next admissible residual outgoing edge
642 Edge e = stack[stack_head].first;
643 if (!stack[stack_head].second) {
648 while ( e != INVALID && (_capacity[e] - (*_flow)[e] == 0 ||
649 !tol.negative(_cost[e] + p - pi[_graph.target(e)])) )
652 stack[stack_head] = pair(e, true);
655 _graph.firstIn(e, v);
657 while ( e != INVALID && ((*_flow)[e] == 0 ||
658 !tol.negative(-_cost[e] + p - pi[_graph.source(e)])) )
660 stack[stack_head] = pair(e, false);
668 // Tighten potentials and epsilon
672 for (int i = proc_head; i >= 0; --i) {
673 Node v = proc_vector[i];
676 for (InEdgeIt e(_graph, v); e != INVALID; ++e) {
677 Node u = _graph.source(e);
678 if ( _capacity[e] - (*_flow)[e] > 0 &&
679 tol.negative(_cost[e] + pi[u] - p) &&
680 level[u] + 1 > l ) l = level[u] + 1;
682 for (OutEdgeIt e(_graph, v); e != INVALID; ++e) {
683 Node u = _graph.target(e);
684 if ( (*_flow)[e] > 0 &&
685 tol.negative(-_cost[e] + pi[u] - p) &&
686 level[u] + 1 > l ) l = level[u] + 1;
693 for (EdgeIt e(_graph); e != INVALID; ++e) {
694 Node u = _graph.source(e);
695 Node v = _graph.target(e);
696 if (_capacity[e] - (*_flow)[e] > 0 && level[u] - level[v] > 0) {
697 p = (_cost[e] + pi[u] - pi[v] + epsilon) /
698 (level[u] - level[v] + 1);
699 if (q < 0 || p < q) q = p;
701 else if ((*_flow)[e] > 0 && level[v] - level[u] > 0) {
702 p = (-_cost[e] - pi[u] + pi[v] + epsilon) /
703 (level[v] - level[u] + 1);
704 if (q < 0 || p < q) q = p;
707 for (NodeIt v(_graph); v != INVALID; ++v) {
708 pi[v] -= q * level[v];
713 for (EdgeIt e(_graph); e != INVALID; ++e) {
714 double curr = _cost[e] + pi[_graph.source(e)]
715 - pi[_graph.target(e)];
716 if (_capacity[e] - (*_flow)[e] > 0 && curr < -epsilon)
718 else if ((*_flow)[e] > 0 && curr > epsilon)
723 // Set epsilon to the minimum cycle mean
727 StaticGraph static_graph;
728 typename ResGraph::template NodeMap<typename StaticGraph::Node> node_ref(*_res_graph);
729 typename ResGraph::template EdgeMap<typename StaticGraph::Edge> edge_ref(*_res_graph);
730 static_graph.build(*_res_graph, node_ref, edge_ref);
731 typename StaticGraph::template NodeMap<double> static_pi(static_graph);
732 typename StaticGraph::template EdgeMap<double> static_cost(static_graph);
734 for (typename ResGraph::EdgeIt e(*_res_graph); e != INVALID; ++e)
735 static_cost[edge_ref[e]] = _res_cost[e];
737 MinMeanCycle<StaticGraph, typename StaticGraph::template EdgeMap<double> >
738 mmc(static_graph, static_cost);
741 epsilon = -mmc.cycleMean();
745 MinMeanCycle<ResGraph, ResidualCostMap> mmc(*_res_graph, _res_cost);
748 epsilon = -mmc.cycleMean();
751 // Compute feasible potentials for the current epsilon
752 for (typename StaticGraph::EdgeIt e(static_graph); e != INVALID; ++e)
753 static_cost[e] += epsilon;
754 typename BellmanFord<StaticGraph, typename StaticGraph::template EdgeMap<double> >::
755 template DefDistMap<typename StaticGraph::template NodeMap<double> >::
756 template DefOperationTraits<BFOperationTraits>::Create
757 bf(static_graph, static_cost);
758 bf.distMap(static_pi).init(0);
760 for (NodeIt n(_graph); n != INVALID; ++n)
761 pi[n] = static_pi[node_ref[n]];
764 for (typename ResGraph::EdgeIt e(*_res_graph); e != INVALID; ++e)
765 shift_cost[e] = _res_cost[e] + epsilon;
766 typename BellmanFord<ResGraph, ResShiftCostMap>::
767 template DefDistMap<FloatPotentialMap>::
768 template DefOperationTraits<BFOperationTraits>::Create
769 bf(*_res_graph, shift_cost);
770 bf.distMap(pi).init(0);
779 // std::cout << t1.realTime() << " " << t2.realTime() << " " << t3.realTime() << "\n";
781 // Handle non-zero lower bounds
783 for (EdgeIt e(_graph); e != INVALID; ++e)
784 (*_flow)[e] += (*_lower)[e];
789 }; //class CancelAndTighten
795 #endif //LEMON_CANCEL_AND_TIGHTEN_H