1 | /* -*- mode: C++; indent-tabs-mode: nil; -*- |
---|
2 | * |
---|
3 | * This file is a part of LEMON, a generic C++ optimization library. |
---|
4 | * |
---|
5 | * Copyright (C) 2003-2013 |
---|
6 | * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
---|
7 | * (Egervary Research Group on Combinatorial Optimization, EGRES). |
---|
8 | * |
---|
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. |
---|
12 | * |
---|
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 |
---|
15 | * purpose. |
---|
16 | * |
---|
17 | */ |
---|
18 | |
---|
19 | #ifndef LEMON_CAPACITY_SCALING_H |
---|
20 | #define LEMON_CAPACITY_SCALING_H |
---|
21 | |
---|
22 | /// \ingroup min_cost_flow_algs |
---|
23 | /// |
---|
24 | /// \file |
---|
25 | /// \brief Capacity Scaling algorithm for finding a minimum cost flow. |
---|
26 | |
---|
27 | #include <vector> |
---|
28 | #include <limits> |
---|
29 | #include <lemon/core.h> |
---|
30 | #include <lemon/bin_heap.h> |
---|
31 | |
---|
32 | namespace lemon { |
---|
33 | |
---|
34 | /// \brief Default traits class of CapacityScaling algorithm. |
---|
35 | /// |
---|
36 | /// Default traits class of CapacityScaling algorithm. |
---|
37 | /// \tparam GR Digraph type. |
---|
38 | /// \tparam V The number type used for flow amounts, capacity bounds |
---|
39 | /// and supply values. By default it is \c int. |
---|
40 | /// \tparam C The number 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 |
---|
44 | { |
---|
45 | /// The type of the digraph |
---|
46 | typedef GR Digraph; |
---|
47 | /// The type of the flow amounts, capacity bounds and supply values |
---|
48 | typedef V Value; |
---|
49 | /// The type of the arc costs |
---|
50 | typedef C Cost; |
---|
51 | |
---|
52 | /// \brief The type of the heap used for internal Dijkstra computations. |
---|
53 | /// |
---|
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; |
---|
59 | }; |
---|
60 | |
---|
61 | /// \addtogroup min_cost_flow_algs |
---|
62 | /// @{ |
---|
63 | |
---|
64 | /// \brief Implementation of the Capacity Scaling algorithm for |
---|
65 | /// finding a \ref min_cost_flow "minimum cost flow". |
---|
66 | /// |
---|
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" \cite amo93networkflows, |
---|
70 | /// \cite edmondskarp72theoretical. It is an efficient dual |
---|
71 | /// solution method, which runs in polynomial time |
---|
72 | /// \f$O(m\log U (n+m)\log n)\f$, where <i>U</i> denotes the maximum |
---|
73 | /// of node supply and arc capacity values. |
---|
74 | /// |
---|
75 | /// This algorithm is typically slower than \ref CostScaling and |
---|
76 | /// \ref NetworkSimplex, but in special cases, it can be more |
---|
77 | /// efficient than them. |
---|
78 | /// (For more information, see \ref min_cost_flow_algs "the module page".) |
---|
79 | /// |
---|
80 | /// Most of the parameters of the problem (except for the digraph) |
---|
81 | /// can be given using separate functions, and the algorithm can be |
---|
82 | /// executed using the \ref run() function. If some parameters are not |
---|
83 | /// specified, then default values will be used. |
---|
84 | /// |
---|
85 | /// \tparam GR The digraph type the algorithm runs on. |
---|
86 | /// \tparam V The number type used for flow amounts, capacity bounds |
---|
87 | /// and supply values in the algorithm. By default, it is \c int. |
---|
88 | /// \tparam C The number type used for costs and potentials in the |
---|
89 | /// algorithm. By default, it is the same as \c V. |
---|
90 | /// \tparam TR The traits class that defines various types used by the |
---|
91 | /// algorithm. By default, it is \ref CapacityScalingDefaultTraits |
---|
92 | /// "CapacityScalingDefaultTraits<GR, V, C>". |
---|
93 | /// In most cases, this parameter should not be set directly, |
---|
94 | /// consider to use the named template parameters instead. |
---|
95 | /// |
---|
96 | /// \warning Both \c V and \c C must be signed number types. |
---|
97 | /// \warning Capacity bounds and supply values must be integer, but |
---|
98 | /// arc costs can be arbitrary real numbers. |
---|
99 | /// \warning This algorithm does not support negative costs for |
---|
100 | /// arcs having infinite upper bound. |
---|
101 | #ifdef DOXYGEN |
---|
102 | template <typename GR, typename V, typename C, typename TR> |
---|
103 | #else |
---|
104 | template < typename GR, typename V = int, typename C = V, |
---|
105 | typename TR = CapacityScalingDefaultTraits<GR, V, C> > |
---|
106 | #endif |
---|
107 | class CapacityScaling |
---|
108 | { |
---|
109 | public: |
---|
110 | |
---|
111 | /// The type of the digraph |
---|
112 | typedef typename TR::Digraph Digraph; |
---|
113 | /// The type of the flow amounts, capacity bounds and supply values |
---|
114 | typedef typename TR::Value Value; |
---|
115 | /// The type of the arc costs |
---|
116 | typedef typename TR::Cost Cost; |
---|
117 | |
---|
118 | /// The type of the heap used for internal Dijkstra computations |
---|
119 | typedef typename TR::Heap Heap; |
---|
120 | |
---|
121 | /// \brief The \ref lemon::CapacityScalingDefaultTraits "traits class" |
---|
122 | /// of the algorithm |
---|
123 | typedef TR Traits; |
---|
124 | |
---|
125 | public: |
---|
126 | |
---|
127 | /// \brief Problem type constants for the \c run() function. |
---|
128 | /// |
---|
129 | /// Enum type containing the problem type constants that can be |
---|
130 | /// returned by the \ref run() function of the algorithm. |
---|
131 | enum ProblemType { |
---|
132 | /// The problem has no feasible solution (flow). |
---|
133 | INFEASIBLE, |
---|
134 | /// The problem has optimal solution (i.e. it is feasible and |
---|
135 | /// bounded), and the algorithm has found optimal flow and node |
---|
136 | /// potentials (primal and dual solutions). |
---|
137 | OPTIMAL, |
---|
138 | /// The digraph contains an arc of negative cost and infinite |
---|
139 | /// upper bound. It means that the objective function is unbounded |
---|
140 | /// on that arc, however, note that it could actually be bounded |
---|
141 | /// over the feasible flows, but this algroithm cannot handle |
---|
142 | /// these cases. |
---|
143 | UNBOUNDED |
---|
144 | }; |
---|
145 | |
---|
146 | private: |
---|
147 | |
---|
148 | TEMPLATE_DIGRAPH_TYPEDEFS(GR); |
---|
149 | |
---|
150 | typedef std::vector<int> IntVector; |
---|
151 | typedef std::vector<Value> ValueVector; |
---|
152 | typedef std::vector<Cost> CostVector; |
---|
153 | typedef std::vector<char> BoolVector; |
---|
154 | // Note: vector<char> is used instead of vector<bool> for efficiency reasons |
---|
155 | |
---|
156 | private: |
---|
157 | |
---|
158 | // Data related to the underlying digraph |
---|
159 | const GR &_graph; |
---|
160 | int _node_num; |
---|
161 | int _arc_num; |
---|
162 | int _res_arc_num; |
---|
163 | int _root; |
---|
164 | |
---|
165 | // Parameters of the problem |
---|
166 | bool _have_lower; |
---|
167 | Value _sum_supply; |
---|
168 | |
---|
169 | // Data structures for storing the digraph |
---|
170 | IntNodeMap _node_id; |
---|
171 | IntArcMap _arc_idf; |
---|
172 | IntArcMap _arc_idb; |
---|
173 | IntVector _first_out; |
---|
174 | BoolVector _forward; |
---|
175 | IntVector _source; |
---|
176 | IntVector _target; |
---|
177 | IntVector _reverse; |
---|
178 | |
---|
179 | // Node and arc data |
---|
180 | ValueVector _lower; |
---|
181 | ValueVector _upper; |
---|
182 | CostVector _cost; |
---|
183 | ValueVector _supply; |
---|
184 | |
---|
185 | ValueVector _res_cap; |
---|
186 | CostVector _pi; |
---|
187 | ValueVector _excess; |
---|
188 | IntVector _excess_nodes; |
---|
189 | IntVector _deficit_nodes; |
---|
190 | |
---|
191 | Value _delta; |
---|
192 | int _factor; |
---|
193 | IntVector _pred; |
---|
194 | |
---|
195 | public: |
---|
196 | |
---|
197 | /// \brief Constant for infinite upper bounds (capacities). |
---|
198 | /// |
---|
199 | /// Constant for infinite upper bounds (capacities). |
---|
200 | /// It is \c std::numeric_limits<Value>::infinity() if available, |
---|
201 | /// \c std::numeric_limits<Value>::max() otherwise. |
---|
202 | const Value INF; |
---|
203 | |
---|
204 | private: |
---|
205 | |
---|
206 | // Special implementation of the Dijkstra algorithm for finding |
---|
207 | // shortest paths in the residual network of the digraph with |
---|
208 | // respect to the reduced arc costs and modifying the node |
---|
209 | // potentials according to the found distance labels. |
---|
210 | class ResidualDijkstra |
---|
211 | { |
---|
212 | private: |
---|
213 | |
---|
214 | int _node_num; |
---|
215 | bool _geq; |
---|
216 | const IntVector &_first_out; |
---|
217 | const IntVector &_target; |
---|
218 | const CostVector &_cost; |
---|
219 | const ValueVector &_res_cap; |
---|
220 | const ValueVector &_excess; |
---|
221 | CostVector &_pi; |
---|
222 | IntVector &_pred; |
---|
223 | |
---|
224 | IntVector _proc_nodes; |
---|
225 | CostVector _dist; |
---|
226 | |
---|
227 | public: |
---|
228 | |
---|
229 | ResidualDijkstra(CapacityScaling& cs) : |
---|
230 | _node_num(cs._node_num), _geq(cs._sum_supply < 0), |
---|
231 | _first_out(cs._first_out), _target(cs._target), _cost(cs._cost), |
---|
232 | _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi), |
---|
233 | _pred(cs._pred), _dist(cs._node_num) |
---|
234 | {} |
---|
235 | |
---|
236 | int run(int s, Value delta = 1) { |
---|
237 | RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP); |
---|
238 | Heap heap(heap_cross_ref); |
---|
239 | heap.push(s, 0); |
---|
240 | _pred[s] = -1; |
---|
241 | _proc_nodes.clear(); |
---|
242 | |
---|
243 | // Process nodes |
---|
244 | while (!heap.empty() && _excess[heap.top()] > -delta) { |
---|
245 | int u = heap.top(), v; |
---|
246 | Cost d = heap.prio() + _pi[u], dn; |
---|
247 | _dist[u] = heap.prio(); |
---|
248 | _proc_nodes.push_back(u); |
---|
249 | heap.pop(); |
---|
250 | |
---|
251 | // Traverse outgoing residual arcs |
---|
252 | int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1; |
---|
253 | for (int a = _first_out[u]; a != last_out; ++a) { |
---|
254 | if (_res_cap[a] < delta) continue; |
---|
255 | v = _target[a]; |
---|
256 | switch (heap.state(v)) { |
---|
257 | case Heap::PRE_HEAP: |
---|
258 | heap.push(v, d + _cost[a] - _pi[v]); |
---|
259 | _pred[v] = a; |
---|
260 | break; |
---|
261 | case Heap::IN_HEAP: |
---|
262 | dn = d + _cost[a] - _pi[v]; |
---|
263 | if (dn < heap[v]) { |
---|
264 | heap.decrease(v, dn); |
---|
265 | _pred[v] = a; |
---|
266 | } |
---|
267 | break; |
---|
268 | case Heap::POST_HEAP: |
---|
269 | break; |
---|
270 | } |
---|
271 | } |
---|
272 | } |
---|
273 | if (heap.empty()) return -1; |
---|
274 | |
---|
275 | // Update potentials of processed nodes |
---|
276 | int t = heap.top(); |
---|
277 | Cost dt = heap.prio(); |
---|
278 | for (int i = 0; i < int(_proc_nodes.size()); ++i) { |
---|
279 | _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt; |
---|
280 | } |
---|
281 | |
---|
282 | return t; |
---|
283 | } |
---|
284 | |
---|
285 | }; //class ResidualDijkstra |
---|
286 | |
---|
287 | public: |
---|
288 | |
---|
289 | /// \name Named Template Parameters |
---|
290 | /// @{ |
---|
291 | |
---|
292 | template <typename T> |
---|
293 | struct SetHeapTraits : public Traits { |
---|
294 | typedef T Heap; |
---|
295 | }; |
---|
296 | |
---|
297 | /// \brief \ref named-templ-param "Named parameter" for setting |
---|
298 | /// \c Heap type. |
---|
299 | /// |
---|
300 | /// \ref named-templ-param "Named parameter" for setting \c Heap |
---|
301 | /// type, which is used for internal Dijkstra computations. |
---|
302 | /// It must conform to the \ref lemon::concepts::Heap "Heap" concept, |
---|
303 | /// its priority type must be \c Cost and its cross reference type |
---|
304 | /// must be \ref RangeMap "RangeMap<int>". |
---|
305 | template <typename T> |
---|
306 | struct SetHeap |
---|
307 | : public CapacityScaling<GR, V, C, SetHeapTraits<T> > { |
---|
308 | typedef CapacityScaling<GR, V, C, SetHeapTraits<T> > Create; |
---|
309 | }; |
---|
310 | |
---|
311 | /// @} |
---|
312 | |
---|
313 | protected: |
---|
314 | |
---|
315 | CapacityScaling() {} |
---|
316 | |
---|
317 | public: |
---|
318 | |
---|
319 | /// \brief Constructor. |
---|
320 | /// |
---|
321 | /// The constructor of the class. |
---|
322 | /// |
---|
323 | /// \param graph The digraph the algorithm runs on. |
---|
324 | CapacityScaling(const GR& graph) : |
---|
325 | _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph), |
---|
326 | INF(std::numeric_limits<Value>::has_infinity ? |
---|
327 | std::numeric_limits<Value>::infinity() : |
---|
328 | std::numeric_limits<Value>::max()) |
---|
329 | { |
---|
330 | // Check the number types |
---|
331 | LEMON_ASSERT(std::numeric_limits<Value>::is_signed, |
---|
332 | "The flow type of CapacityScaling must be signed"); |
---|
333 | LEMON_ASSERT(std::numeric_limits<Cost>::is_signed, |
---|
334 | "The cost type of CapacityScaling must be signed"); |
---|
335 | |
---|
336 | // Reset data structures |
---|
337 | reset(); |
---|
338 | } |
---|
339 | |
---|
340 | /// \name Parameters |
---|
341 | /// The parameters of the algorithm can be specified using these |
---|
342 | /// functions. |
---|
343 | |
---|
344 | /// @{ |
---|
345 | |
---|
346 | /// \brief Set the lower bounds on the arcs. |
---|
347 | /// |
---|
348 | /// This function sets the lower bounds on the arcs. |
---|
349 | /// If it is not used before calling \ref run(), the lower bounds |
---|
350 | /// will be set to zero on all arcs. |
---|
351 | /// |
---|
352 | /// \param map An arc map storing the lower bounds. |
---|
353 | /// Its \c Value type must be convertible to the \c Value type |
---|
354 | /// of the algorithm. |
---|
355 | /// |
---|
356 | /// \return <tt>(*this)</tt> |
---|
357 | template <typename LowerMap> |
---|
358 | CapacityScaling& lowerMap(const LowerMap& map) { |
---|
359 | _have_lower = true; |
---|
360 | for (ArcIt a(_graph); a != INVALID; ++a) { |
---|
361 | _lower[_arc_idf[a]] = map[a]; |
---|
362 | _lower[_arc_idb[a]] = map[a]; |
---|
363 | } |
---|
364 | return *this; |
---|
365 | } |
---|
366 | |
---|
367 | /// \brief Set the upper bounds (capacities) on the arcs. |
---|
368 | /// |
---|
369 | /// This function sets the upper bounds (capacities) on the arcs. |
---|
370 | /// If it is not used before calling \ref run(), the upper bounds |
---|
371 | /// will be set to \ref INF on all arcs (i.e. the flow value will be |
---|
372 | /// unbounded from above). |
---|
373 | /// |
---|
374 | /// \param map An arc map storing the upper bounds. |
---|
375 | /// Its \c Value type must be convertible to the \c Value type |
---|
376 | /// of the algorithm. |
---|
377 | /// |
---|
378 | /// \return <tt>(*this)</tt> |
---|
379 | template<typename UpperMap> |
---|
380 | CapacityScaling& upperMap(const UpperMap& map) { |
---|
381 | for (ArcIt a(_graph); a != INVALID; ++a) { |
---|
382 | _upper[_arc_idf[a]] = map[a]; |
---|
383 | } |
---|
384 | return *this; |
---|
385 | } |
---|
386 | |
---|
387 | /// \brief Set the costs of the arcs. |
---|
388 | /// |
---|
389 | /// This function sets the costs of the arcs. |
---|
390 | /// If it is not used before calling \ref run(), the costs |
---|
391 | /// will be set to \c 1 on all arcs. |
---|
392 | /// |
---|
393 | /// \param map An arc map storing the costs. |
---|
394 | /// Its \c Value type must be convertible to the \c Cost type |
---|
395 | /// of the algorithm. |
---|
396 | /// |
---|
397 | /// \return <tt>(*this)</tt> |
---|
398 | template<typename CostMap> |
---|
399 | CapacityScaling& costMap(const CostMap& map) { |
---|
400 | for (ArcIt a(_graph); a != INVALID; ++a) { |
---|
401 | _cost[_arc_idf[a]] = map[a]; |
---|
402 | _cost[_arc_idb[a]] = -map[a]; |
---|
403 | } |
---|
404 | return *this; |
---|
405 | } |
---|
406 | |
---|
407 | /// \brief Set the supply values of the nodes. |
---|
408 | /// |
---|
409 | /// This function sets the supply values of the nodes. |
---|
410 | /// If neither this function nor \ref stSupply() is used before |
---|
411 | /// calling \ref run(), the supply of each node will be set to zero. |
---|
412 | /// |
---|
413 | /// \param map A node map storing the supply values. |
---|
414 | /// Its \c Value type must be convertible to the \c Value type |
---|
415 | /// of the algorithm. |
---|
416 | /// |
---|
417 | /// \return <tt>(*this)</tt> |
---|
418 | template<typename SupplyMap> |
---|
419 | CapacityScaling& supplyMap(const SupplyMap& map) { |
---|
420 | for (NodeIt n(_graph); n != INVALID; ++n) { |
---|
421 | _supply[_node_id[n]] = map[n]; |
---|
422 | } |
---|
423 | return *this; |
---|
424 | } |
---|
425 | |
---|
426 | /// \brief Set single source and target nodes and a supply value. |
---|
427 | /// |
---|
428 | /// This function sets a single source node and a single target node |
---|
429 | /// and the required flow value. |
---|
430 | /// If neither this function nor \ref supplyMap() is used before |
---|
431 | /// calling \ref run(), the supply of each node will be set to zero. |
---|
432 | /// |
---|
433 | /// Using this function has the same effect as using \ref supplyMap() |
---|
434 | /// with a map in which \c k is assigned to \c s, \c -k is |
---|
435 | /// assigned to \c t and all other nodes have zero supply value. |
---|
436 | /// |
---|
437 | /// \param s The source node. |
---|
438 | /// \param t The target node. |
---|
439 | /// \param k The required amount of flow from node \c s to node \c t |
---|
440 | /// (i.e. the supply of \c s and the demand of \c t). |
---|
441 | /// |
---|
442 | /// \return <tt>(*this)</tt> |
---|
443 | CapacityScaling& stSupply(const Node& s, const Node& t, Value k) { |
---|
444 | for (int i = 0; i != _node_num; ++i) { |
---|
445 | _supply[i] = 0; |
---|
446 | } |
---|
447 | _supply[_node_id[s]] = k; |
---|
448 | _supply[_node_id[t]] = -k; |
---|
449 | return *this; |
---|
450 | } |
---|
451 | |
---|
452 | /// @} |
---|
453 | |
---|
454 | /// \name Execution control |
---|
455 | /// The algorithm can be executed using \ref run(). |
---|
456 | |
---|
457 | /// @{ |
---|
458 | |
---|
459 | /// \brief Run the algorithm. |
---|
460 | /// |
---|
461 | /// This function runs the algorithm. |
---|
462 | /// The paramters can be specified using functions \ref lowerMap(), |
---|
463 | /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). |
---|
464 | /// For example, |
---|
465 | /// \code |
---|
466 | /// CapacityScaling<ListDigraph> cs(graph); |
---|
467 | /// cs.lowerMap(lower).upperMap(upper).costMap(cost) |
---|
468 | /// .supplyMap(sup).run(); |
---|
469 | /// \endcode |
---|
470 | /// |
---|
471 | /// This function can be called more than once. All the given parameters |
---|
472 | /// are kept for the next call, unless \ref resetParams() or \ref reset() |
---|
473 | /// is used, thus only the modified parameters have to be set again. |
---|
474 | /// If the underlying digraph was also modified after the construction |
---|
475 | /// of the class (or the last \ref reset() call), then the \ref reset() |
---|
476 | /// function must be called. |
---|
477 | /// |
---|
478 | /// \param factor The capacity scaling factor. It must be larger than |
---|
479 | /// one to use scaling. If it is less or equal to one, then scaling |
---|
480 | /// will be disabled. |
---|
481 | /// |
---|
482 | /// \return \c INFEASIBLE if no feasible flow exists, |
---|
483 | /// \n \c OPTIMAL if the problem has optimal solution |
---|
484 | /// (i.e. it is feasible and bounded), and the algorithm has found |
---|
485 | /// optimal flow and node potentials (primal and dual solutions), |
---|
486 | /// \n \c UNBOUNDED if the digraph contains an arc of negative cost |
---|
487 | /// and infinite upper bound. It means that the objective function |
---|
488 | /// is unbounded on that arc, however, note that it could actually be |
---|
489 | /// bounded over the feasible flows, but this algroithm cannot handle |
---|
490 | /// these cases. |
---|
491 | /// |
---|
492 | /// \see ProblemType |
---|
493 | /// \see resetParams(), reset() |
---|
494 | ProblemType run(int factor = 4) { |
---|
495 | _factor = factor; |
---|
496 | ProblemType pt = init(); |
---|
497 | if (pt != OPTIMAL) return pt; |
---|
498 | return start(); |
---|
499 | } |
---|
500 | |
---|
501 | /// \brief Reset all the parameters that have been given before. |
---|
502 | /// |
---|
503 | /// This function resets all the paramaters that have been given |
---|
504 | /// before using functions \ref lowerMap(), \ref upperMap(), |
---|
505 | /// \ref costMap(), \ref supplyMap(), \ref stSupply(). |
---|
506 | /// |
---|
507 | /// It is useful for multiple \ref run() calls. Basically, all the given |
---|
508 | /// parameters are kept for the next \ref run() call, unless |
---|
509 | /// \ref resetParams() or \ref reset() is used. |
---|
510 | /// If the underlying digraph was also modified after the construction |
---|
511 | /// of the class or the last \ref reset() call, then the \ref reset() |
---|
512 | /// function must be used, otherwise \ref resetParams() is sufficient. |
---|
513 | /// |
---|
514 | /// For example, |
---|
515 | /// \code |
---|
516 | /// CapacityScaling<ListDigraph> cs(graph); |
---|
517 | /// |
---|
518 | /// // First run |
---|
519 | /// cs.lowerMap(lower).upperMap(upper).costMap(cost) |
---|
520 | /// .supplyMap(sup).run(); |
---|
521 | /// |
---|
522 | /// // Run again with modified cost map (resetParams() is not called, |
---|
523 | /// // so only the cost map have to be set again) |
---|
524 | /// cost[e] += 100; |
---|
525 | /// cs.costMap(cost).run(); |
---|
526 | /// |
---|
527 | /// // Run again from scratch using resetParams() |
---|
528 | /// // (the lower bounds will be set to zero on all arcs) |
---|
529 | /// cs.resetParams(); |
---|
530 | /// cs.upperMap(capacity).costMap(cost) |
---|
531 | /// .supplyMap(sup).run(); |
---|
532 | /// \endcode |
---|
533 | /// |
---|
534 | /// \return <tt>(*this)</tt> |
---|
535 | /// |
---|
536 | /// \see reset(), run() |
---|
537 | CapacityScaling& resetParams() { |
---|
538 | for (int i = 0; i != _node_num; ++i) { |
---|
539 | _supply[i] = 0; |
---|
540 | } |
---|
541 | for (int j = 0; j != _res_arc_num; ++j) { |
---|
542 | _lower[j] = 0; |
---|
543 | _upper[j] = INF; |
---|
544 | _cost[j] = _forward[j] ? 1 : -1; |
---|
545 | } |
---|
546 | _have_lower = false; |
---|
547 | return *this; |
---|
548 | } |
---|
549 | |
---|
550 | /// \brief Reset the internal data structures and all the parameters |
---|
551 | /// that have been given before. |
---|
552 | /// |
---|
553 | /// This function resets the internal data structures and all the |
---|
554 | /// paramaters that have been given before using functions \ref lowerMap(), |
---|
555 | /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). |
---|
556 | /// |
---|
557 | /// It is useful for multiple \ref run() calls. Basically, all the given |
---|
558 | /// parameters are kept for the next \ref run() call, unless |
---|
559 | /// \ref resetParams() or \ref reset() is used. |
---|
560 | /// If the underlying digraph was also modified after the construction |
---|
561 | /// of the class or the last \ref reset() call, then the \ref reset() |
---|
562 | /// function must be used, otherwise \ref resetParams() is sufficient. |
---|
563 | /// |
---|
564 | /// See \ref resetParams() for examples. |
---|
565 | /// |
---|
566 | /// \return <tt>(*this)</tt> |
---|
567 | /// |
---|
568 | /// \see resetParams(), run() |
---|
569 | CapacityScaling& reset() { |
---|
570 | // Resize vectors |
---|
571 | _node_num = countNodes(_graph); |
---|
572 | _arc_num = countArcs(_graph); |
---|
573 | _res_arc_num = 2 * (_arc_num + _node_num); |
---|
574 | _root = _node_num; |
---|
575 | ++_node_num; |
---|
576 | |
---|
577 | _first_out.resize(_node_num + 1); |
---|
578 | _forward.resize(_res_arc_num); |
---|
579 | _source.resize(_res_arc_num); |
---|
580 | _target.resize(_res_arc_num); |
---|
581 | _reverse.resize(_res_arc_num); |
---|
582 | |
---|
583 | _lower.resize(_res_arc_num); |
---|
584 | _upper.resize(_res_arc_num); |
---|
585 | _cost.resize(_res_arc_num); |
---|
586 | _supply.resize(_node_num); |
---|
587 | |
---|
588 | _res_cap.resize(_res_arc_num); |
---|
589 | _pi.resize(_node_num); |
---|
590 | _excess.resize(_node_num); |
---|
591 | _pred.resize(_node_num); |
---|
592 | |
---|
593 | // Copy the graph |
---|
594 | int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1; |
---|
595 | for (NodeIt n(_graph); n != INVALID; ++n, ++i) { |
---|
596 | _node_id[n] = i; |
---|
597 | } |
---|
598 | i = 0; |
---|
599 | for (NodeIt n(_graph); n != INVALID; ++n, ++i) { |
---|
600 | _first_out[i] = j; |
---|
601 | for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) { |
---|
602 | _arc_idf[a] = j; |
---|
603 | _forward[j] = true; |
---|
604 | _source[j] = i; |
---|
605 | _target[j] = _node_id[_graph.runningNode(a)]; |
---|
606 | } |
---|
607 | for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) { |
---|
608 | _arc_idb[a] = j; |
---|
609 | _forward[j] = false; |
---|
610 | _source[j] = i; |
---|
611 | _target[j] = _node_id[_graph.runningNode(a)]; |
---|
612 | } |
---|
613 | _forward[j] = false; |
---|
614 | _source[j] = i; |
---|
615 | _target[j] = _root; |
---|
616 | _reverse[j] = k; |
---|
617 | _forward[k] = true; |
---|
618 | _source[k] = _root; |
---|
619 | _target[k] = i; |
---|
620 | _reverse[k] = j; |
---|
621 | ++j; ++k; |
---|
622 | } |
---|
623 | _first_out[i] = j; |
---|
624 | _first_out[_node_num] = k; |
---|
625 | for (ArcIt a(_graph); a != INVALID; ++a) { |
---|
626 | int fi = _arc_idf[a]; |
---|
627 | int bi = _arc_idb[a]; |
---|
628 | _reverse[fi] = bi; |
---|
629 | _reverse[bi] = fi; |
---|
630 | } |
---|
631 | |
---|
632 | // Reset parameters |
---|
633 | resetParams(); |
---|
634 | return *this; |
---|
635 | } |
---|
636 | |
---|
637 | /// @} |
---|
638 | |
---|
639 | /// \name Query Functions |
---|
640 | /// The results of the algorithm can be obtained using these |
---|
641 | /// functions.\n |
---|
642 | /// The \ref run() function must be called before using them. |
---|
643 | |
---|
644 | /// @{ |
---|
645 | |
---|
646 | /// \brief Return the total cost of the found flow. |
---|
647 | /// |
---|
648 | /// This function returns the total cost of the found flow. |
---|
649 | /// Its complexity is O(m). |
---|
650 | /// |
---|
651 | /// \note The return type of the function can be specified as a |
---|
652 | /// template parameter. For example, |
---|
653 | /// \code |
---|
654 | /// cs.totalCost<double>(); |
---|
655 | /// \endcode |
---|
656 | /// It is useful if the total cost cannot be stored in the \c Cost |
---|
657 | /// type of the algorithm, which is the default return type of the |
---|
658 | /// function. |
---|
659 | /// |
---|
660 | /// \pre \ref run() must be called before using this function. |
---|
661 | template <typename Number> |
---|
662 | Number totalCost() const { |
---|
663 | Number c = 0; |
---|
664 | for (ArcIt a(_graph); a != INVALID; ++a) { |
---|
665 | int i = _arc_idb[a]; |
---|
666 | c += static_cast<Number>(_res_cap[i]) * |
---|
667 | (-static_cast<Number>(_cost[i])); |
---|
668 | } |
---|
669 | return c; |
---|
670 | } |
---|
671 | |
---|
672 | #ifndef DOXYGEN |
---|
673 | Cost totalCost() const { |
---|
674 | return totalCost<Cost>(); |
---|
675 | } |
---|
676 | #endif |
---|
677 | |
---|
678 | /// \brief Return the flow on the given arc. |
---|
679 | /// |
---|
680 | /// This function returns the flow on the given arc. |
---|
681 | /// |
---|
682 | /// \pre \ref run() must be called before using this function. |
---|
683 | Value flow(const Arc& a) const { |
---|
684 | return _res_cap[_arc_idb[a]]; |
---|
685 | } |
---|
686 | |
---|
687 | /// \brief Copy the flow values (the primal solution) into the |
---|
688 | /// given map. |
---|
689 | /// |
---|
690 | /// This function copies the flow value on each arc into the given |
---|
691 | /// map. The \c Value type of the algorithm must be convertible to |
---|
692 | /// the \c Value type of the map. |
---|
693 | /// |
---|
694 | /// \pre \ref run() must be called before using this function. |
---|
695 | template <typename FlowMap> |
---|
696 | void flowMap(FlowMap &map) const { |
---|
697 | for (ArcIt a(_graph); a != INVALID; ++a) { |
---|
698 | map.set(a, _res_cap[_arc_idb[a]]); |
---|
699 | } |
---|
700 | } |
---|
701 | |
---|
702 | /// \brief Return the potential (dual value) of the given node. |
---|
703 | /// |
---|
704 | /// This function returns the potential (dual value) of the |
---|
705 | /// given node. |
---|
706 | /// |
---|
707 | /// \pre \ref run() must be called before using this function. |
---|
708 | Cost potential(const Node& n) const { |
---|
709 | return _pi[_node_id[n]]; |
---|
710 | } |
---|
711 | |
---|
712 | /// \brief Copy the potential values (the dual solution) into the |
---|
713 | /// given map. |
---|
714 | /// |
---|
715 | /// This function copies the potential (dual value) of each node |
---|
716 | /// into the given map. |
---|
717 | /// The \c Cost type of the algorithm must be convertible to the |
---|
718 | /// \c Value type of the map. |
---|
719 | /// |
---|
720 | /// \pre \ref run() must be called before using this function. |
---|
721 | template <typename PotentialMap> |
---|
722 | void potentialMap(PotentialMap &map) const { |
---|
723 | for (NodeIt n(_graph); n != INVALID; ++n) { |
---|
724 | map.set(n, _pi[_node_id[n]]); |
---|
725 | } |
---|
726 | } |
---|
727 | |
---|
728 | /// @} |
---|
729 | |
---|
730 | private: |
---|
731 | |
---|
732 | // Initialize the algorithm |
---|
733 | ProblemType init() { |
---|
734 | if (_node_num <= 1) return INFEASIBLE; |
---|
735 | |
---|
736 | // Check the sum of supply values |
---|
737 | _sum_supply = 0; |
---|
738 | for (int i = 0; i != _root; ++i) { |
---|
739 | _sum_supply += _supply[i]; |
---|
740 | } |
---|
741 | if (_sum_supply > 0) return INFEASIBLE; |
---|
742 | |
---|
743 | // Check lower and upper bounds |
---|
744 | LEMON_DEBUG(checkBoundMaps(), |
---|
745 | "Upper bounds must be greater or equal to the lower bounds"); |
---|
746 | |
---|
747 | |
---|
748 | // Initialize vectors |
---|
749 | for (int i = 0; i != _root; ++i) { |
---|
750 | _pi[i] = 0; |
---|
751 | _excess[i] = _supply[i]; |
---|
752 | } |
---|
753 | |
---|
754 | // Remove non-zero lower bounds |
---|
755 | const Value MAX = std::numeric_limits<Value>::max(); |
---|
756 | int last_out; |
---|
757 | if (_have_lower) { |
---|
758 | for (int i = 0; i != _root; ++i) { |
---|
759 | last_out = _first_out[i+1]; |
---|
760 | for (int j = _first_out[i]; j != last_out; ++j) { |
---|
761 | if (_forward[j]) { |
---|
762 | Value c = _lower[j]; |
---|
763 | if (c >= 0) { |
---|
764 | _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF; |
---|
765 | } else { |
---|
766 | _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF; |
---|
767 | } |
---|
768 | _excess[i] -= c; |
---|
769 | _excess[_target[j]] += c; |
---|
770 | } else { |
---|
771 | _res_cap[j] = 0; |
---|
772 | } |
---|
773 | } |
---|
774 | } |
---|
775 | } else { |
---|
776 | for (int j = 0; j != _res_arc_num; ++j) { |
---|
777 | _res_cap[j] = _forward[j] ? _upper[j] : 0; |
---|
778 | } |
---|
779 | } |
---|
780 | |
---|
781 | // Handle negative costs |
---|
782 | for (int i = 0; i != _root; ++i) { |
---|
783 | last_out = _first_out[i+1] - 1; |
---|
784 | for (int j = _first_out[i]; j != last_out; ++j) { |
---|
785 | Value rc = _res_cap[j]; |
---|
786 | if (_cost[j] < 0 && rc > 0) { |
---|
787 | if (rc >= MAX) return UNBOUNDED; |
---|
788 | _excess[i] -= rc; |
---|
789 | _excess[_target[j]] += rc; |
---|
790 | _res_cap[j] = 0; |
---|
791 | _res_cap[_reverse[j]] += rc; |
---|
792 | } |
---|
793 | } |
---|
794 | } |
---|
795 | |
---|
796 | // Handle GEQ supply type |
---|
797 | if (_sum_supply < 0) { |
---|
798 | _pi[_root] = 0; |
---|
799 | _excess[_root] = -_sum_supply; |
---|
800 | for (int a = _first_out[_root]; a != _res_arc_num; ++a) { |
---|
801 | int ra = _reverse[a]; |
---|
802 | _res_cap[a] = -_sum_supply + 1; |
---|
803 | _res_cap[ra] = 0; |
---|
804 | _cost[a] = 0; |
---|
805 | _cost[ra] = 0; |
---|
806 | } |
---|
807 | } else { |
---|
808 | _pi[_root] = 0; |
---|
809 | _excess[_root] = 0; |
---|
810 | for (int a = _first_out[_root]; a != _res_arc_num; ++a) { |
---|
811 | int ra = _reverse[a]; |
---|
812 | _res_cap[a] = 1; |
---|
813 | _res_cap[ra] = 0; |
---|
814 | _cost[a] = 0; |
---|
815 | _cost[ra] = 0; |
---|
816 | } |
---|
817 | } |
---|
818 | |
---|
819 | // Initialize delta value |
---|
820 | if (_factor > 1) { |
---|
821 | // With scaling |
---|
822 | Value max_sup = 0, max_dem = 0, max_cap = 0; |
---|
823 | for (int i = 0; i != _root; ++i) { |
---|
824 | Value ex = _excess[i]; |
---|
825 | if ( ex > max_sup) max_sup = ex; |
---|
826 | if (-ex > max_dem) max_dem = -ex; |
---|
827 | int last_out = _first_out[i+1] - 1; |
---|
828 | for (int j = _first_out[i]; j != last_out; ++j) { |
---|
829 | if (_res_cap[j] > max_cap) max_cap = _res_cap[j]; |
---|
830 | } |
---|
831 | } |
---|
832 | max_sup = std::min(std::min(max_sup, max_dem), max_cap); |
---|
833 | for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ; |
---|
834 | } else { |
---|
835 | // Without scaling |
---|
836 | _delta = 1; |
---|
837 | } |
---|
838 | |
---|
839 | return OPTIMAL; |
---|
840 | } |
---|
841 | |
---|
842 | // Check if the upper bound is greater or equal to the lower bound |
---|
843 | // on each arc. |
---|
844 | bool checkBoundMaps() { |
---|
845 | for (int j = 0; j != _res_arc_num; ++j) { |
---|
846 | if (_upper[j] < _lower[j]) return false; |
---|
847 | } |
---|
848 | return true; |
---|
849 | } |
---|
850 | |
---|
851 | ProblemType start() { |
---|
852 | // Execute the algorithm |
---|
853 | ProblemType pt; |
---|
854 | if (_delta > 1) |
---|
855 | pt = startWithScaling(); |
---|
856 | else |
---|
857 | pt = startWithoutScaling(); |
---|
858 | |
---|
859 | // Handle non-zero lower bounds |
---|
860 | if (_have_lower) { |
---|
861 | int limit = _first_out[_root]; |
---|
862 | for (int j = 0; j != limit; ++j) { |
---|
863 | if (!_forward[j]) _res_cap[j] += _lower[j]; |
---|
864 | } |
---|
865 | } |
---|
866 | |
---|
867 | // Shift potentials if necessary |
---|
868 | Cost pr = _pi[_root]; |
---|
869 | if (_sum_supply < 0 || pr > 0) { |
---|
870 | for (int i = 0; i != _node_num; ++i) { |
---|
871 | _pi[i] -= pr; |
---|
872 | } |
---|
873 | } |
---|
874 | |
---|
875 | return pt; |
---|
876 | } |
---|
877 | |
---|
878 | // Execute the capacity scaling algorithm |
---|
879 | ProblemType startWithScaling() { |
---|
880 | // Perform capacity scaling phases |
---|
881 | int s, t; |
---|
882 | ResidualDijkstra _dijkstra(*this); |
---|
883 | while (true) { |
---|
884 | // Saturate all arcs not satisfying the optimality condition |
---|
885 | int last_out; |
---|
886 | for (int u = 0; u != _node_num; ++u) { |
---|
887 | last_out = _sum_supply < 0 ? |
---|
888 | _first_out[u+1] : _first_out[u+1] - 1; |
---|
889 | for (int a = _first_out[u]; a != last_out; ++a) { |
---|
890 | int v = _target[a]; |
---|
891 | Cost c = _cost[a] + _pi[u] - _pi[v]; |
---|
892 | Value rc = _res_cap[a]; |
---|
893 | if (c < 0 && rc >= _delta) { |
---|
894 | _excess[u] -= rc; |
---|
895 | _excess[v] += rc; |
---|
896 | _res_cap[a] = 0; |
---|
897 | _res_cap[_reverse[a]] += rc; |
---|
898 | } |
---|
899 | } |
---|
900 | } |
---|
901 | |
---|
902 | // Find excess nodes and deficit nodes |
---|
903 | _excess_nodes.clear(); |
---|
904 | _deficit_nodes.clear(); |
---|
905 | for (int u = 0; u != _node_num; ++u) { |
---|
906 | Value ex = _excess[u]; |
---|
907 | if (ex >= _delta) _excess_nodes.push_back(u); |
---|
908 | if (ex <= -_delta) _deficit_nodes.push_back(u); |
---|
909 | } |
---|
910 | int next_node = 0, next_def_node = 0; |
---|
911 | |
---|
912 | // Find augmenting shortest paths |
---|
913 | while (next_node < int(_excess_nodes.size())) { |
---|
914 | // Check deficit nodes |
---|
915 | if (_delta > 1) { |
---|
916 | bool delta_deficit = false; |
---|
917 | for ( ; next_def_node < int(_deficit_nodes.size()); |
---|
918 | ++next_def_node ) { |
---|
919 | if (_excess[_deficit_nodes[next_def_node]] <= -_delta) { |
---|
920 | delta_deficit = true; |
---|
921 | break; |
---|
922 | } |
---|
923 | } |
---|
924 | if (!delta_deficit) break; |
---|
925 | } |
---|
926 | |
---|
927 | // Run Dijkstra in the residual network |
---|
928 | s = _excess_nodes[next_node]; |
---|
929 | if ((t = _dijkstra.run(s, _delta)) == -1) { |
---|
930 | if (_delta > 1) { |
---|
931 | ++next_node; |
---|
932 | continue; |
---|
933 | } |
---|
934 | return INFEASIBLE; |
---|
935 | } |
---|
936 | |
---|
937 | // Augment along a shortest path from s to t |
---|
938 | Value d = std::min(_excess[s], -_excess[t]); |
---|
939 | int u = t; |
---|
940 | int a; |
---|
941 | if (d > _delta) { |
---|
942 | while ((a = _pred[u]) != -1) { |
---|
943 | if (_res_cap[a] < d) d = _res_cap[a]; |
---|
944 | u = _source[a]; |
---|
945 | } |
---|
946 | } |
---|
947 | u = t; |
---|
948 | while ((a = _pred[u]) != -1) { |
---|
949 | _res_cap[a] -= d; |
---|
950 | _res_cap[_reverse[a]] += d; |
---|
951 | u = _source[a]; |
---|
952 | } |
---|
953 | _excess[s] -= d; |
---|
954 | _excess[t] += d; |
---|
955 | |
---|
956 | if (_excess[s] < _delta) ++next_node; |
---|
957 | } |
---|
958 | |
---|
959 | if (_delta == 1) break; |
---|
960 | _delta = _delta <= _factor ? 1 : _delta / _factor; |
---|
961 | } |
---|
962 | |
---|
963 | return OPTIMAL; |
---|
964 | } |
---|
965 | |
---|
966 | // Execute the successive shortest path algorithm |
---|
967 | ProblemType startWithoutScaling() { |
---|
968 | // Find excess nodes |
---|
969 | _excess_nodes.clear(); |
---|
970 | for (int i = 0; i != _node_num; ++i) { |
---|
971 | if (_excess[i] > 0) _excess_nodes.push_back(i); |
---|
972 | } |
---|
973 | if (_excess_nodes.size() == 0) return OPTIMAL; |
---|
974 | int next_node = 0; |
---|
975 | |
---|
976 | // Find shortest paths |
---|
977 | int s, t; |
---|
978 | ResidualDijkstra _dijkstra(*this); |
---|
979 | while ( _excess[_excess_nodes[next_node]] > 0 || |
---|
980 | ++next_node < int(_excess_nodes.size()) ) |
---|
981 | { |
---|
982 | // Run Dijkstra in the residual network |
---|
983 | s = _excess_nodes[next_node]; |
---|
984 | if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE; |
---|
985 | |
---|
986 | // Augment along a shortest path from s to t |
---|
987 | Value d = std::min(_excess[s], -_excess[t]); |
---|
988 | int u = t; |
---|
989 | int a; |
---|
990 | if (d > 1) { |
---|
991 | while ((a = _pred[u]) != -1) { |
---|
992 | if (_res_cap[a] < d) d = _res_cap[a]; |
---|
993 | u = _source[a]; |
---|
994 | } |
---|
995 | } |
---|
996 | u = t; |
---|
997 | while ((a = _pred[u]) != -1) { |
---|
998 | _res_cap[a] -= d; |
---|
999 | _res_cap[_reverse[a]] += d; |
---|
1000 | u = _source[a]; |
---|
1001 | } |
---|
1002 | _excess[s] -= d; |
---|
1003 | _excess[t] += d; |
---|
1004 | } |
---|
1005 | |
---|
1006 | return OPTIMAL; |
---|
1007 | } |
---|
1008 | |
---|
1009 | }; //class CapacityScaling |
---|
1010 | |
---|
1011 | ///@} |
---|
1012 | |
---|
1013 | } //namespace lemon |
---|
1014 | |
---|
1015 | #endif //LEMON_CAPACITY_SCALING_H |
---|