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/maps.h> |
---|
31 | #include <lemon/bin_heap.h> |
---|
32 | |
---|
33 | namespace lemon { |
---|
34 | |
---|
35 | /// \brief Default traits class of CapacityScaling algorithm. |
---|
36 | /// |
---|
37 | /// Default traits class of CapacityScaling algorithm. |
---|
38 | /// \tparam GR Digraph type. |
---|
39 | /// \tparam V The number type used for flow amounts, capacity bounds |
---|
40 | /// and supply values. By default it is \c int. |
---|
41 | /// \tparam C The number type used for costs and potentials. |
---|
42 | /// By default it is the same as \c V. |
---|
43 | template <typename GR, typename V = int, typename C = V> |
---|
44 | struct CapacityScalingDefaultTraits |
---|
45 | { |
---|
46 | /// The type of the digraph |
---|
47 | typedef GR Digraph; |
---|
48 | /// The type of the flow amounts, capacity bounds and supply values |
---|
49 | typedef V Value; |
---|
50 | /// The type of the arc costs |
---|
51 | typedef C Cost; |
---|
52 | |
---|
53 | /// \brief The type of the heap used for internal Dijkstra computations. |
---|
54 | /// |
---|
55 | /// The type of the heap used for internal Dijkstra computations. |
---|
56 | /// It must conform to the \ref lemon::concepts::Heap "Heap" concept, |
---|
57 | /// its priority type must be \c Cost and its cross reference type |
---|
58 | /// must be \ref RangeMap "RangeMap<int>". |
---|
59 | typedef BinHeap<Cost, RangeMap<int> > Heap; |
---|
60 | }; |
---|
61 | |
---|
62 | /// \addtogroup min_cost_flow_algs |
---|
63 | /// @{ |
---|
64 | |
---|
65 | /// \brief Implementation of the Capacity Scaling algorithm for |
---|
66 | /// finding a \ref min_cost_flow "minimum cost flow". |
---|
67 | /// |
---|
68 | /// \ref CapacityScaling implements the capacity scaling version |
---|
69 | /// of the successive shortest path algorithm for finding a |
---|
70 | /// \ref min_cost_flow "minimum cost flow" \cite amo93networkflows, |
---|
71 | /// \cite edmondskarp72theoretical. It is an efficient dual |
---|
72 | /// solution method, which runs in polynomial time |
---|
73 | /// \f$O(m\log U (n+m)\log n)\f$, where <i>U</i> denotes the maximum |
---|
74 | /// of node supply and arc capacity values. |
---|
75 | /// |
---|
76 | /// This algorithm is typically slower than \ref CostScaling and |
---|
77 | /// \ref NetworkSimplex, but in special cases, it can be more |
---|
78 | /// efficient than them. |
---|
79 | /// (For more information, see \ref min_cost_flow_algs "the module page".) |
---|
80 | /// |
---|
81 | /// Most of the parameters of the problem (except for the digraph) |
---|
82 | /// can be given using separate functions, and the algorithm can be |
---|
83 | /// executed using the \ref run() function. If some parameters are not |
---|
84 | /// specified, then default values will be used. |
---|
85 | /// |
---|
86 | /// \tparam GR The digraph type the algorithm runs on. |
---|
87 | /// \tparam V The number type used for flow amounts, capacity bounds |
---|
88 | /// and supply values in the algorithm. By default, it is \c int. |
---|
89 | /// \tparam C The number type used for costs and potentials in the |
---|
90 | /// algorithm. By default, it is the same as \c V. |
---|
91 | /// \tparam TR The traits class that defines various types used by the |
---|
92 | /// algorithm. By default, it is \ref CapacityScalingDefaultTraits |
---|
93 | /// "CapacityScalingDefaultTraits<GR, V, C>". |
---|
94 | /// In most cases, this parameter should not be set directly, |
---|
95 | /// consider to use the named template parameters instead. |
---|
96 | /// |
---|
97 | /// \warning Both \c V and \c C must be signed number types. |
---|
98 | /// \warning Capacity bounds and supply values must be integer, but |
---|
99 | /// arc costs can be arbitrary real numbers. |
---|
100 | /// \warning This algorithm does not support negative costs for |
---|
101 | /// arcs having infinite upper bound. |
---|
102 | #ifdef DOXYGEN |
---|
103 | template <typename GR, typename V, typename C, typename TR> |
---|
104 | #else |
---|
105 | template < typename GR, typename V = int, typename C = V, |
---|
106 | typename TR = CapacityScalingDefaultTraits<GR, V, C> > |
---|
107 | #endif |
---|
108 | class CapacityScaling |
---|
109 | { |
---|
110 | public: |
---|
111 | |
---|
112 | /// The type of the digraph |
---|
113 | typedef typename TR::Digraph Digraph; |
---|
114 | /// The type of the flow amounts, capacity bounds and supply values |
---|
115 | typedef typename TR::Value Value; |
---|
116 | /// The type of the arc costs |
---|
117 | typedef typename TR::Cost Cost; |
---|
118 | |
---|
119 | /// The type of the heap used for internal Dijkstra computations |
---|
120 | typedef typename TR::Heap Heap; |
---|
121 | |
---|
122 | /// \brief The \ref lemon::CapacityScalingDefaultTraits "traits class" |
---|
123 | /// of the algorithm |
---|
124 | typedef TR Traits; |
---|
125 | |
---|
126 | public: |
---|
127 | |
---|
128 | /// \brief Problem type constants for the \c run() function. |
---|
129 | /// |
---|
130 | /// Enum type containing the problem type constants that can be |
---|
131 | /// returned by the \ref run() function of the algorithm. |
---|
132 | enum ProblemType { |
---|
133 | /// The problem has no feasible solution (flow). |
---|
134 | INFEASIBLE, |
---|
135 | /// The problem has optimal solution (i.e. it is feasible and |
---|
136 | /// bounded), and the algorithm has found optimal flow and node |
---|
137 | /// potentials (primal and dual solutions). |
---|
138 | OPTIMAL, |
---|
139 | /// The digraph contains an arc of negative cost and infinite |
---|
140 | /// upper bound. It means that the objective function is unbounded |
---|
141 | /// on that arc, however, note that it could actually be bounded |
---|
142 | /// over the feasible flows, but this algroithm cannot handle |
---|
143 | /// these cases. |
---|
144 | UNBOUNDED |
---|
145 | }; |
---|
146 | |
---|
147 | private: |
---|
148 | |
---|
149 | TEMPLATE_DIGRAPH_TYPEDEFS(GR); |
---|
150 | |
---|
151 | typedef std::vector<int> IntVector; |
---|
152 | typedef std::vector<Value> ValueVector; |
---|
153 | typedef std::vector<Cost> CostVector; |
---|
154 | typedef std::vector<char> BoolVector; |
---|
155 | // Note: vector<char> is used instead of vector<bool> for efficiency reasons |
---|
156 | |
---|
157 | private: |
---|
158 | |
---|
159 | // Data related to the underlying digraph |
---|
160 | const GR &_graph; |
---|
161 | int _node_num; |
---|
162 | int _arc_num; |
---|
163 | int _res_arc_num; |
---|
164 | int _root; |
---|
165 | |
---|
166 | // Parameters of the problem |
---|
167 | bool _has_lower; |
---|
168 | Value _sum_supply; |
---|
169 | |
---|
170 | // Data structures for storing the digraph |
---|
171 | IntNodeMap _node_id; |
---|
172 | IntArcMap _arc_idf; |
---|
173 | IntArcMap _arc_idb; |
---|
174 | IntVector _first_out; |
---|
175 | BoolVector _forward; |
---|
176 | IntVector _source; |
---|
177 | IntVector _target; |
---|
178 | IntVector _reverse; |
---|
179 | |
---|
180 | // Node and arc data |
---|
181 | ValueVector _lower; |
---|
182 | ValueVector _upper; |
---|
183 | CostVector _cost; |
---|
184 | ValueVector _supply; |
---|
185 | |
---|
186 | ValueVector _res_cap; |
---|
187 | CostVector _pi; |
---|
188 | ValueVector _excess; |
---|
189 | IntVector _excess_nodes; |
---|
190 | IntVector _deficit_nodes; |
---|
191 | |
---|
192 | Value _delta; |
---|
193 | int _factor; |
---|
194 | IntVector _pred; |
---|
195 | |
---|
196 | public: |
---|
197 | |
---|
198 | /// \brief Constant for infinite upper bounds (capacities). |
---|
199 | /// |
---|
200 | /// Constant for infinite upper bounds (capacities). |
---|
201 | /// It is \c std::numeric_limits<Value>::infinity() if available, |
---|
202 | /// \c std::numeric_limits<Value>::max() otherwise. |
---|
203 | const Value INF; |
---|
204 | |
---|
205 | private: |
---|
206 | |
---|
207 | // Special implementation of the Dijkstra algorithm for finding |
---|
208 | // shortest paths in the residual network of the digraph with |
---|
209 | // respect to the reduced arc costs and modifying the node |
---|
210 | // potentials according to the found distance labels. |
---|
211 | class ResidualDijkstra |
---|
212 | { |
---|
213 | private: |
---|
214 | |
---|
215 | int _node_num; |
---|
216 | bool _geq; |
---|
217 | const IntVector &_first_out; |
---|
218 | const IntVector &_target; |
---|
219 | const CostVector &_cost; |
---|
220 | const ValueVector &_res_cap; |
---|
221 | const ValueVector &_excess; |
---|
222 | CostVector &_pi; |
---|
223 | IntVector &_pred; |
---|
224 | |
---|
225 | IntVector _proc_nodes; |
---|
226 | CostVector _dist; |
---|
227 | |
---|
228 | public: |
---|
229 | |
---|
230 | ResidualDijkstra(CapacityScaling& cs) : |
---|
231 | _node_num(cs._node_num), _geq(cs._sum_supply < 0), |
---|
232 | _first_out(cs._first_out), _target(cs._target), _cost(cs._cost), |
---|
233 | _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi), |
---|
234 | _pred(cs._pred), _dist(cs._node_num) |
---|
235 | {} |
---|
236 | |
---|
237 | int run(int s, Value delta = 1) { |
---|
238 | RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP); |
---|
239 | Heap heap(heap_cross_ref); |
---|
240 | heap.push(s, 0); |
---|
241 | _pred[s] = -1; |
---|
242 | _proc_nodes.clear(); |
---|
243 | |
---|
244 | // Process nodes |
---|
245 | while (!heap.empty() && _excess[heap.top()] > -delta) { |
---|
246 | int u = heap.top(), v; |
---|
247 | Cost d = heap.prio() + _pi[u], dn; |
---|
248 | _dist[u] = heap.prio(); |
---|
249 | _proc_nodes.push_back(u); |
---|
250 | heap.pop(); |
---|
251 | |
---|
252 | // Traverse outgoing residual arcs |
---|
253 | int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1; |
---|
254 | for (int a = _first_out[u]; a != last_out; ++a) { |
---|
255 | if (_res_cap[a] < delta) continue; |
---|
256 | v = _target[a]; |
---|
257 | switch (heap.state(v)) { |
---|
258 | case Heap::PRE_HEAP: |
---|
259 | heap.push(v, d + _cost[a] - _pi[v]); |
---|
260 | _pred[v] = a; |
---|
261 | break; |
---|
262 | case Heap::IN_HEAP: |
---|
263 | dn = d + _cost[a] - _pi[v]; |
---|
264 | if (dn < heap[v]) { |
---|
265 | heap.decrease(v, dn); |
---|
266 | _pred[v] = a; |
---|
267 | } |
---|
268 | break; |
---|
269 | case Heap::POST_HEAP: |
---|
270 | break; |
---|
271 | } |
---|
272 | } |
---|
273 | } |
---|
274 | if (heap.empty()) return -1; |
---|
275 | |
---|
276 | // Update potentials of processed nodes |
---|
277 | int t = heap.top(); |
---|
278 | Cost dt = heap.prio(); |
---|
279 | for (int i = 0; i < int(_proc_nodes.size()); ++i) { |
---|
280 | _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt; |
---|
281 | } |
---|
282 | |
---|
283 | return t; |
---|
284 | } |
---|
285 | |
---|
286 | }; //class ResidualDijkstra |
---|
287 | |
---|
288 | public: |
---|
289 | |
---|
290 | /// \name Named Template Parameters |
---|
291 | /// @{ |
---|
292 | |
---|
293 | template <typename T> |
---|
294 | struct SetHeapTraits : public Traits { |
---|
295 | typedef T Heap; |
---|
296 | }; |
---|
297 | |
---|
298 | /// \brief \ref named-templ-param "Named parameter" for setting |
---|
299 | /// \c Heap type. |
---|
300 | /// |
---|
301 | /// \ref named-templ-param "Named parameter" for setting \c Heap |
---|
302 | /// type, which is used for internal Dijkstra computations. |
---|
303 | /// It must conform to the \ref lemon::concepts::Heap "Heap" concept, |
---|
304 | /// its priority type must be \c Cost and its cross reference type |
---|
305 | /// must be \ref RangeMap "RangeMap<int>". |
---|
306 | template <typename T> |
---|
307 | struct SetHeap |
---|
308 | : public CapacityScaling<GR, V, C, SetHeapTraits<T> > { |
---|
309 | typedef CapacityScaling<GR, V, C, SetHeapTraits<T> > Create; |
---|
310 | }; |
---|
311 | |
---|
312 | /// @} |
---|
313 | |
---|
314 | protected: |
---|
315 | |
---|
316 | CapacityScaling() {} |
---|
317 | |
---|
318 | public: |
---|
319 | |
---|
320 | /// \brief Constructor. |
---|
321 | /// |
---|
322 | /// The constructor of the class. |
---|
323 | /// |
---|
324 | /// \param graph The digraph the algorithm runs on. |
---|
325 | CapacityScaling(const GR& graph) : |
---|
326 | _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph), |
---|
327 | INF(std::numeric_limits<Value>::has_infinity ? |
---|
328 | std::numeric_limits<Value>::infinity() : |
---|
329 | std::numeric_limits<Value>::max()) |
---|
330 | { |
---|
331 | // Check the number types |
---|
332 | LEMON_ASSERT(std::numeric_limits<Value>::is_signed, |
---|
333 | "The flow type of CapacityScaling must be signed"); |
---|
334 | LEMON_ASSERT(std::numeric_limits<Cost>::is_signed, |
---|
335 | "The cost type of CapacityScaling must be signed"); |
---|
336 | |
---|
337 | // Reset data structures |
---|
338 | reset(); |
---|
339 | } |
---|
340 | |
---|
341 | /// \name Parameters |
---|
342 | /// The parameters of the algorithm can be specified using these |
---|
343 | /// functions. |
---|
344 | |
---|
345 | /// @{ |
---|
346 | |
---|
347 | /// \brief Set the lower bounds on the arcs. |
---|
348 | /// |
---|
349 | /// This function sets the lower bounds on the arcs. |
---|
350 | /// If it is not used before calling \ref run(), the lower bounds |
---|
351 | /// will be set to zero on all arcs. |
---|
352 | /// |
---|
353 | /// \param map An arc map storing the lower bounds. |
---|
354 | /// Its \c Value type must be convertible to the \c Value type |
---|
355 | /// of the algorithm. |
---|
356 | /// |
---|
357 | /// \return <tt>(*this)</tt> |
---|
358 | template <typename LowerMap> |
---|
359 | CapacityScaling& lowerMap(const LowerMap& map) { |
---|
360 | _has_lower = true; |
---|
361 | for (ArcIt a(_graph); a != INVALID; ++a) { |
---|
362 | _lower[_arc_idf[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 | _has_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 (_has_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 than or equal to the lower bound |
---|
843 | // on each forward arc. |
---|
844 | bool checkBoundMaps() { |
---|
845 | for (int j = 0; j != _res_arc_num; ++j) { |
---|
846 | if (_forward[j] && _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 (_has_lower) { |
---|
861 | int limit = _first_out[_root]; |
---|
862 | for (int j = 0; j != limit; ++j) { |
---|
863 | if (_forward[j]) _res_cap[_reverse[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 |
---|