3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2007
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_CYCLE_CANCELING_H
20 #define LEMON_CYCLE_CANCELING_H
22 /// \ingroup min_cost_flow
25 /// \brief A cycle canceling algorithm for finding a minimum cost flow.
28 #include <lemon/circulation.h>
29 #include <lemon/graph_adaptor.h>
31 /// \brief The used cycle canceling method.
32 #define LIMITED_CYCLE_CANCELING
33 //#define MIN_MEAN_CYCLE_CANCELING
35 #ifdef LIMITED_CYCLE_CANCELING
36 #include <lemon/bellman_ford.h>
37 /// \brief The maximum number of iterations for the first execution
38 /// of the \ref lemon::BellmanFord "Bellman-Ford" algorithm.
39 #define STARTING_LIMIT 2
40 /// \brief The iteration limit for the
41 /// \ref lemon::BellmanFord "Bellman-Ford" algorithm is multiplied by
42 /// <tt>ALPHA_MUL % ALPHA_DIV</tt> in every round.
44 /// \brief The iteration limit for the
45 /// \ref lemon::BellmanFord "Bellman-Ford" algorithm is multiplied by
46 /// <tt>ALPHA_MUL % ALPHA_DIV</tt> in every round.
49 //#define _ONLY_ONE_CYCLE_
50 //#define _DEBUG_ITER_
53 #ifdef MIN_MEAN_CYCLE_CANCELING
54 #include <lemon/min_mean_cycle.h>
55 #include <lemon/path.h>
60 /// \addtogroup min_cost_flow
63 /// \brief Implementation of a cycle canceling algorithm for finding
64 /// a minimum cost flow.
66 /// \ref lemon::CycleCanceling "CycleCanceling" implements a cycle
67 /// canceling algorithm for finding a minimum cost flow.
69 /// \param Graph The directed graph type the algorithm runs on.
70 /// \param LowerMap The type of the lower bound map.
71 /// \param CapacityMap The type of the capacity (upper bound) map.
72 /// \param CostMap The type of the cost (length) map.
73 /// \param SupplyMap The type of the supply map.
76 /// - Edge capacities and costs should be nonnegative integers.
77 /// However \c CostMap::Value should be signed type.
78 /// - Supply values should be integers.
79 /// - \c LowerMap::Value must be convertible to
80 /// \c CapacityMap::Value and \c CapacityMap::Value must be
81 /// convertible to \c SupplyMap::Value.
83 /// \author Peter Kovacs
85 template < typename Graph,
86 typename LowerMap = typename Graph::template EdgeMap<int>,
87 typename CapacityMap = LowerMap,
88 typename CostMap = typename Graph::template EdgeMap<int>,
89 typename SupplyMap = typename Graph::template NodeMap
90 <typename CapacityMap::Value> >
93 typedef typename Graph::Node Node;
94 typedef typename Graph::NodeIt NodeIt;
95 typedef typename Graph::Edge Edge;
96 typedef typename Graph::EdgeIt EdgeIt;
97 typedef typename Graph::InEdgeIt InEdgeIt;
98 typedef typename Graph::OutEdgeIt OutEdgeIt;
100 typedef typename LowerMap::Value Lower;
101 typedef typename CapacityMap::Value Capacity;
102 typedef typename CostMap::Value Cost;
103 typedef typename SupplyMap::Value Supply;
104 typedef typename Graph::template EdgeMap<Capacity> CapacityRefMap;
105 typedef typename Graph::template NodeMap<Supply> SupplyRefMap;
107 typedef ResGraphAdaptor< const Graph, Capacity,
108 CapacityRefMap, CapacityRefMap > ResGraph;
109 typedef typename ResGraph::Node ResNode;
110 typedef typename ResGraph::NodeIt ResNodeIt;
111 typedef typename ResGraph::Edge ResEdge;
112 typedef typename ResGraph::EdgeIt ResEdgeIt;
116 /// \brief The type of the flow map.
117 typedef CapacityRefMap FlowMap;
121 /// \brief Map adaptor class for demand map.
122 class DemandMap : public MapBase<Node, Supply>
126 const SupplyMap *map;
130 typedef typename MapBase<Node, Supply>::Value Value;
131 typedef typename MapBase<Node, Supply>::Key Key;
133 DemandMap(const SupplyMap &_map) : map(&_map) {}
135 Value operator[](const Key &e) const {
141 /// \brief Map adaptor class for handling residual edge costs.
142 class ResCostMap : public MapBase<ResEdge, Cost>
146 const CostMap &cost_map;
150 typedef typename MapBase<ResEdge, Cost>::Value Value;
151 typedef typename MapBase<ResEdge, Cost>::Key Key;
153 ResCostMap(const CostMap &_cost) : cost_map(_cost) {}
155 Value operator[](const Key &e) const {
156 return ResGraph::forward(e) ? cost_map[e] : -cost_map[e];
159 }; //class ResCostMap
163 /// \brief The directed graph the algorithm runs on.
165 /// \brief The original lower bound map.
166 const LowerMap *lower;
167 /// \brief The modified capacity map.
168 CapacityRefMap capacity;
169 /// \brief The cost map.
171 /// \brief The modified supply map.
173 /// \brief The modified demand map.
175 /// \brief The sum of supply values equals zero.
178 /// \brief The current flow.
180 /// \brief The residual graph.
182 /// \brief The residual cost map.
187 /// \brief General constructor of the class (with lower bounds).
189 /// General constructor of the class (with lower bounds).
191 /// \param _graph The directed graph the algorithm runs on.
192 /// \param _lower The lower bounds of the edges.
193 /// \param _capacity The capacities (upper bounds) of the edges.
194 /// \param _cost The cost (length) values of the edges.
195 /// \param _supply The supply values of the nodes (signed).
196 CycleCanceling( const Graph &_graph,
197 const LowerMap &_lower,
198 const CapacityMap &_capacity,
199 const CostMap &_cost,
200 const SupplyMap &_supply ) :
201 graph(_graph), lower(&_lower), capacity(_graph), cost(_cost),
202 supply(_graph), demand(supply), flow(_graph, 0),
203 res_graph(_graph, capacity, flow), res_cost(cost)
205 // Removing nonzero lower bounds
206 capacity = subMap(_capacity, _lower);
208 for (NodeIt n(graph); n != INVALID; ++n) {
209 Supply s = _supply[n];
210 for (InEdgeIt e(graph, n); e != INVALID; ++e)
212 for (OutEdgeIt e(graph, n); e != INVALID; ++e)
214 sum += (supply[n] = s);
216 valid_supply = sum == 0;
219 /// \brief General constructor of the class (without lower bounds).
221 /// General constructor of the class (without lower bounds).
223 /// \param _graph The directed graph the algorithm runs on.
224 /// \param _capacity The capacities (upper bounds) of the edges.
225 /// \param _cost The cost (length) values of the edges.
226 /// \param _supply The supply values of the nodes (signed).
227 CycleCanceling( const Graph &_graph,
228 const CapacityMap &_capacity,
229 const CostMap &_cost,
230 const SupplyMap &_supply ) :
231 graph(_graph), lower(NULL), capacity(_capacity), cost(_cost),
232 supply(_supply), demand(supply), flow(_graph, 0),
233 res_graph(_graph, capacity, flow), res_cost(cost)
235 // Checking the sum of supply values
237 for (NodeIt n(graph); n != INVALID; ++n) sum += supply[n];
238 valid_supply = sum == 0;
242 /// \brief Simple constructor of the class (with lower bounds).
244 /// Simple constructor of the class (with lower bounds).
246 /// \param _graph The directed graph the algorithm runs on.
247 /// \param _lower The lower bounds of the edges.
248 /// \param _capacity The capacities (upper bounds) of the edges.
249 /// \param _cost The cost (length) values of the edges.
250 /// \param _s The source node.
251 /// \param _t The target node.
252 /// \param _flow_value The required amount of flow from node \c _s
253 /// to node \c _t (i.e. the supply of \c _s and the demand of
255 CycleCanceling( const Graph &_graph,
256 const LowerMap &_lower,
257 const CapacityMap &_capacity,
258 const CostMap &_cost,
260 Supply _flow_value ) :
261 graph(_graph), lower(&_lower), capacity(_graph), cost(_cost),
262 supply(_graph), demand(supply), flow(_graph, 0),
263 res_graph(_graph, capacity, flow), res_cost(cost)
265 // Removing nonzero lower bounds
266 capacity = subMap(_capacity, _lower);
267 for (NodeIt n(graph); n != INVALID; ++n) {
269 if (n == _s) s = _flow_value;
270 if (n == _t) s = -_flow_value;
271 for (InEdgeIt e(graph, n); e != INVALID; ++e)
273 for (OutEdgeIt e(graph, n); e != INVALID; ++e)
280 /// \brief Simple constructor of the class (without lower bounds).
282 /// Simple constructor of the class (without lower bounds).
284 /// \param _graph The directed graph the algorithm runs on.
285 /// \param _capacity The capacities (upper bounds) of the edges.
286 /// \param _cost The cost (length) values of the edges.
287 /// \param _s The source node.
288 /// \param _t The target node.
289 /// \param _flow_value The required amount of flow from node \c _s
290 /// to node \c _t (i.e. the supply of \c _s and the demand of
292 CycleCanceling( const Graph &_graph,
293 const CapacityMap &_capacity,
294 const CostMap &_cost,
296 Supply _flow_value ) :
297 graph(_graph), lower(NULL), capacity(_capacity), cost(_cost),
298 supply(_graph, 0), demand(supply), flow(_graph, 0),
299 res_graph(_graph, capacity, flow), res_cost(cost)
301 supply[_s] = _flow_value;
302 supply[_t] = -_flow_value;
306 /// \brief Returns a const reference to the flow map.
308 /// Returns a const reference to the flow map.
310 /// \pre \ref run() must be called before using this function.
311 const FlowMap& flowMap() const {
315 /// \brief Returns the total cost of the found flow.
317 /// Returns the total cost of the found flow. The complexity of the
318 /// function is \f$ O(e) \f$.
320 /// \pre \ref run() must be called before using this function.
321 Cost totalCost() const {
323 for (EdgeIt e(graph); e != INVALID; ++e)
324 c += flow[e] * cost[e];
328 /// \brief Runs the algorithm.
330 /// Runs the algorithm.
332 /// \return \c true if a feasible flow can be found.
334 return init() && start();
339 /// \brief Initializes the algorithm.
341 // Checking the sum of supply values
343 for (NodeIt n(graph); n != INVALID; ++n) sum += supply[n];
344 if (sum != 0) return false;
346 // Finding a feasible flow
347 Circulation< Graph, Capacity, FlowMap, ConstMap<Edge, Capacity>,
348 CapacityRefMap, DemandMap >
349 circulation( graph, constMap<Edge>((Capacity)0),
350 capacity, demand, flow );
351 return circulation.run() == -1;
354 #ifdef LIMITED_CYCLE_CANCELING
355 /// \brief Executes a cycle canceling algorithm using
356 /// \ref lemon::BellmanFord "Bellman-Ford" algorithm with limited
359 typename BellmanFord<ResGraph, ResCostMap>::PredMap pred(res_graph);
360 typename ResGraph::template NodeMap<int> visited(res_graph);
361 std::vector<ResEdge> cycle;
362 int node_num = countNodes(graph);
367 int length_bound = STARTING_LIMIT;
368 bool optimal = false;
370 BellmanFord<ResGraph, ResCostMap> bf(res_graph, res_cost);
374 bool cycle_found = false;
375 while (!cycle_found) {
376 int curr_iter_num = iter_num + length_bound <= node_num ?
377 length_bound : node_num - iter_num;
378 iter_num += curr_iter_num;
379 int real_iter_num = curr_iter_num;
380 for (int i = 0; i < curr_iter_num; ++i) {
381 if (bf.processNextWeakRound()) {
386 if (real_iter_num < curr_iter_num) {
390 // Searching for node disjoint negative cycles
391 for (ResNodeIt n(res_graph); n != INVALID; ++n)
394 for (ResNodeIt n(res_graph); n != INVALID; ++n) {
395 if (visited[n] > 0) continue;
397 ResNode u = pred[n] == INVALID ?
398 INVALID : res_graph.source(pred[n]);
399 while (u != INVALID && visited[u] == 0) {
401 u = pred[u] == INVALID ?
402 INVALID : res_graph.source(pred[u]);
404 if (u != INVALID && visited[u] == id) {
405 // Finding the negative cycle
410 Capacity d = res_graph.rescap(e);
411 while (res_graph.source(e) != u) {
412 cycle.push_back(e = pred[res_graph.source(e)]);
413 if (res_graph.rescap(e) < d)
414 d = res_graph.rescap(e);
419 // Augmenting along the cycle
420 for (int i = 0; i < cycle.size(); ++i)
421 res_graph.augment(cycle[i], d);
422 #ifdef _ONLY_ONE_CYCLE_
430 length_bound = length_bound * ALPHA_MUL / ALPHA_DIV;
435 std::cout << "Limited cycle canceling algorithm finished. "
436 << "Found " << cycle_num << " negative cycles."
440 // Handling nonzero lower bounds
442 for (EdgeIt e(graph); e != INVALID; ++e)
443 flow[e] += (*lower)[e];
449 #ifdef MIN_MEAN_CYCLE_CANCELING
450 /// \brief Executes the minimum mean cycle canceling algorithm
451 /// using \ref lemon::MinMeanCycle "MinMeanCycle" class.
453 typedef Path<ResGraph> ResPath;
454 MinMeanCycle<ResGraph, ResCostMap> mmc(res_graph, res_cost);
460 mmc.cyclePath(cycle).init();
461 if (mmc.findMinMean()) {
462 while (mmc.cycleLength() < 0) {
469 // Finding the largest flow amount that can be augmented
472 for (typename ResPath::EdgeIt e(cycle); e != INVALID; ++e) {
473 if (delta == 0 || res_graph.rescap(e) < delta)
474 delta = res_graph.rescap(e);
477 // Augmenting along the cycle
478 for (typename ResPath::EdgeIt e(cycle); e != INVALID; ++e)
479 res_graph.augment(e, delta);
481 // Finding the minimum cycle mean for the modified residual
484 if (!mmc.findMinMean()) break;
489 std::cout << "Minimum mean cycle canceling algorithm finished. "
490 << "Found " << cycle_num << " negative cycles."
494 // Handling nonzero lower bounds
496 for (EdgeIt e(graph); e != INVALID; ++e)
497 flow[e] += (*lower)[e];
503 }; //class CycleCanceling
509 #endif //LEMON_CYCLE_CANCELING_H