1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2009 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
/*! |
20 | 20 |
|
21 | 21 |
\page coding_style LEMON Coding Style |
22 | 22 |
|
23 | 23 |
\section naming_conv Naming Conventions |
24 | 24 |
|
25 | 25 |
In order to make development easier we have made some conventions |
26 | 26 |
according to coding style. These include names of types, classes, |
27 | 27 |
functions, variables, constants and exceptions. If these conventions |
28 | 28 |
are met in one's code then it is easier to read and maintain |
29 | 29 |
it. Please comply with these conventions if you want to contribute |
30 | 30 |
developing LEMON library. |
31 | 31 |
|
32 | 32 |
\note When the coding style requires the capitalization of an abbreviation, |
33 | 33 |
only the first letter should be upper case. |
34 | 34 |
|
35 | 35 |
\code |
36 | 36 |
XmlReader |
37 | 37 |
\endcode |
38 | 38 |
|
39 | 39 |
|
40 | 40 |
\warning In some cases we diverge from these rules. |
41 | 41 |
This is primary done because STL uses different naming convention and |
42 | 42 |
in certain cases |
43 | 43 |
it is beneficial to provide STL compatible interface. |
44 | 44 |
|
45 | 45 |
\subsection cs-files File Names |
46 | 46 |
|
47 | 47 |
The header file names should look like the following. |
48 | 48 |
|
49 | 49 |
\code |
50 | 50 |
header_file.h |
51 | 51 |
\endcode |
52 | 52 |
|
53 | 53 |
Note that all standard LEMON headers are located in the \c lemon subdirectory, |
54 | 54 |
so you should include them from C++ source like this: |
55 | 55 |
|
56 | 56 |
\code |
57 | 57 |
#include <lemon/header_file.h> |
58 | 58 |
\endcode |
59 | 59 |
|
60 | 60 |
The source code files use the same style and they have '.cc' extension. |
61 | 61 |
|
62 | 62 |
\code |
63 | 63 |
source_code.cc |
64 | 64 |
\endcode |
65 | 65 |
|
66 | 66 |
\subsection cs-class Classes and other types |
67 | 67 |
|
68 | 68 |
The name of a class or any type should look like the following. |
69 | 69 |
|
70 | 70 |
\code |
71 | 71 |
AllWordsCapitalizedWithoutUnderscores |
72 | 72 |
\endcode |
73 | 73 |
|
74 | 74 |
\subsection cs-func Methods and other functions |
75 | 75 |
|
76 | 76 |
The name of a function should look like the following. |
77 | 77 |
|
78 | 78 |
\code |
79 | 79 |
firstWordLowerCaseRestCapitalizedWithoutUnderscores |
80 | 80 |
\endcode |
81 | 81 |
|
82 | 82 |
\subsection cs-funcs Constants, Macros |
83 | 83 |
|
84 | 84 |
The names of constants and macros should look like the following. |
85 | 85 |
|
86 | 86 |
\code |
87 | 87 |
ALL_UPPER_CASE_WITH_UNDERSCORES |
88 | 88 |
\endcode |
89 | 89 |
|
90 | 90 |
\subsection cs-loc-var Class and instance member variables, auto variables |
91 | 91 |
|
92 | 92 |
The names of class and instance member variables and auto variables |
93 | 93 |
(=variables used locally in methods) should look like the following. |
94 | 94 |
|
95 | 95 |
\code |
96 | 96 |
all_lower_case_with_underscores |
97 | 97 |
\endcode |
98 | 98 |
|
99 | 99 |
\subsection pri-loc-var Private member variables |
100 | 100 |
|
101 |
Private member variables should start with underscore |
|
101 |
Private member variables should start with underscore. |
|
102 | 102 |
|
103 | 103 |
\code |
104 |
|
|
104 |
_start_with_underscore |
|
105 | 105 |
\endcode |
106 | 106 |
|
107 | 107 |
\subsection cs-excep Exceptions |
108 | 108 |
|
109 | 109 |
When writing exceptions please comply the following naming conventions. |
110 | 110 |
|
111 | 111 |
\code |
112 | 112 |
ClassNameEndsWithException |
113 | 113 |
\endcode |
114 | 114 |
|
115 | 115 |
or |
116 | 116 |
|
117 | 117 |
\code |
118 | 118 |
ClassNameEndsWithError |
119 | 119 |
\endcode |
120 | 120 |
|
121 | 121 |
\section header-template Template Header File |
122 | 122 |
|
123 | 123 |
Each LEMON header file should look like this: |
124 | 124 |
|
125 | 125 |
\include template.h |
126 | 126 |
|
127 | 127 |
*/ |
1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2010 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
namespace lemon { |
20 | 20 |
|
21 | 21 |
/** |
22 | 22 |
@defgroup datas Data Structures |
23 | 23 |
This group contains the several data structures implemented in LEMON. |
24 | 24 |
*/ |
25 | 25 |
|
26 | 26 |
/** |
27 | 27 |
@defgroup graphs Graph Structures |
28 | 28 |
@ingroup datas |
29 | 29 |
\brief Graph structures implemented in LEMON. |
30 | 30 |
|
31 | 31 |
The implementation of combinatorial algorithms heavily relies on |
32 | 32 |
efficient graph implementations. LEMON offers data structures which are |
33 | 33 |
planned to be easily used in an experimental phase of implementation studies, |
34 | 34 |
and thereafter the program code can be made efficient by small modifications. |
35 | 35 |
|
36 | 36 |
The most efficient implementation of diverse applications require the |
37 | 37 |
usage of different physical graph implementations. These differences |
38 | 38 |
appear in the size of graph we require to handle, memory or time usage |
39 | 39 |
limitations or in the set of operations through which the graph can be |
40 | 40 |
accessed. LEMON provides several physical graph structures to meet |
41 | 41 |
the diverging requirements of the possible users. In order to save on |
42 | 42 |
running time or on memory usage, some structures may fail to provide |
43 | 43 |
some graph features like arc/edge or node deletion. |
44 | 44 |
|
45 | 45 |
Alteration of standard containers need a very limited number of |
46 | 46 |
operations, these together satisfy the everyday requirements. |
47 | 47 |
In the case of graph structures, different operations are needed which do |
48 | 48 |
not alter the physical graph, but gives another view. If some nodes or |
49 | 49 |
arcs have to be hidden or the reverse oriented graph have to be used, then |
50 | 50 |
this is the case. It also may happen that in a flow implementation |
51 | 51 |
the residual graph can be accessed by another algorithm, or a node-set |
52 | 52 |
is to be shrunk for another algorithm. |
53 | 53 |
LEMON also provides a variety of graphs for these requirements called |
54 | 54 |
\ref graph_adaptors "graph adaptors". Adaptors cannot be used alone but only |
55 | 55 |
in conjunction with other graph representations. |
56 | 56 |
|
57 | 57 |
You are free to use the graph structure that fit your requirements |
58 | 58 |
the best, most graph algorithms and auxiliary data structures can be used |
59 | 59 |
with any graph structure. |
60 | 60 |
|
61 | 61 |
<b>See also:</b> \ref graph_concepts "Graph Structure Concepts". |
62 | 62 |
*/ |
63 | 63 |
|
64 | 64 |
/** |
65 | 65 |
@defgroup graph_adaptors Adaptor Classes for Graphs |
66 | 66 |
@ingroup graphs |
67 | 67 |
\brief Adaptor classes for digraphs and graphs |
68 | 68 |
|
69 | 69 |
This group contains several useful adaptor classes for digraphs and graphs. |
70 | 70 |
|
71 | 71 |
The main parts of LEMON are the different graph structures, generic |
72 | 72 |
graph algorithms, graph concepts, which couple them, and graph |
73 | 73 |
adaptors. While the previous notions are more or less clear, the |
74 | 74 |
latter one needs further explanation. Graph adaptors are graph classes |
75 | 75 |
which serve for considering graph structures in different ways. |
76 | 76 |
|
77 | 77 |
A short example makes this much clearer. Suppose that we have an |
78 | 78 |
instance \c g of a directed graph type, say ListDigraph and an algorithm |
79 | 79 |
\code |
80 | 80 |
template <typename Digraph> |
81 | 81 |
int algorithm(const Digraph&); |
82 | 82 |
\endcode |
83 | 83 |
is needed to run on the reverse oriented graph. It may be expensive |
84 | 84 |
(in time or in memory usage) to copy \c g with the reversed |
85 | 85 |
arcs. In this case, an adaptor class is used, which (according |
86 | 86 |
to LEMON \ref concepts::Digraph "digraph concepts") works as a digraph. |
87 | 87 |
The adaptor uses the original digraph structure and digraph operations when |
88 | 88 |
methods of the reversed oriented graph are called. This means that the adaptor |
89 | 89 |
have minor memory usage, and do not perform sophisticated algorithmic |
90 | 90 |
actions. The purpose of it is to give a tool for the cases when a |
91 | 91 |
graph have to be used in a specific alteration. If this alteration is |
92 | 92 |
obtained by a usual construction like filtering the node or the arc set or |
93 | 93 |
considering a new orientation, then an adaptor is worthwhile to use. |
94 | 94 |
To come back to the reverse oriented graph, in this situation |
95 | 95 |
\code |
96 | 96 |
template<typename Digraph> class ReverseDigraph; |
97 | 97 |
\endcode |
98 | 98 |
template class can be used. The code looks as follows |
99 | 99 |
\code |
100 | 100 |
ListDigraph g; |
101 | 101 |
ReverseDigraph<ListDigraph> rg(g); |
102 | 102 |
int result = algorithm(rg); |
103 | 103 |
\endcode |
104 | 104 |
During running the algorithm, the original digraph \c g is untouched. |
105 | 105 |
This techniques give rise to an elegant code, and based on stable |
106 | 106 |
graph adaptors, complex algorithms can be implemented easily. |
107 | 107 |
|
108 | 108 |
In flow, circulation and matching problems, the residual |
109 | 109 |
graph is of particular importance. Combining an adaptor implementing |
110 | 110 |
this with shortest path algorithms or minimum mean cycle algorithms, |
111 | 111 |
a range of weighted and cardinality optimization algorithms can be |
112 | 112 |
obtained. For other examples, the interested user is referred to the |
113 | 113 |
detailed documentation of particular adaptors. |
114 | 114 |
|
115 | 115 |
The behavior of graph adaptors can be very different. Some of them keep |
116 | 116 |
capabilities of the original graph while in other cases this would be |
117 | 117 |
meaningless. This means that the concepts that they meet depend |
118 | 118 |
on the graph adaptor, and the wrapped graph. |
119 | 119 |
For example, if an arc of a reversed digraph is deleted, this is carried |
120 | 120 |
out by deleting the corresponding arc of the original digraph, thus the |
121 | 121 |
adaptor modifies the original digraph. |
122 | 122 |
However in case of a residual digraph, this operation has no sense. |
123 | 123 |
|
124 | 124 |
Let us stand one more example here to simplify your work. |
125 | 125 |
ReverseDigraph has constructor |
126 | 126 |
\code |
127 | 127 |
ReverseDigraph(Digraph& digraph); |
128 | 128 |
\endcode |
129 | 129 |
This means that in a situation, when a <tt>const %ListDigraph&</tt> |
130 | 130 |
reference to a graph is given, then it have to be instantiated with |
131 | 131 |
<tt>Digraph=const %ListDigraph</tt>. |
132 | 132 |
\code |
133 | 133 |
int algorithm1(const ListDigraph& g) { |
134 | 134 |
ReverseDigraph<const ListDigraph> rg(g); |
135 | 135 |
return algorithm2(rg); |
136 | 136 |
} |
137 | 137 |
\endcode |
138 | 138 |
*/ |
139 | 139 |
|
140 | 140 |
/** |
141 | 141 |
@defgroup maps Maps |
142 | 142 |
@ingroup datas |
143 | 143 |
\brief Map structures implemented in LEMON. |
144 | 144 |
|
145 | 145 |
This group contains the map structures implemented in LEMON. |
146 | 146 |
|
147 | 147 |
LEMON provides several special purpose maps and map adaptors that e.g. combine |
148 | 148 |
new maps from existing ones. |
149 | 149 |
|
150 | 150 |
<b>See also:</b> \ref map_concepts "Map Concepts". |
151 | 151 |
*/ |
152 | 152 |
|
153 | 153 |
/** |
154 | 154 |
@defgroup graph_maps Graph Maps |
155 | 155 |
@ingroup maps |
156 | 156 |
\brief Special graph-related maps. |
157 | 157 |
|
158 | 158 |
This group contains maps that are specifically designed to assign |
159 | 159 |
values to the nodes and arcs/edges of graphs. |
160 | 160 |
|
161 | 161 |
If you are looking for the standard graph maps (\c NodeMap, \c ArcMap, |
162 | 162 |
\c EdgeMap), see the \ref graph_concepts "Graph Structure Concepts". |
163 | 163 |
*/ |
164 | 164 |
|
165 | 165 |
/** |
166 | 166 |
\defgroup map_adaptors Map Adaptors |
167 | 167 |
\ingroup maps |
168 | 168 |
\brief Tools to create new maps from existing ones |
169 | 169 |
|
170 | 170 |
This group contains map adaptors that are used to create "implicit" |
171 | 171 |
maps from other maps. |
172 | 172 |
|
173 | 173 |
Most of them are \ref concepts::ReadMap "read-only maps". |
174 | 174 |
They can make arithmetic and logical operations between one or two maps |
175 | 175 |
(negation, shifting, addition, multiplication, logical 'and', 'or', |
176 | 176 |
'not' etc.) or e.g. convert a map to another one of different Value type. |
177 | 177 |
|
178 | 178 |
The typical usage of this classes is passing implicit maps to |
179 | 179 |
algorithms. If a function type algorithm is called then the function |
180 | 180 |
type map adaptors can be used comfortable. For example let's see the |
181 | 181 |
usage of map adaptors with the \c graphToEps() function. |
182 | 182 |
\code |
183 | 183 |
Color nodeColor(int deg) { |
184 | 184 |
if (deg >= 2) { |
185 | 185 |
return Color(0.5, 0.0, 0.5); |
186 | 186 |
} else if (deg == 1) { |
187 | 187 |
return Color(1.0, 0.5, 1.0); |
188 | 188 |
} else { |
189 | 189 |
return Color(0.0, 0.0, 0.0); |
190 | 190 |
} |
191 | 191 |
} |
192 | 192 |
|
193 | 193 |
Digraph::NodeMap<int> degree_map(graph); |
194 | 194 |
|
195 | 195 |
graphToEps(graph, "graph.eps") |
196 | 196 |
.coords(coords).scaleToA4().undirected() |
197 | 197 |
.nodeColors(composeMap(functorToMap(nodeColor), degree_map)) |
198 | 198 |
.run(); |
199 | 199 |
\endcode |
200 | 200 |
The \c functorToMap() function makes an \c int to \c Color map from the |
201 | 201 |
\c nodeColor() function. The \c composeMap() compose the \c degree_map |
202 | 202 |
and the previously created map. The composed map is a proper function to |
203 | 203 |
get the color of each node. |
204 | 204 |
|
205 | 205 |
The usage with class type algorithms is little bit harder. In this |
206 | 206 |
case the function type map adaptors can not be used, because the |
207 | 207 |
function map adaptors give back temporary objects. |
208 | 208 |
\code |
209 | 209 |
Digraph graph; |
210 | 210 |
|
211 | 211 |
typedef Digraph::ArcMap<double> DoubleArcMap; |
212 | 212 |
DoubleArcMap length(graph); |
213 | 213 |
DoubleArcMap speed(graph); |
214 | 214 |
|
215 | 215 |
typedef DivMap<DoubleArcMap, DoubleArcMap> TimeMap; |
216 | 216 |
TimeMap time(length, speed); |
217 | 217 |
|
218 | 218 |
Dijkstra<Digraph, TimeMap> dijkstra(graph, time); |
219 | 219 |
dijkstra.run(source, target); |
220 | 220 |
\endcode |
221 | 221 |
We have a length map and a maximum speed map on the arcs of a digraph. |
222 | 222 |
The minimum time to pass the arc can be calculated as the division of |
223 | 223 |
the two maps which can be done implicitly with the \c DivMap template |
224 | 224 |
class. We use the implicit minimum time map as the length map of the |
225 | 225 |
\c Dijkstra algorithm. |
226 | 226 |
*/ |
227 | 227 |
|
228 | 228 |
/** |
229 | 229 |
@defgroup paths Path Structures |
230 | 230 |
@ingroup datas |
231 | 231 |
\brief %Path structures implemented in LEMON. |
232 | 232 |
|
233 | 233 |
This group contains the path structures implemented in LEMON. |
234 | 234 |
|
235 | 235 |
LEMON provides flexible data structures to work with paths. |
236 | 236 |
All of them have similar interfaces and they can be copied easily with |
237 | 237 |
assignment operators and copy constructors. This makes it easy and |
238 | 238 |
efficient to have e.g. the Dijkstra algorithm to store its result in |
239 | 239 |
any kind of path structure. |
240 | 240 |
|
241 | 241 |
\sa \ref concepts::Path "Path concept" |
242 | 242 |
*/ |
243 | 243 |
|
244 | 244 |
/** |
245 | 245 |
@defgroup heaps Heap Structures |
246 | 246 |
@ingroup datas |
247 | 247 |
\brief %Heap structures implemented in LEMON. |
248 | 248 |
|
249 | 249 |
This group contains the heap structures implemented in LEMON. |
250 | 250 |
|
251 | 251 |
LEMON provides several heap classes. They are efficient implementations |
252 | 252 |
of the abstract data type \e priority \e queue. They store items with |
253 | 253 |
specified values called \e priorities in such a way that finding and |
254 | 254 |
removing the item with minimum priority are efficient. |
255 | 255 |
The basic operations are adding and erasing items, changing the priority |
256 | 256 |
of an item, etc. |
257 | 257 |
|
258 | 258 |
Heaps are crucial in several algorithms, such as Dijkstra and Prim. |
259 | 259 |
The heap implementations have the same interface, thus any of them can be |
260 | 260 |
used easily in such algorithms. |
261 | 261 |
|
262 | 262 |
\sa \ref concepts::Heap "Heap concept" |
263 | 263 |
*/ |
264 | 264 |
|
265 | 265 |
/** |
266 | 266 |
@defgroup auxdat Auxiliary Data Structures |
267 | 267 |
@ingroup datas |
268 | 268 |
\brief Auxiliary data structures implemented in LEMON. |
269 | 269 |
|
270 | 270 |
This group contains some data structures implemented in LEMON in |
271 | 271 |
order to make it easier to implement combinatorial algorithms. |
272 | 272 |
*/ |
273 | 273 |
|
274 | 274 |
/** |
275 | 275 |
@defgroup geomdat Geometric Data Structures |
276 | 276 |
@ingroup auxdat |
277 | 277 |
\brief Geometric data structures implemented in LEMON. |
278 | 278 |
|
279 | 279 |
This group contains geometric data structures implemented in LEMON. |
280 | 280 |
|
281 | 281 |
- \ref lemon::dim2::Point "dim2::Point" implements a two dimensional |
282 | 282 |
vector with the usual operations. |
283 | 283 |
- \ref lemon::dim2::Box "dim2::Box" can be used to determine the |
284 | 284 |
rectangular bounding box of a set of \ref lemon::dim2::Point |
285 | 285 |
"dim2::Point"'s. |
286 | 286 |
*/ |
287 | 287 |
|
288 | 288 |
/** |
289 | 289 |
@defgroup matrices Matrices |
290 | 290 |
@ingroup auxdat |
291 | 291 |
\brief Two dimensional data storages implemented in LEMON. |
292 | 292 |
|
293 | 293 |
This group contains two dimensional data storages implemented in LEMON. |
294 | 294 |
*/ |
295 | 295 |
|
296 | 296 |
/** |
297 | 297 |
@defgroup algs Algorithms |
298 | 298 |
\brief This group contains the several algorithms |
299 | 299 |
implemented in LEMON. |
300 | 300 |
|
301 | 301 |
This group contains the several algorithms |
302 | 302 |
implemented in LEMON. |
303 | 303 |
*/ |
304 | 304 |
|
305 | 305 |
/** |
306 | 306 |
@defgroup search Graph Search |
307 | 307 |
@ingroup algs |
308 | 308 |
\brief Common graph search algorithms. |
309 | 309 |
|
310 | 310 |
This group contains the common graph search algorithms, namely |
311 | 311 |
\e breadth-first \e search (BFS) and \e depth-first \e search (DFS) |
312 | 312 |
\ref clrs01algorithms. |
313 | 313 |
*/ |
314 | 314 |
|
315 | 315 |
/** |
316 | 316 |
@defgroup shortest_path Shortest Path Algorithms |
317 | 317 |
@ingroup algs |
318 | 318 |
\brief Algorithms for finding shortest paths. |
319 | 319 |
|
320 | 320 |
This group contains the algorithms for finding shortest paths in digraphs |
321 | 321 |
\ref clrs01algorithms. |
322 | 322 |
|
323 | 323 |
- \ref Dijkstra algorithm for finding shortest paths from a source node |
324 | 324 |
when all arc lengths are non-negative. |
325 | 325 |
- \ref BellmanFord "Bellman-Ford" algorithm for finding shortest paths |
326 | 326 |
from a source node when arc lenghts can be either positive or negative, |
327 | 327 |
but the digraph should not contain directed cycles with negative total |
328 | 328 |
length. |
329 | 329 |
- \ref FloydWarshall "Floyd-Warshall" and \ref Johnson "Johnson" algorithms |
330 | 330 |
for solving the \e all-pairs \e shortest \e paths \e problem when arc |
331 | 331 |
lenghts can be either positive or negative, but the digraph should |
332 | 332 |
not contain directed cycles with negative total length. |
333 | 333 |
- \ref Suurballe A successive shortest path algorithm for finding |
334 | 334 |
arc-disjoint paths between two nodes having minimum total length. |
335 | 335 |
*/ |
336 | 336 |
|
337 | 337 |
/** |
338 | 338 |
@defgroup spantree Minimum Spanning Tree Algorithms |
339 | 339 |
@ingroup algs |
340 | 340 |
\brief Algorithms for finding minimum cost spanning trees and arborescences. |
341 | 341 |
|
342 | 342 |
This group contains the algorithms for finding minimum cost spanning |
343 | 343 |
trees and arborescences \ref clrs01algorithms. |
344 | 344 |
*/ |
345 | 345 |
|
346 | 346 |
/** |
347 | 347 |
@defgroup max_flow Maximum Flow Algorithms |
348 | 348 |
@ingroup algs |
349 | 349 |
\brief Algorithms for finding maximum flows. |
350 | 350 |
|
351 | 351 |
This group contains the algorithms for finding maximum flows and |
352 | 352 |
feasible circulations \ref clrs01algorithms, \ref amo93networkflows. |
353 | 353 |
|
354 | 354 |
The \e maximum \e flow \e problem is to find a flow of maximum value between |
355 | 355 |
a single source and a single target. Formally, there is a \f$G=(V,A)\f$ |
356 | 356 |
digraph, a \f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function and |
357 | 357 |
\f$s, t \in V\f$ source and target nodes. |
358 | 358 |
A maximum flow is an \f$f: A\rightarrow\mathbf{R}^+_0\f$ solution of the |
359 | 359 |
following optimization problem. |
360 | 360 |
|
361 | 361 |
\f[ \max\sum_{sv\in A} f(sv) - \sum_{vs\in A} f(vs) \f] |
362 | 362 |
\f[ \sum_{uv\in A} f(uv) = \sum_{vu\in A} f(vu) |
363 | 363 |
\quad \forall u\in V\setminus\{s,t\} \f] |
364 | 364 |
\f[ 0 \leq f(uv) \leq cap(uv) \quad \forall uv\in A \f] |
365 | 365 |
|
366 | 366 |
LEMON contains several algorithms for solving maximum flow problems: |
367 | 367 |
- \ref EdmondsKarp Edmonds-Karp algorithm |
368 | 368 |
\ref edmondskarp72theoretical. |
369 | 369 |
- \ref Preflow Goldberg-Tarjan's preflow push-relabel algorithm |
370 | 370 |
\ref goldberg88newapproach. |
371 | 371 |
- \ref DinitzSleatorTarjan Dinitz's blocking flow algorithm with dynamic trees |
372 | 372 |
\ref dinic70algorithm, \ref sleator83dynamic. |
373 | 373 |
- \ref GoldbergTarjan !Preflow push-relabel algorithm with dynamic trees |
374 | 374 |
\ref goldberg88newapproach, \ref sleator83dynamic. |
375 | 375 |
|
376 | 376 |
In most cases the \ref Preflow algorithm provides the |
377 | 377 |
fastest method for computing a maximum flow. All implementations |
378 | 378 |
also provide functions to query the minimum cut, which is the dual |
379 | 379 |
problem of maximum flow. |
380 | 380 |
|
381 | 381 |
\ref Circulation is a preflow push-relabel algorithm implemented directly |
382 | 382 |
for finding feasible circulations, which is a somewhat different problem, |
383 | 383 |
but it is strongly related to maximum flow. |
384 | 384 |
For more information, see \ref Circulation. |
385 | 385 |
*/ |
386 | 386 |
|
387 | 387 |
/** |
388 | 388 |
@defgroup min_cost_flow_algs Minimum Cost Flow Algorithms |
389 | 389 |
@ingroup algs |
390 | 390 |
|
391 | 391 |
\brief Algorithms for finding minimum cost flows and circulations. |
392 | 392 |
|
393 | 393 |
This group contains the algorithms for finding minimum cost flows and |
394 | 394 |
circulations \ref amo93networkflows. For more information about this |
395 | 395 |
problem and its dual solution, see \ref min_cost_flow |
396 | 396 |
"Minimum Cost Flow Problem". |
397 | 397 |
|
398 | 398 |
LEMON contains several algorithms for this problem. |
399 | 399 |
- \ref NetworkSimplex Primal Network Simplex algorithm with various |
400 | 400 |
pivot strategies \ref dantzig63linearprog, \ref kellyoneill91netsimplex. |
401 | 401 |
- \ref CostScaling Cost Scaling algorithm based on push/augment and |
402 | 402 |
relabel operations \ref goldberg90approximation, \ref goldberg97efficient, |
403 | 403 |
\ref bunnagel98efficient. |
404 | 404 |
- \ref CapacityScaling Capacity Scaling algorithm based on the successive |
405 | 405 |
shortest path method \ref edmondskarp72theoretical. |
406 | 406 |
- \ref CycleCanceling Cycle-Canceling algorithms, two of which are |
407 | 407 |
strongly polynomial \ref klein67primal, \ref goldberg89cyclecanceling. |
408 | 408 |
|
409 |
In general NetworkSimplex is the most efficient implementation, |
|
410 |
but in special cases other algorithms could be faster. |
|
409 |
In general, \ref NetworkSimplex and \ref CostScaling are the most efficient |
|
410 |
implementations, but the other two algorithms could be faster in special cases. |
|
411 | 411 |
For example, if the total supply and/or capacities are rather small, |
412 |
CapacityScaling is usually the fastest algorithm (without effective scaling). |
|
412 |
\ref CapacityScaling is usually the fastest algorithm (without effective scaling). |
|
413 | 413 |
*/ |
414 | 414 |
|
415 | 415 |
/** |
416 | 416 |
@defgroup min_cut Minimum Cut Algorithms |
417 | 417 |
@ingroup algs |
418 | 418 |
|
419 | 419 |
\brief Algorithms for finding minimum cut in graphs. |
420 | 420 |
|
421 | 421 |
This group contains the algorithms for finding minimum cut in graphs. |
422 | 422 |
|
423 | 423 |
The \e minimum \e cut \e problem is to find a non-empty and non-complete |
424 | 424 |
\f$X\f$ subset of the nodes with minimum overall capacity on |
425 | 425 |
outgoing arcs. Formally, there is a \f$G=(V,A)\f$ digraph, a |
426 | 426 |
\f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function. The minimum |
427 | 427 |
cut is the \f$X\f$ solution of the next optimization problem: |
428 | 428 |
|
429 | 429 |
\f[ \min_{X \subset V, X\not\in \{\emptyset, V\}} |
430 | 430 |
\sum_{uv\in A: u\in X, v\not\in X}cap(uv) \f] |
431 | 431 |
|
432 | 432 |
LEMON contains several algorithms related to minimum cut problems: |
433 | 433 |
|
434 | 434 |
- \ref HaoOrlin "Hao-Orlin algorithm" for calculating minimum cut |
435 | 435 |
in directed graphs. |
436 | 436 |
- \ref NagamochiIbaraki "Nagamochi-Ibaraki algorithm" for |
437 | 437 |
calculating minimum cut in undirected graphs. |
438 | 438 |
- \ref GomoryHu "Gomory-Hu tree computation" for calculating |
439 | 439 |
all-pairs minimum cut in undirected graphs. |
440 | 440 |
|
441 | 441 |
If you want to find minimum cut just between two distinict nodes, |
442 | 442 |
see the \ref max_flow "maximum flow problem". |
443 | 443 |
*/ |
444 | 444 |
|
445 | 445 |
/** |
446 | 446 |
@defgroup min_mean_cycle Minimum Mean Cycle Algorithms |
447 | 447 |
@ingroup algs |
448 | 448 |
\brief Algorithms for finding minimum mean cycles. |
449 | 449 |
|
450 | 450 |
This group contains the algorithms for finding minimum mean cycles |
451 | 451 |
\ref clrs01algorithms, \ref amo93networkflows. |
452 | 452 |
|
453 | 453 |
The \e minimum \e mean \e cycle \e problem is to find a directed cycle |
454 | 454 |
of minimum mean length (cost) in a digraph. |
455 | 455 |
The mean length of a cycle is the average length of its arcs, i.e. the |
456 | 456 |
ratio between the total length of the cycle and the number of arcs on it. |
457 | 457 |
|
458 | 458 |
This problem has an important connection to \e conservative \e length |
459 | 459 |
\e functions, too. A length function on the arcs of a digraph is called |
460 | 460 |
conservative if and only if there is no directed cycle of negative total |
461 | 461 |
length. For an arbitrary length function, the negative of the minimum |
462 | 462 |
cycle mean is the smallest \f$\epsilon\f$ value so that increasing the |
463 | 463 |
arc lengths uniformly by \f$\epsilon\f$ results in a conservative length |
464 | 464 |
function. |
465 | 465 |
|
466 | 466 |
LEMON contains three algorithms for solving the minimum mean cycle problem: |
467 | 467 |
- \ref KarpMmc Karp's original algorithm \ref amo93networkflows, |
468 | 468 |
\ref dasdan98minmeancycle. |
469 | 469 |
- \ref HartmannOrlinMmc Hartmann-Orlin's algorithm, which is an improved |
470 | 470 |
version of Karp's algorithm \ref dasdan98minmeancycle. |
471 | 471 |
- \ref HowardMmc Howard's policy iteration algorithm |
472 | 472 |
\ref dasdan98minmeancycle. |
473 | 473 |
|
474 |
In practice, the \ref HowardMmc "Howard" algorithm |
|
474 |
In practice, the \ref HowardMmc "Howard" algorithm turned out to be by far the |
|
475 | 475 |
most efficient one, though the best known theoretical bound on its running |
476 | 476 |
time is exponential. |
477 | 477 |
Both \ref KarpMmc "Karp" and \ref HartmannOrlinMmc "Hartmann-Orlin" algorithms |
478 | 478 |
run in time O(ne) and use space O(n<sup>2</sup>+e), but the latter one is |
479 | 479 |
typically faster due to the applied early termination scheme. |
480 | 480 |
*/ |
481 | 481 |
|
482 | 482 |
/** |
483 | 483 |
@defgroup matching Matching Algorithms |
484 | 484 |
@ingroup algs |
485 | 485 |
\brief Algorithms for finding matchings in graphs and bipartite graphs. |
486 | 486 |
|
487 | 487 |
This group contains the algorithms for calculating |
488 | 488 |
matchings in graphs and bipartite graphs. The general matching problem is |
489 | 489 |
finding a subset of the edges for which each node has at most one incident |
490 | 490 |
edge. |
491 | 491 |
|
492 | 492 |
There are several different algorithms for calculate matchings in |
493 | 493 |
graphs. The matching problems in bipartite graphs are generally |
494 | 494 |
easier than in general graphs. The goal of the matching optimization |
495 | 495 |
can be finding maximum cardinality, maximum weight or minimum cost |
496 | 496 |
matching. The search can be constrained to find perfect or |
497 | 497 |
maximum cardinality matching. |
498 | 498 |
|
499 | 499 |
The matching algorithms implemented in LEMON: |
500 | 500 |
- \ref MaxBipartiteMatching Hopcroft-Karp augmenting path algorithm |
501 | 501 |
for calculating maximum cardinality matching in bipartite graphs. |
502 | 502 |
- \ref PrBipartiteMatching Push-relabel algorithm |
503 | 503 |
for calculating maximum cardinality matching in bipartite graphs. |
504 | 504 |
- \ref MaxWeightedBipartiteMatching |
505 | 505 |
Successive shortest path algorithm for calculating maximum weighted |
506 | 506 |
matching and maximum weighted bipartite matching in bipartite graphs. |
507 | 507 |
- \ref MinCostMaxBipartiteMatching |
508 | 508 |
Successive shortest path algorithm for calculating minimum cost maximum |
509 | 509 |
matching in bipartite graphs. |
510 | 510 |
- \ref MaxMatching Edmond's blossom shrinking algorithm for calculating |
511 | 511 |
maximum cardinality matching in general graphs. |
512 | 512 |
- \ref MaxWeightedMatching Edmond's blossom shrinking algorithm for calculating |
513 | 513 |
maximum weighted matching in general graphs. |
514 | 514 |
- \ref MaxWeightedPerfectMatching |
515 | 515 |
Edmond's blossom shrinking algorithm for calculating maximum weighted |
516 | 516 |
perfect matching in general graphs. |
517 | 517 |
- \ref MaxFractionalMatching Push-relabel algorithm for calculating |
518 | 518 |
maximum cardinality fractional matching in general graphs. |
519 | 519 |
- \ref MaxWeightedFractionalMatching Augmenting path algorithm for calculating |
520 | 520 |
maximum weighted fractional matching in general graphs. |
521 | 521 |
- \ref MaxWeightedPerfectFractionalMatching |
522 | 522 |
Augmenting path algorithm for calculating maximum weighted |
523 | 523 |
perfect fractional matching in general graphs. |
524 | 524 |
|
525 | 525 |
\image html matching.png |
526 | 526 |
\image latex matching.eps "Min Cost Perfect Matching" width=\textwidth |
527 | 527 |
*/ |
528 | 528 |
|
529 | 529 |
/** |
530 | 530 |
@defgroup graph_properties Connectivity and Other Graph Properties |
531 | 531 |
@ingroup algs |
532 | 532 |
\brief Algorithms for discovering the graph properties |
533 | 533 |
|
534 | 534 |
This group contains the algorithms for discovering the graph properties |
535 | 535 |
like connectivity, bipartiteness, euler property, simplicity etc. |
536 | 536 |
|
537 | 537 |
\image html connected_components.png |
538 | 538 |
\image latex connected_components.eps "Connected components" width=\textwidth |
539 | 539 |
*/ |
540 | 540 |
|
541 | 541 |
/** |
542 |
@defgroup planar |
|
542 |
@defgroup planar Planar Embedding and Drawing |
|
543 | 543 |
@ingroup algs |
544 | 544 |
\brief Algorithms for planarity checking, embedding and drawing |
545 | 545 |
|
546 | 546 |
This group contains the algorithms for planarity checking, |
547 | 547 |
embedding and drawing. |
548 | 548 |
|
549 | 549 |
\image html planar.png |
550 | 550 |
\image latex planar.eps "Plane graph" width=\textwidth |
551 | 551 |
*/ |
552 | 552 |
|
553 | 553 |
/** |
554 | 554 |
@defgroup approx_algs Approximation Algorithms |
555 | 555 |
@ingroup algs |
556 | 556 |
\brief Approximation algorithms. |
557 | 557 |
|
558 | 558 |
This group contains the approximation and heuristic algorithms |
559 | 559 |
implemented in LEMON. |
560 | 560 |
|
561 | 561 |
<b>Maximum Clique Problem</b> |
562 | 562 |
- \ref GrossoLocatelliPullanMc An efficient heuristic algorithm of |
563 | 563 |
Grosso, Locatelli, and Pullan. |
564 | 564 |
*/ |
565 | 565 |
|
566 | 566 |
/** |
567 | 567 |
@defgroup auxalg Auxiliary Algorithms |
568 | 568 |
@ingroup algs |
569 | 569 |
\brief Auxiliary algorithms implemented in LEMON. |
570 | 570 |
|
571 | 571 |
This group contains some algorithms implemented in LEMON |
572 | 572 |
in order to make it easier to implement complex algorithms. |
573 | 573 |
*/ |
574 | 574 |
|
575 | 575 |
/** |
576 | 576 |
@defgroup gen_opt_group General Optimization Tools |
577 | 577 |
\brief This group contains some general optimization frameworks |
578 | 578 |
implemented in LEMON. |
579 | 579 |
|
580 | 580 |
This group contains some general optimization frameworks |
581 | 581 |
implemented in LEMON. |
582 | 582 |
*/ |
583 | 583 |
|
584 | 584 |
/** |
585 | 585 |
@defgroup lp_group LP and MIP Solvers |
586 | 586 |
@ingroup gen_opt_group |
587 | 587 |
\brief LP and MIP solver interfaces for LEMON. |
588 | 588 |
|
589 | 589 |
This group contains LP and MIP solver interfaces for LEMON. |
590 | 590 |
Various LP solvers could be used in the same manner with this |
591 | 591 |
high-level interface. |
592 | 592 |
|
593 | 593 |
The currently supported solvers are \ref glpk, \ref clp, \ref cbc, |
594 | 594 |
\ref cplex, \ref soplex. |
595 | 595 |
*/ |
596 | 596 |
|
597 | 597 |
/** |
598 | 598 |
@defgroup lp_utils Tools for Lp and Mip Solvers |
599 | 599 |
@ingroup lp_group |
600 | 600 |
\brief Helper tools to the Lp and Mip solvers. |
601 | 601 |
|
602 | 602 |
This group adds some helper tools to general optimization framework |
603 | 603 |
implemented in LEMON. |
604 | 604 |
*/ |
605 | 605 |
|
606 | 606 |
/** |
607 | 607 |
@defgroup metah Metaheuristics |
608 | 608 |
@ingroup gen_opt_group |
609 | 609 |
\brief Metaheuristics for LEMON library. |
610 | 610 |
|
611 | 611 |
This group contains some metaheuristic optimization tools. |
612 | 612 |
*/ |
613 | 613 |
|
614 | 614 |
/** |
615 | 615 |
@defgroup utils Tools and Utilities |
616 | 616 |
\brief Tools and utilities for programming in LEMON |
617 | 617 |
|
618 | 618 |
Tools and utilities for programming in LEMON. |
619 | 619 |
*/ |
620 | 620 |
|
621 | 621 |
/** |
622 | 622 |
@defgroup gutils Basic Graph Utilities |
623 | 623 |
@ingroup utils |
624 | 624 |
\brief Simple basic graph utilities. |
625 | 625 |
|
626 | 626 |
This group contains some simple basic graph utilities. |
627 | 627 |
*/ |
628 | 628 |
|
629 | 629 |
/** |
630 | 630 |
@defgroup misc Miscellaneous Tools |
631 | 631 |
@ingroup utils |
632 | 632 |
\brief Tools for development, debugging and testing. |
633 | 633 |
|
634 | 634 |
This group contains several useful tools for development, |
635 | 635 |
debugging and testing. |
636 | 636 |
*/ |
637 | 637 |
|
638 | 638 |
/** |
639 | 639 |
@defgroup timecount Time Measuring and Counting |
640 | 640 |
@ingroup misc |
641 | 641 |
\brief Simple tools for measuring the performance of algorithms. |
642 | 642 |
|
643 | 643 |
This group contains simple tools for measuring the performance |
644 | 644 |
of algorithms. |
645 | 645 |
*/ |
646 | 646 |
|
647 | 647 |
/** |
648 | 648 |
@defgroup exceptions Exceptions |
649 | 649 |
@ingroup utils |
650 | 650 |
\brief Exceptions defined in LEMON. |
651 | 651 |
|
652 | 652 |
This group contains the exceptions defined in LEMON. |
653 | 653 |
*/ |
654 | 654 |
|
655 | 655 |
/** |
656 | 656 |
@defgroup io_group Input-Output |
657 | 657 |
\brief Graph Input-Output methods |
658 | 658 |
|
659 | 659 |
This group contains the tools for importing and exporting graphs |
660 | 660 |
and graph related data. Now it supports the \ref lgf-format |
661 | 661 |
"LEMON Graph Format", the \c DIMACS format and the encapsulated |
662 | 662 |
postscript (EPS) format. |
663 | 663 |
*/ |
664 | 664 |
|
665 | 665 |
/** |
666 | 666 |
@defgroup lemon_io LEMON Graph Format |
667 | 667 |
@ingroup io_group |
668 | 668 |
\brief Reading and writing LEMON Graph Format. |
669 | 669 |
|
670 | 670 |
This group contains methods for reading and writing |
671 | 671 |
\ref lgf-format "LEMON Graph Format". |
672 | 672 |
*/ |
673 | 673 |
|
674 | 674 |
/** |
675 | 675 |
@defgroup eps_io Postscript Exporting |
676 | 676 |
@ingroup io_group |
677 | 677 |
\brief General \c EPS drawer and graph exporter |
678 | 678 |
|
679 | 679 |
This group contains general \c EPS drawing methods and special |
680 | 680 |
graph exporting tools. |
681 | 681 |
*/ |
682 | 682 |
|
683 | 683 |
/** |
684 | 684 |
@defgroup dimacs_group DIMACS Format |
685 | 685 |
@ingroup io_group |
686 | 686 |
\brief Read and write files in DIMACS format |
687 | 687 |
|
688 | 688 |
Tools to read a digraph from or write it to a file in DIMACS format data. |
689 | 689 |
*/ |
690 | 690 |
|
691 | 691 |
/** |
692 | 692 |
@defgroup nauty_group NAUTY Format |
693 | 693 |
@ingroup io_group |
694 | 694 |
\brief Read \e Nauty format |
695 | 695 |
|
696 | 696 |
Tool to read graphs from \e Nauty format data. |
697 | 697 |
*/ |
698 | 698 |
|
699 | 699 |
/** |
700 | 700 |
@defgroup concept Concepts |
701 | 701 |
\brief Skeleton classes and concept checking classes |
702 | 702 |
|
703 | 703 |
This group contains the data/algorithm skeletons and concept checking |
704 | 704 |
classes implemented in LEMON. |
705 | 705 |
|
706 | 706 |
The purpose of the classes in this group is fourfold. |
707 | 707 |
|
708 | 708 |
- These classes contain the documentations of the %concepts. In order |
709 | 709 |
to avoid document multiplications, an implementation of a concept |
710 | 710 |
simply refers to the corresponding concept class. |
711 | 711 |
|
712 | 712 |
- These classes declare every functions, <tt>typedef</tt>s etc. an |
713 | 713 |
implementation of the %concepts should provide, however completely |
714 | 714 |
without implementations and real data structures behind the |
715 | 715 |
interface. On the other hand they should provide nothing else. All |
716 | 716 |
the algorithms working on a data structure meeting a certain concept |
717 | 717 |
should compile with these classes. (Though it will not run properly, |
718 | 718 |
of course.) In this way it is easily to check if an algorithm |
719 | 719 |
doesn't use any extra feature of a certain implementation. |
720 | 720 |
|
721 | 721 |
- The concept descriptor classes also provide a <em>checker class</em> |
722 | 722 |
that makes it possible to check whether a certain implementation of a |
723 | 723 |
concept indeed provides all the required features. |
724 | 724 |
|
725 | 725 |
- Finally, They can serve as a skeleton of a new implementation of a concept. |
726 | 726 |
*/ |
727 | 727 |
|
728 | 728 |
/** |
729 | 729 |
@defgroup graph_concepts Graph Structure Concepts |
730 | 730 |
@ingroup concept |
731 | 731 |
\brief Skeleton and concept checking classes for graph structures |
732 | 732 |
|
733 | 733 |
This group contains the skeletons and concept checking classes of |
734 | 734 |
graph structures. |
735 | 735 |
*/ |
736 | 736 |
|
737 | 737 |
/** |
738 | 738 |
@defgroup map_concepts Map Concepts |
739 | 739 |
@ingroup concept |
740 | 740 |
\brief Skeleton and concept checking classes for maps |
741 | 741 |
|
742 | 742 |
This group contains the skeletons and concept checking classes of maps. |
743 | 743 |
*/ |
744 | 744 |
|
745 | 745 |
/** |
746 | 746 |
@defgroup tools Standalone Utility Applications |
747 | 747 |
|
748 | 748 |
Some utility applications are listed here. |
749 | 749 |
|
750 | 750 |
The standard compilation procedure (<tt>./configure;make</tt>) will compile |
751 | 751 |
them, as well. |
752 | 752 |
*/ |
753 | 753 |
|
754 | 754 |
/** |
755 | 755 |
\anchor demoprograms |
756 | 756 |
|
757 | 757 |
@defgroup demos Demo Programs |
758 | 758 |
|
759 | 759 |
Some demo programs are listed here. Their full source codes can be found in |
760 | 760 |
the \c demo subdirectory of the source tree. |
761 | 761 |
|
762 | 762 |
In order to compile them, use the <tt>make demo</tt> or the |
763 | 763 |
<tt>make check</tt> commands. |
764 | 764 |
*/ |
765 | 765 |
|
766 | 766 |
} |
1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2010 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
#ifndef LEMON_CAPACITY_SCALING_H |
20 | 20 |
#define LEMON_CAPACITY_SCALING_H |
21 | 21 |
|
22 | 22 |
/// \ingroup min_cost_flow_algs |
23 | 23 |
/// |
24 | 24 |
/// \file |
25 | 25 |
/// \brief Capacity Scaling algorithm for finding a minimum cost flow. |
26 | 26 |
|
27 | 27 |
#include <vector> |
28 | 28 |
#include <limits> |
29 | 29 |
#include <lemon/core.h> |
30 | 30 |
#include <lemon/bin_heap.h> |
31 | 31 |
|
32 | 32 |
namespace lemon { |
33 | 33 |
|
34 | 34 |
/// \brief Default traits class of CapacityScaling algorithm. |
35 | 35 |
/// |
36 | 36 |
/// Default traits class of CapacityScaling algorithm. |
37 | 37 |
/// \tparam GR Digraph type. |
38 | 38 |
/// \tparam V The number type used for flow amounts, capacity bounds |
39 | 39 |
/// and supply values. By default it is \c int. |
40 | 40 |
/// \tparam C The number type used for costs and potentials. |
41 | 41 |
/// By default it is the same as \c V. |
42 | 42 |
template <typename GR, typename V = int, typename C = V> |
43 | 43 |
struct CapacityScalingDefaultTraits |
44 | 44 |
{ |
45 | 45 |
/// The type of the digraph |
46 | 46 |
typedef GR Digraph; |
47 | 47 |
/// The type of the flow amounts, capacity bounds and supply values |
48 | 48 |
typedef V Value; |
49 | 49 |
/// The type of the arc costs |
50 | 50 |
typedef C Cost; |
51 | 51 |
|
52 | 52 |
/// \brief The type of the heap used for internal Dijkstra computations. |
53 | 53 |
/// |
54 | 54 |
/// The type of the heap used for internal Dijkstra computations. |
55 | 55 |
/// It must conform to the \ref lemon::concepts::Heap "Heap" concept, |
56 | 56 |
/// its priority type must be \c Cost and its cross reference type |
57 | 57 |
/// must be \ref RangeMap "RangeMap<int>". |
58 | 58 |
typedef BinHeap<Cost, RangeMap<int> > Heap; |
59 | 59 |
}; |
60 | 60 |
|
61 | 61 |
/// \addtogroup min_cost_flow_algs |
62 | 62 |
/// @{ |
63 | 63 |
|
64 | 64 |
/// \brief Implementation of the Capacity Scaling algorithm for |
65 | 65 |
/// finding a \ref min_cost_flow "minimum cost flow". |
66 | 66 |
/// |
67 | 67 |
/// \ref CapacityScaling implements the capacity scaling version |
68 | 68 |
/// of the successive shortest path algorithm for finding a |
69 | 69 |
/// \ref min_cost_flow "minimum cost flow" \ref amo93networkflows, |
70 | 70 |
/// \ref edmondskarp72theoretical. It is an efficient dual |
71 | 71 |
/// solution method. |
72 | 72 |
/// |
73 | 73 |
/// Most of the parameters of the problem (except for the digraph) |
74 | 74 |
/// can be given using separate functions, and the algorithm can be |
75 | 75 |
/// executed using the \ref run() function. If some parameters are not |
76 | 76 |
/// specified, then default values will be used. |
77 | 77 |
/// |
78 | 78 |
/// \tparam GR The digraph type the algorithm runs on. |
79 | 79 |
/// \tparam V The number type used for flow amounts, capacity bounds |
80 | 80 |
/// and supply values in the algorithm. By default, it is \c int. |
81 | 81 |
/// \tparam C The number type used for costs and potentials in the |
82 | 82 |
/// algorithm. By default, it is the same as \c V. |
83 | 83 |
/// \tparam TR The traits class that defines various types used by the |
84 | 84 |
/// algorithm. By default, it is \ref CapacityScalingDefaultTraits |
85 | 85 |
/// "CapacityScalingDefaultTraits<GR, V, C>". |
86 | 86 |
/// In most cases, this parameter should not be set directly, |
87 | 87 |
/// consider to use the named template parameters instead. |
88 | 88 |
/// |
89 | 89 |
/// \warning Both \c V and \c C must be signed number types. |
90 | 90 |
/// \warning All input data (capacities, supply values, and costs) must |
91 | 91 |
/// be integer. |
92 |
/// \warning This algorithm does not support negative costs for such |
|
93 |
/// arcs that have infinite upper bound. |
|
92 |
/// \warning This algorithm does not support negative costs for |
|
93 |
/// arcs having infinite upper bound. |
|
94 | 94 |
#ifdef DOXYGEN |
95 | 95 |
template <typename GR, typename V, typename C, typename TR> |
96 | 96 |
#else |
97 | 97 |
template < typename GR, typename V = int, typename C = V, |
98 | 98 |
typename TR = CapacityScalingDefaultTraits<GR, V, C> > |
99 | 99 |
#endif |
100 | 100 |
class CapacityScaling |
101 | 101 |
{ |
102 | 102 |
public: |
103 | 103 |
|
104 | 104 |
/// The type of the digraph |
105 | 105 |
typedef typename TR::Digraph Digraph; |
106 | 106 |
/// The type of the flow amounts, capacity bounds and supply values |
107 | 107 |
typedef typename TR::Value Value; |
108 | 108 |
/// The type of the arc costs |
109 | 109 |
typedef typename TR::Cost Cost; |
110 | 110 |
|
111 | 111 |
/// The type of the heap used for internal Dijkstra computations |
112 | 112 |
typedef typename TR::Heap Heap; |
113 | 113 |
|
114 | 114 |
/// The \ref CapacityScalingDefaultTraits "traits class" of the algorithm |
115 | 115 |
typedef TR Traits; |
116 | 116 |
|
117 | 117 |
public: |
118 | 118 |
|
119 | 119 |
/// \brief Problem type constants for the \c run() function. |
120 | 120 |
/// |
121 | 121 |
/// Enum type containing the problem type constants that can be |
122 | 122 |
/// returned by the \ref run() function of the algorithm. |
123 | 123 |
enum ProblemType { |
124 | 124 |
/// The problem has no feasible solution (flow). |
125 | 125 |
INFEASIBLE, |
126 | 126 |
/// The problem has optimal solution (i.e. it is feasible and |
127 | 127 |
/// bounded), and the algorithm has found optimal flow and node |
128 | 128 |
/// potentials (primal and dual solutions). |
129 | 129 |
OPTIMAL, |
130 | 130 |
/// The digraph contains an arc of negative cost and infinite |
131 | 131 |
/// upper bound. It means that the objective function is unbounded |
132 | 132 |
/// on that arc, however, note that it could actually be bounded |
133 | 133 |
/// over the feasible flows, but this algroithm cannot handle |
134 | 134 |
/// these cases. |
135 | 135 |
UNBOUNDED |
136 | 136 |
}; |
137 | 137 |
|
138 | 138 |
private: |
139 | 139 |
|
140 | 140 |
TEMPLATE_DIGRAPH_TYPEDEFS(GR); |
141 | 141 |
|
142 | 142 |
typedef std::vector<int> IntVector; |
143 | 143 |
typedef std::vector<Value> ValueVector; |
144 | 144 |
typedef std::vector<Cost> CostVector; |
145 | 145 |
typedef std::vector<char> BoolVector; |
146 | 146 |
// Note: vector<char> is used instead of vector<bool> for efficiency reasons |
147 | 147 |
|
148 | 148 |
private: |
149 | 149 |
|
150 | 150 |
// Data related to the underlying digraph |
151 | 151 |
const GR &_graph; |
152 | 152 |
int _node_num; |
153 | 153 |
int _arc_num; |
154 | 154 |
int _res_arc_num; |
155 | 155 |
int _root; |
156 | 156 |
|
157 | 157 |
// Parameters of the problem |
158 | 158 |
bool _have_lower; |
159 | 159 |
Value _sum_supply; |
160 | 160 |
|
161 | 161 |
// Data structures for storing the digraph |
162 | 162 |
IntNodeMap _node_id; |
163 | 163 |
IntArcMap _arc_idf; |
164 | 164 |
IntArcMap _arc_idb; |
165 | 165 |
IntVector _first_out; |
166 | 166 |
BoolVector _forward; |
167 | 167 |
IntVector _source; |
168 | 168 |
IntVector _target; |
169 | 169 |
IntVector _reverse; |
170 | 170 |
|
171 | 171 |
// Node and arc data |
172 | 172 |
ValueVector _lower; |
173 | 173 |
ValueVector _upper; |
174 | 174 |
CostVector _cost; |
175 | 175 |
ValueVector _supply; |
176 | 176 |
|
177 | 177 |
ValueVector _res_cap; |
178 | 178 |
CostVector _pi; |
179 | 179 |
ValueVector _excess; |
180 | 180 |
IntVector _excess_nodes; |
181 | 181 |
IntVector _deficit_nodes; |
182 | 182 |
|
183 | 183 |
Value _delta; |
184 | 184 |
int _factor; |
185 | 185 |
IntVector _pred; |
186 | 186 |
|
187 | 187 |
public: |
188 | 188 |
|
189 | 189 |
/// \brief Constant for infinite upper bounds (capacities). |
190 | 190 |
/// |
191 | 191 |
/// Constant for infinite upper bounds (capacities). |
192 | 192 |
/// It is \c std::numeric_limits<Value>::infinity() if available, |
193 | 193 |
/// \c std::numeric_limits<Value>::max() otherwise. |
194 | 194 |
const Value INF; |
195 | 195 |
|
196 | 196 |
private: |
197 | 197 |
|
198 | 198 |
// Special implementation of the Dijkstra algorithm for finding |
199 | 199 |
// shortest paths in the residual network of the digraph with |
200 | 200 |
// respect to the reduced arc costs and modifying the node |
201 | 201 |
// potentials according to the found distance labels. |
202 | 202 |
class ResidualDijkstra |
203 | 203 |
{ |
204 | 204 |
private: |
205 | 205 |
|
206 | 206 |
int _node_num; |
207 | 207 |
bool _geq; |
208 | 208 |
const IntVector &_first_out; |
209 | 209 |
const IntVector &_target; |
210 | 210 |
const CostVector &_cost; |
211 | 211 |
const ValueVector &_res_cap; |
212 | 212 |
const ValueVector &_excess; |
213 | 213 |
CostVector &_pi; |
214 | 214 |
IntVector &_pred; |
215 | 215 |
|
216 | 216 |
IntVector _proc_nodes; |
217 | 217 |
CostVector _dist; |
218 | 218 |
|
219 | 219 |
public: |
220 | 220 |
|
221 | 221 |
ResidualDijkstra(CapacityScaling& cs) : |
222 | 222 |
_node_num(cs._node_num), _geq(cs._sum_supply < 0), |
223 | 223 |
_first_out(cs._first_out), _target(cs._target), _cost(cs._cost), |
224 | 224 |
_res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi), |
225 | 225 |
_pred(cs._pred), _dist(cs._node_num) |
226 | 226 |
{} |
227 | 227 |
|
228 | 228 |
int run(int s, Value delta = 1) { |
229 | 229 |
RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP); |
230 | 230 |
Heap heap(heap_cross_ref); |
231 | 231 |
heap.push(s, 0); |
232 | 232 |
_pred[s] = -1; |
233 | 233 |
_proc_nodes.clear(); |
234 | 234 |
|
235 | 235 |
// Process nodes |
236 | 236 |
while (!heap.empty() && _excess[heap.top()] > -delta) { |
237 | 237 |
int u = heap.top(), v; |
238 | 238 |
Cost d = heap.prio() + _pi[u], dn; |
239 | 239 |
_dist[u] = heap.prio(); |
240 | 240 |
_proc_nodes.push_back(u); |
241 | 241 |
heap.pop(); |
242 | 242 |
|
243 | 243 |
// Traverse outgoing residual arcs |
244 | 244 |
int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1; |
245 | 245 |
for (int a = _first_out[u]; a != last_out; ++a) { |
246 | 246 |
if (_res_cap[a] < delta) continue; |
247 | 247 |
v = _target[a]; |
248 | 248 |
switch (heap.state(v)) { |
249 | 249 |
case Heap::PRE_HEAP: |
250 | 250 |
heap.push(v, d + _cost[a] - _pi[v]); |
251 | 251 |
_pred[v] = a; |
252 | 252 |
break; |
253 | 253 |
case Heap::IN_HEAP: |
254 | 254 |
dn = d + _cost[a] - _pi[v]; |
255 | 255 |
if (dn < heap[v]) { |
256 | 256 |
heap.decrease(v, dn); |
257 | 257 |
_pred[v] = a; |
258 | 258 |
} |
259 | 259 |
break; |
260 | 260 |
case Heap::POST_HEAP: |
261 | 261 |
break; |
262 | 262 |
} |
263 | 263 |
} |
264 | 264 |
} |
265 | 265 |
if (heap.empty()) return -1; |
266 | 266 |
|
267 | 267 |
// Update potentials of processed nodes |
268 | 268 |
int t = heap.top(); |
269 | 269 |
Cost dt = heap.prio(); |
270 | 270 |
for (int i = 0; i < int(_proc_nodes.size()); ++i) { |
271 | 271 |
_pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt; |
272 | 272 |
} |
273 | 273 |
|
274 | 274 |
return t; |
275 | 275 |
} |
276 | 276 |
|
277 | 277 |
}; //class ResidualDijkstra |
278 | 278 |
|
279 | 279 |
public: |
280 | 280 |
|
281 | 281 |
/// \name Named Template Parameters |
282 | 282 |
/// @{ |
283 | 283 |
|
284 | 284 |
template <typename T> |
285 | 285 |
struct SetHeapTraits : public Traits { |
286 | 286 |
typedef T Heap; |
287 | 287 |
}; |
288 | 288 |
|
289 | 289 |
/// \brief \ref named-templ-param "Named parameter" for setting |
290 | 290 |
/// \c Heap type. |
291 | 291 |
/// |
292 | 292 |
/// \ref named-templ-param "Named parameter" for setting \c Heap |
293 | 293 |
/// type, which is used for internal Dijkstra computations. |
294 | 294 |
/// It must conform to the \ref lemon::concepts::Heap "Heap" concept, |
295 | 295 |
/// its priority type must be \c Cost and its cross reference type |
296 | 296 |
/// must be \ref RangeMap "RangeMap<int>". |
297 | 297 |
template <typename T> |
298 | 298 |
struct SetHeap |
299 | 299 |
: public CapacityScaling<GR, V, C, SetHeapTraits<T> > { |
300 | 300 |
typedef CapacityScaling<GR, V, C, SetHeapTraits<T> > Create; |
301 | 301 |
}; |
302 | 302 |
|
303 | 303 |
/// @} |
304 | 304 |
|
305 | 305 |
protected: |
306 | 306 |
|
307 | 307 |
CapacityScaling() {} |
308 | 308 |
|
309 | 309 |
public: |
310 | 310 |
|
311 | 311 |
/// \brief Constructor. |
312 | 312 |
/// |
313 | 313 |
/// The constructor of the class. |
314 | 314 |
/// |
315 | 315 |
/// \param graph The digraph the algorithm runs on. |
316 | 316 |
CapacityScaling(const GR& graph) : |
317 | 317 |
_graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph), |
318 | 318 |
INF(std::numeric_limits<Value>::has_infinity ? |
319 | 319 |
std::numeric_limits<Value>::infinity() : |
320 | 320 |
std::numeric_limits<Value>::max()) |
321 | 321 |
{ |
322 | 322 |
// Check the number types |
323 | 323 |
LEMON_ASSERT(std::numeric_limits<Value>::is_signed, |
324 | 324 |
"The flow type of CapacityScaling must be signed"); |
325 | 325 |
LEMON_ASSERT(std::numeric_limits<Cost>::is_signed, |
326 | 326 |
"The cost type of CapacityScaling must be signed"); |
327 | 327 |
|
328 | 328 |
// Reset data structures |
329 | 329 |
reset(); |
330 | 330 |
} |
331 | 331 |
|
332 | 332 |
/// \name Parameters |
333 | 333 |
/// The parameters of the algorithm can be specified using these |
334 | 334 |
/// functions. |
335 | 335 |
|
336 | 336 |
/// @{ |
337 | 337 |
|
338 | 338 |
/// \brief Set the lower bounds on the arcs. |
339 | 339 |
/// |
340 | 340 |
/// This function sets the lower bounds on the arcs. |
341 | 341 |
/// If it is not used before calling \ref run(), the lower bounds |
342 | 342 |
/// will be set to zero on all arcs. |
343 | 343 |
/// |
344 | 344 |
/// \param map An arc map storing the lower bounds. |
345 | 345 |
/// Its \c Value type must be convertible to the \c Value type |
346 | 346 |
/// of the algorithm. |
347 | 347 |
/// |
348 | 348 |
/// \return <tt>(*this)</tt> |
349 | 349 |
template <typename LowerMap> |
350 | 350 |
CapacityScaling& lowerMap(const LowerMap& map) { |
351 | 351 |
_have_lower = true; |
352 | 352 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
353 | 353 |
_lower[_arc_idf[a]] = map[a]; |
354 | 354 |
_lower[_arc_idb[a]] = map[a]; |
355 | 355 |
} |
356 | 356 |
return *this; |
357 | 357 |
} |
358 | 358 |
|
359 | 359 |
/// \brief Set the upper bounds (capacities) on the arcs. |
360 | 360 |
/// |
361 | 361 |
/// This function sets the upper bounds (capacities) on the arcs. |
362 | 362 |
/// If it is not used before calling \ref run(), the upper bounds |
363 | 363 |
/// will be set to \ref INF on all arcs (i.e. the flow value will be |
364 | 364 |
/// unbounded from above). |
365 | 365 |
/// |
366 | 366 |
/// \param map An arc map storing the upper bounds. |
367 | 367 |
/// Its \c Value type must be convertible to the \c Value type |
368 | 368 |
/// of the algorithm. |
369 | 369 |
/// |
370 | 370 |
/// \return <tt>(*this)</tt> |
371 | 371 |
template<typename UpperMap> |
372 | 372 |
CapacityScaling& upperMap(const UpperMap& map) { |
373 | 373 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
374 | 374 |
_upper[_arc_idf[a]] = map[a]; |
375 | 375 |
} |
376 | 376 |
return *this; |
377 | 377 |
} |
378 | 378 |
|
379 | 379 |
/// \brief Set the costs of the arcs. |
380 | 380 |
/// |
381 | 381 |
/// This function sets the costs of the arcs. |
382 | 382 |
/// If it is not used before calling \ref run(), the costs |
383 | 383 |
/// will be set to \c 1 on all arcs. |
384 | 384 |
/// |
385 | 385 |
/// \param map An arc map storing the costs. |
386 | 386 |
/// Its \c Value type must be convertible to the \c Cost type |
387 | 387 |
/// of the algorithm. |
388 | 388 |
/// |
389 | 389 |
/// \return <tt>(*this)</tt> |
390 | 390 |
template<typename CostMap> |
391 | 391 |
CapacityScaling& costMap(const CostMap& map) { |
392 | 392 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
393 | 393 |
_cost[_arc_idf[a]] = map[a]; |
394 | 394 |
_cost[_arc_idb[a]] = -map[a]; |
395 | 395 |
} |
396 | 396 |
return *this; |
397 | 397 |
} |
398 | 398 |
|
399 | 399 |
/// \brief Set the supply values of the nodes. |
400 | 400 |
/// |
401 | 401 |
/// This function sets the supply values of the nodes. |
402 | 402 |
/// If neither this function nor \ref stSupply() is used before |
403 | 403 |
/// calling \ref run(), the supply of each node will be set to zero. |
404 | 404 |
/// |
405 | 405 |
/// \param map A node map storing the supply values. |
406 | 406 |
/// Its \c Value type must be convertible to the \c Value type |
407 | 407 |
/// of the algorithm. |
408 | 408 |
/// |
409 | 409 |
/// \return <tt>(*this)</tt> |
410 | 410 |
template<typename SupplyMap> |
411 | 411 |
CapacityScaling& supplyMap(const SupplyMap& map) { |
412 | 412 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
413 | 413 |
_supply[_node_id[n]] = map[n]; |
414 | 414 |
} |
415 | 415 |
return *this; |
416 | 416 |
} |
417 | 417 |
|
418 | 418 |
/// \brief Set single source and target nodes and a supply value. |
419 | 419 |
/// |
420 | 420 |
/// This function sets a single source node and a single target node |
421 | 421 |
/// and the required flow value. |
422 | 422 |
/// If neither this function nor \ref supplyMap() is used before |
423 | 423 |
/// calling \ref run(), the supply of each node will be set to zero. |
424 | 424 |
/// |
425 | 425 |
/// Using this function has the same effect as using \ref supplyMap() |
426 |
/// with |
|
426 |
/// with a map in which \c k is assigned to \c s, \c -k is |
|
427 | 427 |
/// assigned to \c t and all other nodes have zero supply value. |
428 | 428 |
/// |
429 | 429 |
/// \param s The source node. |
430 | 430 |
/// \param t The target node. |
431 | 431 |
/// \param k The required amount of flow from node \c s to node \c t |
432 | 432 |
/// (i.e. the supply of \c s and the demand of \c t). |
433 | 433 |
/// |
434 | 434 |
/// \return <tt>(*this)</tt> |
435 | 435 |
CapacityScaling& stSupply(const Node& s, const Node& t, Value k) { |
436 | 436 |
for (int i = 0; i != _node_num; ++i) { |
437 | 437 |
_supply[i] = 0; |
438 | 438 |
} |
439 | 439 |
_supply[_node_id[s]] = k; |
440 | 440 |
_supply[_node_id[t]] = -k; |
441 | 441 |
return *this; |
442 | 442 |
} |
443 | 443 |
|
444 | 444 |
/// @} |
445 | 445 |
|
446 | 446 |
/// \name Execution control |
447 | 447 |
/// The algorithm can be executed using \ref run(). |
448 | 448 |
|
449 | 449 |
/// @{ |
450 | 450 |
|
451 | 451 |
/// \brief Run the algorithm. |
452 | 452 |
/// |
453 | 453 |
/// This function runs the algorithm. |
454 | 454 |
/// The paramters can be specified using functions \ref lowerMap(), |
455 | 455 |
/// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). |
456 | 456 |
/// For example, |
457 | 457 |
/// \code |
458 | 458 |
/// CapacityScaling<ListDigraph> cs(graph); |
459 | 459 |
/// cs.lowerMap(lower).upperMap(upper).costMap(cost) |
460 | 460 |
/// .supplyMap(sup).run(); |
461 | 461 |
/// \endcode |
462 | 462 |
/// |
463 | 463 |
/// This function can be called more than once. All the given parameters |
464 | 464 |
/// are kept for the next call, unless \ref resetParams() or \ref reset() |
465 | 465 |
/// is used, thus only the modified parameters have to be set again. |
466 | 466 |
/// If the underlying digraph was also modified after the construction |
467 | 467 |
/// of the class (or the last \ref reset() call), then the \ref reset() |
468 | 468 |
/// function must be called. |
469 | 469 |
/// |
470 | 470 |
/// \param factor The capacity scaling factor. It must be larger than |
471 | 471 |
/// one to use scaling. If it is less or equal to one, then scaling |
472 | 472 |
/// will be disabled. |
473 | 473 |
/// |
474 | 474 |
/// \return \c INFEASIBLE if no feasible flow exists, |
475 | 475 |
/// \n \c OPTIMAL if the problem has optimal solution |
476 | 476 |
/// (i.e. it is feasible and bounded), and the algorithm has found |
477 | 477 |
/// optimal flow and node potentials (primal and dual solutions), |
478 | 478 |
/// \n \c UNBOUNDED if the digraph contains an arc of negative cost |
479 | 479 |
/// and infinite upper bound. It means that the objective function |
480 | 480 |
/// is unbounded on that arc, however, note that it could actually be |
481 | 481 |
/// bounded over the feasible flows, but this algroithm cannot handle |
482 | 482 |
/// these cases. |
483 | 483 |
/// |
484 | 484 |
/// \see ProblemType |
485 | 485 |
/// \see resetParams(), reset() |
486 | 486 |
ProblemType run(int factor = 4) { |
487 | 487 |
_factor = factor; |
488 | 488 |
ProblemType pt = init(); |
489 | 489 |
if (pt != OPTIMAL) return pt; |
490 | 490 |
return start(); |
491 | 491 |
} |
492 | 492 |
|
493 | 493 |
/// \brief Reset all the parameters that have been given before. |
494 | 494 |
/// |
495 | 495 |
/// This function resets all the paramaters that have been given |
496 | 496 |
/// before using functions \ref lowerMap(), \ref upperMap(), |
497 | 497 |
/// \ref costMap(), \ref supplyMap(), \ref stSupply(). |
498 | 498 |
/// |
499 | 499 |
/// It is useful for multiple \ref run() calls. Basically, all the given |
500 | 500 |
/// parameters are kept for the next \ref run() call, unless |
501 | 501 |
/// \ref resetParams() or \ref reset() is used. |
502 | 502 |
/// If the underlying digraph was also modified after the construction |
503 | 503 |
/// of the class or the last \ref reset() call, then the \ref reset() |
504 | 504 |
/// function must be used, otherwise \ref resetParams() is sufficient. |
505 | 505 |
/// |
506 | 506 |
/// For example, |
507 | 507 |
/// \code |
508 | 508 |
/// CapacityScaling<ListDigraph> cs(graph); |
509 | 509 |
/// |
510 | 510 |
/// // First run |
511 | 511 |
/// cs.lowerMap(lower).upperMap(upper).costMap(cost) |
512 | 512 |
/// .supplyMap(sup).run(); |
513 | 513 |
/// |
514 | 514 |
/// // Run again with modified cost map (resetParams() is not called, |
515 | 515 |
/// // so only the cost map have to be set again) |
516 | 516 |
/// cost[e] += 100; |
517 | 517 |
/// cs.costMap(cost).run(); |
518 | 518 |
/// |
519 | 519 |
/// // Run again from scratch using resetParams() |
520 | 520 |
/// // (the lower bounds will be set to zero on all arcs) |
521 | 521 |
/// cs.resetParams(); |
522 | 522 |
/// cs.upperMap(capacity).costMap(cost) |
523 | 523 |
/// .supplyMap(sup).run(); |
524 | 524 |
/// \endcode |
525 | 525 |
/// |
526 | 526 |
/// \return <tt>(*this)</tt> |
527 | 527 |
/// |
528 | 528 |
/// \see reset(), run() |
529 | 529 |
CapacityScaling& resetParams() { |
530 | 530 |
for (int i = 0; i != _node_num; ++i) { |
531 | 531 |
_supply[i] = 0; |
532 | 532 |
} |
533 | 533 |
for (int j = 0; j != _res_arc_num; ++j) { |
534 | 534 |
_lower[j] = 0; |
535 | 535 |
_upper[j] = INF; |
536 | 536 |
_cost[j] = _forward[j] ? 1 : -1; |
537 | 537 |
} |
538 | 538 |
_have_lower = false; |
539 | 539 |
return *this; |
540 | 540 |
} |
541 | 541 |
|
542 | 542 |
/// \brief Reset the internal data structures and all the parameters |
543 | 543 |
/// that have been given before. |
544 | 544 |
/// |
545 | 545 |
/// This function resets the internal data structures and all the |
546 | 546 |
/// paramaters that have been given before using functions \ref lowerMap(), |
547 | 547 |
/// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). |
548 | 548 |
/// |
549 | 549 |
/// It is useful for multiple \ref run() calls. Basically, all the given |
550 | 550 |
/// parameters are kept for the next \ref run() call, unless |
551 | 551 |
/// \ref resetParams() or \ref reset() is used. |
552 | 552 |
/// If the underlying digraph was also modified after the construction |
553 | 553 |
/// of the class or the last \ref reset() call, then the \ref reset() |
554 | 554 |
/// function must be used, otherwise \ref resetParams() is sufficient. |
555 | 555 |
/// |
556 | 556 |
/// See \ref resetParams() for examples. |
557 | 557 |
/// |
558 | 558 |
/// \return <tt>(*this)</tt> |
559 | 559 |
/// |
560 | 560 |
/// \see resetParams(), run() |
561 | 561 |
CapacityScaling& reset() { |
562 | 562 |
// Resize vectors |
563 | 563 |
_node_num = countNodes(_graph); |
564 | 564 |
_arc_num = countArcs(_graph); |
565 | 565 |
_res_arc_num = 2 * (_arc_num + _node_num); |
566 | 566 |
_root = _node_num; |
567 | 567 |
++_node_num; |
568 | 568 |
|
569 | 569 |
_first_out.resize(_node_num + 1); |
570 | 570 |
_forward.resize(_res_arc_num); |
571 | 571 |
_source.resize(_res_arc_num); |
572 | 572 |
_target.resize(_res_arc_num); |
573 | 573 |
_reverse.resize(_res_arc_num); |
574 | 574 |
|
575 | 575 |
_lower.resize(_res_arc_num); |
576 | 576 |
_upper.resize(_res_arc_num); |
577 | 577 |
_cost.resize(_res_arc_num); |
578 | 578 |
_supply.resize(_node_num); |
579 | 579 |
|
580 | 580 |
_res_cap.resize(_res_arc_num); |
581 | 581 |
_pi.resize(_node_num); |
582 | 582 |
_excess.resize(_node_num); |
583 | 583 |
_pred.resize(_node_num); |
584 | 584 |
|
585 | 585 |
// Copy the graph |
586 | 586 |
int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1; |
587 | 587 |
for (NodeIt n(_graph); n != INVALID; ++n, ++i) { |
588 | 588 |
_node_id[n] = i; |
589 | 589 |
} |
590 | 590 |
i = 0; |
591 | 591 |
for (NodeIt n(_graph); n != INVALID; ++n, ++i) { |
592 | 592 |
_first_out[i] = j; |
593 | 593 |
for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) { |
594 | 594 |
_arc_idf[a] = j; |
595 | 595 |
_forward[j] = true; |
596 | 596 |
_source[j] = i; |
597 | 597 |
_target[j] = _node_id[_graph.runningNode(a)]; |
598 | 598 |
} |
599 | 599 |
for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) { |
600 | 600 |
_arc_idb[a] = j; |
601 | 601 |
_forward[j] = false; |
602 | 602 |
_source[j] = i; |
603 | 603 |
_target[j] = _node_id[_graph.runningNode(a)]; |
604 | 604 |
} |
605 | 605 |
_forward[j] = false; |
606 | 606 |
_source[j] = i; |
607 | 607 |
_target[j] = _root; |
608 | 608 |
_reverse[j] = k; |
609 | 609 |
_forward[k] = true; |
610 | 610 |
_source[k] = _root; |
611 | 611 |
_target[k] = i; |
612 | 612 |
_reverse[k] = j; |
613 | 613 |
++j; ++k; |
614 | 614 |
} |
615 | 615 |
_first_out[i] = j; |
616 | 616 |
_first_out[_node_num] = k; |
617 | 617 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
618 | 618 |
int fi = _arc_idf[a]; |
619 | 619 |
int bi = _arc_idb[a]; |
620 | 620 |
_reverse[fi] = bi; |
621 | 621 |
_reverse[bi] = fi; |
622 | 622 |
} |
623 | 623 |
|
624 | 624 |
// Reset parameters |
625 | 625 |
resetParams(); |
626 | 626 |
return *this; |
627 | 627 |
} |
628 | 628 |
|
629 | 629 |
/// @} |
630 | 630 |
|
631 | 631 |
/// \name Query Functions |
632 | 632 |
/// The results of the algorithm can be obtained using these |
633 | 633 |
/// functions.\n |
634 | 634 |
/// The \ref run() function must be called before using them. |
635 | 635 |
|
636 | 636 |
/// @{ |
637 | 637 |
|
638 | 638 |
/// \brief Return the total cost of the found flow. |
639 | 639 |
/// |
640 | 640 |
/// This function returns the total cost of the found flow. |
641 | 641 |
/// Its complexity is O(e). |
642 | 642 |
/// |
643 | 643 |
/// \note The return type of the function can be specified as a |
644 | 644 |
/// template parameter. For example, |
645 | 645 |
/// \code |
646 | 646 |
/// cs.totalCost<double>(); |
647 | 647 |
/// \endcode |
648 | 648 |
/// It is useful if the total cost cannot be stored in the \c Cost |
649 | 649 |
/// type of the algorithm, which is the default return type of the |
650 | 650 |
/// function. |
651 | 651 |
/// |
652 | 652 |
/// \pre \ref run() must be called before using this function. |
653 | 653 |
template <typename Number> |
654 | 654 |
Number totalCost() const { |
655 | 655 |
Number c = 0; |
656 | 656 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
657 | 657 |
int i = _arc_idb[a]; |
658 | 658 |
c += static_cast<Number>(_res_cap[i]) * |
659 | 659 |
(-static_cast<Number>(_cost[i])); |
660 | 660 |
} |
661 | 661 |
return c; |
662 | 662 |
} |
663 | 663 |
|
664 | 664 |
#ifndef DOXYGEN |
665 | 665 |
Cost totalCost() const { |
666 | 666 |
return totalCost<Cost>(); |
667 | 667 |
} |
668 | 668 |
#endif |
669 | 669 |
|
670 | 670 |
/// \brief Return the flow on the given arc. |
671 | 671 |
/// |
672 | 672 |
/// This function returns the flow on the given arc. |
673 | 673 |
/// |
674 | 674 |
/// \pre \ref run() must be called before using this function. |
675 | 675 |
Value flow(const Arc& a) const { |
676 | 676 |
return _res_cap[_arc_idb[a]]; |
677 | 677 |
} |
678 | 678 |
|
679 | 679 |
/// \brief Return the flow map (the primal solution). |
680 | 680 |
/// |
681 | 681 |
/// This function copies the flow value on each arc into the given |
682 | 682 |
/// map. The \c Value type of the algorithm must be convertible to |
683 | 683 |
/// the \c Value type of the map. |
684 | 684 |
/// |
685 | 685 |
/// \pre \ref run() must be called before using this function. |
686 | 686 |
template <typename FlowMap> |
687 | 687 |
void flowMap(FlowMap &map) const { |
688 | 688 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
689 | 689 |
map.set(a, _res_cap[_arc_idb[a]]); |
690 | 690 |
} |
691 | 691 |
} |
692 | 692 |
|
693 | 693 |
/// \brief Return the potential (dual value) of the given node. |
694 | 694 |
/// |
695 | 695 |
/// This function returns the potential (dual value) of the |
696 | 696 |
/// given node. |
697 | 697 |
/// |
698 | 698 |
/// \pre \ref run() must be called before using this function. |
699 | 699 |
Cost potential(const Node& n) const { |
700 | 700 |
return _pi[_node_id[n]]; |
701 | 701 |
} |
702 | 702 |
|
703 | 703 |
/// \brief Return the potential map (the dual solution). |
704 | 704 |
/// |
705 | 705 |
/// This function copies the potential (dual value) of each node |
706 | 706 |
/// into the given map. |
707 | 707 |
/// The \c Cost type of the algorithm must be convertible to the |
708 | 708 |
/// \c Value type of the map. |
709 | 709 |
/// |
710 | 710 |
/// \pre \ref run() must be called before using this function. |
711 | 711 |
template <typename PotentialMap> |
712 | 712 |
void potentialMap(PotentialMap &map) const { |
713 | 713 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
714 | 714 |
map.set(n, _pi[_node_id[n]]); |
715 | 715 |
} |
716 | 716 |
} |
717 | 717 |
|
718 | 718 |
/// @} |
719 | 719 |
|
720 | 720 |
private: |
721 | 721 |
|
722 | 722 |
// Initialize the algorithm |
723 | 723 |
ProblemType init() { |
724 | 724 |
if (_node_num <= 1) return INFEASIBLE; |
725 | 725 |
|
726 | 726 |
// Check the sum of supply values |
727 | 727 |
_sum_supply = 0; |
728 | 728 |
for (int i = 0; i != _root; ++i) { |
729 | 729 |
_sum_supply += _supply[i]; |
730 | 730 |
} |
731 | 731 |
if (_sum_supply > 0) return INFEASIBLE; |
732 | 732 |
|
733 | 733 |
// Initialize vectors |
734 | 734 |
for (int i = 0; i != _root; ++i) { |
735 | 735 |
_pi[i] = 0; |
736 | 736 |
_excess[i] = _supply[i]; |
737 | 737 |
} |
738 | 738 |
|
739 | 739 |
// Remove non-zero lower bounds |
740 | 740 |
const Value MAX = std::numeric_limits<Value>::max(); |
741 | 741 |
int last_out; |
742 | 742 |
if (_have_lower) { |
743 | 743 |
for (int i = 0; i != _root; ++i) { |
744 | 744 |
last_out = _first_out[i+1]; |
745 | 745 |
for (int j = _first_out[i]; j != last_out; ++j) { |
746 | 746 |
if (_forward[j]) { |
747 | 747 |
Value c = _lower[j]; |
748 | 748 |
if (c >= 0) { |
749 | 749 |
_res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF; |
750 | 750 |
} else { |
751 | 751 |
_res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF; |
752 | 752 |
} |
753 | 753 |
_excess[i] -= c; |
754 | 754 |
_excess[_target[j]] += c; |
755 | 755 |
} else { |
756 | 756 |
_res_cap[j] = 0; |
757 | 757 |
} |
758 | 758 |
} |
759 | 759 |
} |
760 | 760 |
} else { |
761 | 761 |
for (int j = 0; j != _res_arc_num; ++j) { |
762 | 762 |
_res_cap[j] = _forward[j] ? _upper[j] : 0; |
763 | 763 |
} |
764 | 764 |
} |
765 | 765 |
|
766 | 766 |
// Handle negative costs |
767 | 767 |
for (int i = 0; i != _root; ++i) { |
768 | 768 |
last_out = _first_out[i+1] - 1; |
769 | 769 |
for (int j = _first_out[i]; j != last_out; ++j) { |
770 | 770 |
Value rc = _res_cap[j]; |
771 | 771 |
if (_cost[j] < 0 && rc > 0) { |
772 | 772 |
if (rc >= MAX) return UNBOUNDED; |
773 | 773 |
_excess[i] -= rc; |
774 | 774 |
_excess[_target[j]] += rc; |
775 | 775 |
_res_cap[j] = 0; |
776 | 776 |
_res_cap[_reverse[j]] += rc; |
777 | 777 |
} |
778 | 778 |
} |
779 | 779 |
} |
780 | 780 |
|
781 | 781 |
// Handle GEQ supply type |
782 | 782 |
if (_sum_supply < 0) { |
783 | 783 |
_pi[_root] = 0; |
784 | 784 |
_excess[_root] = -_sum_supply; |
785 | 785 |
for (int a = _first_out[_root]; a != _res_arc_num; ++a) { |
786 | 786 |
int ra = _reverse[a]; |
787 | 787 |
_res_cap[a] = -_sum_supply + 1; |
788 | 788 |
_res_cap[ra] = 0; |
789 | 789 |
_cost[a] = 0; |
790 | 790 |
_cost[ra] = 0; |
791 | 791 |
} |
792 | 792 |
} else { |
793 | 793 |
_pi[_root] = 0; |
794 | 794 |
_excess[_root] = 0; |
795 | 795 |
for (int a = _first_out[_root]; a != _res_arc_num; ++a) { |
796 | 796 |
int ra = _reverse[a]; |
797 | 797 |
_res_cap[a] = 1; |
798 | 798 |
_res_cap[ra] = 0; |
799 | 799 |
_cost[a] = 0; |
800 | 800 |
_cost[ra] = 0; |
801 | 801 |
} |
802 | 802 |
} |
803 | 803 |
|
804 | 804 |
// Initialize delta value |
805 | 805 |
if (_factor > 1) { |
806 | 806 |
// With scaling |
807 | 807 |
Value max_sup = 0, max_dem = 0, max_cap = 0; |
808 | 808 |
for (int i = 0; i != _root; ++i) { |
809 | 809 |
Value ex = _excess[i]; |
810 | 810 |
if ( ex > max_sup) max_sup = ex; |
811 | 811 |
if (-ex > max_dem) max_dem = -ex; |
812 | 812 |
int last_out = _first_out[i+1] - 1; |
813 | 813 |
for (int j = _first_out[i]; j != last_out; ++j) { |
814 | 814 |
if (_res_cap[j] > max_cap) max_cap = _res_cap[j]; |
815 | 815 |
} |
816 | 816 |
} |
817 | 817 |
max_sup = std::min(std::min(max_sup, max_dem), max_cap); |
818 | 818 |
for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ; |
819 | 819 |
} else { |
820 | 820 |
// Without scaling |
821 | 821 |
_delta = 1; |
822 | 822 |
} |
823 | 823 |
|
824 | 824 |
return OPTIMAL; |
825 | 825 |
} |
826 | 826 |
|
827 | 827 |
ProblemType start() { |
828 | 828 |
// Execute the algorithm |
829 | 829 |
ProblemType pt; |
830 | 830 |
if (_delta > 1) |
831 | 831 |
pt = startWithScaling(); |
832 | 832 |
else |
833 | 833 |
pt = startWithoutScaling(); |
834 | 834 |
|
835 | 835 |
// Handle non-zero lower bounds |
836 | 836 |
if (_have_lower) { |
837 | 837 |
int limit = _first_out[_root]; |
838 | 838 |
for (int j = 0; j != limit; ++j) { |
839 | 839 |
if (!_forward[j]) _res_cap[j] += _lower[j]; |
840 | 840 |
} |
841 | 841 |
} |
842 | 842 |
|
843 | 843 |
// Shift potentials if necessary |
844 | 844 |
Cost pr = _pi[_root]; |
845 | 845 |
if (_sum_supply < 0 || pr > 0) { |
846 | 846 |
for (int i = 0; i != _node_num; ++i) { |
847 | 847 |
_pi[i] -= pr; |
848 | 848 |
} |
849 | 849 |
} |
850 | 850 |
|
851 | 851 |
return pt; |
852 | 852 |
} |
853 | 853 |
|
854 | 854 |
// Execute the capacity scaling algorithm |
855 | 855 |
ProblemType startWithScaling() { |
856 | 856 |
// Perform capacity scaling phases |
857 | 857 |
int s, t; |
858 | 858 |
ResidualDijkstra _dijkstra(*this); |
859 | 859 |
while (true) { |
860 | 860 |
// Saturate all arcs not satisfying the optimality condition |
861 | 861 |
int last_out; |
862 | 862 |
for (int u = 0; u != _node_num; ++u) { |
863 | 863 |
last_out = _sum_supply < 0 ? |
864 | 864 |
_first_out[u+1] : _first_out[u+1] - 1; |
865 | 865 |
for (int a = _first_out[u]; a != last_out; ++a) { |
866 | 866 |
int v = _target[a]; |
867 | 867 |
Cost c = _cost[a] + _pi[u] - _pi[v]; |
868 | 868 |
Value rc = _res_cap[a]; |
869 | 869 |
if (c < 0 && rc >= _delta) { |
870 | 870 |
_excess[u] -= rc; |
871 | 871 |
_excess[v] += rc; |
872 | 872 |
_res_cap[a] = 0; |
873 | 873 |
_res_cap[_reverse[a]] += rc; |
874 | 874 |
} |
875 | 875 |
} |
876 | 876 |
} |
877 | 877 |
|
878 | 878 |
// Find excess nodes and deficit nodes |
879 | 879 |
_excess_nodes.clear(); |
880 | 880 |
_deficit_nodes.clear(); |
881 | 881 |
for (int u = 0; u != _node_num; ++u) { |
882 | 882 |
Value ex = _excess[u]; |
883 | 883 |
if (ex >= _delta) _excess_nodes.push_back(u); |
884 | 884 |
if (ex <= -_delta) _deficit_nodes.push_back(u); |
885 | 885 |
} |
886 | 886 |
int next_node = 0, next_def_node = 0; |
887 | 887 |
|
888 | 888 |
// Find augmenting shortest paths |
889 | 889 |
while (next_node < int(_excess_nodes.size())) { |
890 | 890 |
// Check deficit nodes |
891 | 891 |
if (_delta > 1) { |
892 | 892 |
bool delta_deficit = false; |
893 | 893 |
for ( ; next_def_node < int(_deficit_nodes.size()); |
894 | 894 |
++next_def_node ) { |
895 | 895 |
if (_excess[_deficit_nodes[next_def_node]] <= -_delta) { |
896 | 896 |
delta_deficit = true; |
897 | 897 |
break; |
898 | 898 |
} |
899 | 899 |
} |
900 | 900 |
if (!delta_deficit) break; |
901 | 901 |
} |
902 | 902 |
|
903 | 903 |
// Run Dijkstra in the residual network |
904 | 904 |
s = _excess_nodes[next_node]; |
905 | 905 |
if ((t = _dijkstra.run(s, _delta)) == -1) { |
906 | 906 |
if (_delta > 1) { |
907 | 907 |
++next_node; |
908 | 908 |
continue; |
909 | 909 |
} |
910 | 910 |
return INFEASIBLE; |
911 | 911 |
} |
912 | 912 |
|
913 | 913 |
// Augment along a shortest path from s to t |
914 | 914 |
Value d = std::min(_excess[s], -_excess[t]); |
915 | 915 |
int u = t; |
916 | 916 |
int a; |
917 | 917 |
if (d > _delta) { |
918 | 918 |
while ((a = _pred[u]) != -1) { |
919 | 919 |
if (_res_cap[a] < d) d = _res_cap[a]; |
920 | 920 |
u = _source[a]; |
921 | 921 |
} |
922 | 922 |
} |
923 | 923 |
u = t; |
924 | 924 |
while ((a = _pred[u]) != -1) { |
925 | 925 |
_res_cap[a] -= d; |
926 | 926 |
_res_cap[_reverse[a]] += d; |
927 | 927 |
u = _source[a]; |
928 | 928 |
} |
929 | 929 |
_excess[s] -= d; |
930 | 930 |
_excess[t] += d; |
931 | 931 |
|
932 | 932 |
if (_excess[s] < _delta) ++next_node; |
933 | 933 |
} |
934 | 934 |
|
935 | 935 |
if (_delta == 1) break; |
936 | 936 |
_delta = _delta <= _factor ? 1 : _delta / _factor; |
937 | 937 |
} |
938 | 938 |
|
939 | 939 |
return OPTIMAL; |
940 | 940 |
} |
941 | 941 |
|
942 | 942 |
// Execute the successive shortest path algorithm |
943 | 943 |
ProblemType startWithoutScaling() { |
944 | 944 |
// Find excess nodes |
945 | 945 |
_excess_nodes.clear(); |
946 | 946 |
for (int i = 0; i != _node_num; ++i) { |
947 | 947 |
if (_excess[i] > 0) _excess_nodes.push_back(i); |
948 | 948 |
} |
949 | 949 |
if (_excess_nodes.size() == 0) return OPTIMAL; |
950 | 950 |
int next_node = 0; |
951 | 951 |
|
952 | 952 |
// Find shortest paths |
953 | 953 |
int s, t; |
954 | 954 |
ResidualDijkstra _dijkstra(*this); |
955 | 955 |
while ( _excess[_excess_nodes[next_node]] > 0 || |
956 | 956 |
++next_node < int(_excess_nodes.size()) ) |
957 | 957 |
{ |
958 | 958 |
// Run Dijkstra in the residual network |
959 | 959 |
s = _excess_nodes[next_node]; |
960 | 960 |
if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE; |
961 | 961 |
|
962 | 962 |
// Augment along a shortest path from s to t |
963 | 963 |
Value d = std::min(_excess[s], -_excess[t]); |
964 | 964 |
int u = t; |
965 | 965 |
int a; |
966 | 966 |
if (d > 1) { |
967 | 967 |
while ((a = _pred[u]) != -1) { |
968 | 968 |
if (_res_cap[a] < d) d = _res_cap[a]; |
969 | 969 |
u = _source[a]; |
970 | 970 |
} |
971 | 971 |
} |
972 | 972 |
u = t; |
973 | 973 |
while ((a = _pred[u]) != -1) { |
974 | 974 |
_res_cap[a] -= d; |
975 | 975 |
_res_cap[_reverse[a]] += d; |
976 | 976 |
u = _source[a]; |
977 | 977 |
} |
978 | 978 |
_excess[s] -= d; |
979 | 979 |
_excess[t] += d; |
980 | 980 |
} |
981 | 981 |
|
982 | 982 |
return OPTIMAL; |
983 | 983 |
} |
984 | 984 |
|
985 | 985 |
}; //class CapacityScaling |
986 | 986 |
|
987 | 987 |
///@} |
988 | 988 |
|
989 | 989 |
} //namespace lemon |
990 | 990 |
|
991 | 991 |
#endif //LEMON_CAPACITY_SCALING_H |
1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2010 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
#ifndef LEMON_CORE_H |
20 | 20 |
#define LEMON_CORE_H |
21 | 21 |
|
22 | 22 |
#include <vector> |
23 | 23 |
#include <algorithm> |
24 | 24 |
|
25 | 25 |
#include <lemon/config.h> |
26 | 26 |
#include <lemon/bits/enable_if.h> |
27 | 27 |
#include <lemon/bits/traits.h> |
28 | 28 |
#include <lemon/assert.h> |
29 | 29 |
|
30 | 30 |
// Disable the following warnings when compiling with MSVC: |
31 | 31 |
// C4250: 'class1' : inherits 'class2::member' via dominance |
32 | 32 |
// C4355: 'this' : used in base member initializer list |
33 | 33 |
// C4503: 'function' : decorated name length exceeded, name was truncated |
34 | 34 |
// C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning) |
35 | 35 |
// C4996: 'function': was declared deprecated |
36 | 36 |
#ifdef _MSC_VER |
37 | 37 |
#pragma warning( disable : 4250 4355 4503 4800 4996 ) |
38 | 38 |
#endif |
39 | 39 |
|
40 | 40 |
///\file |
41 | 41 |
///\brief LEMON core utilities. |
42 | 42 |
/// |
43 | 43 |
///This header file contains core utilities for LEMON. |
44 | 44 |
///It is automatically included by all graph types, therefore it usually |
45 | 45 |
///do not have to be included directly. |
46 | 46 |
|
47 | 47 |
namespace lemon { |
48 | 48 |
|
49 | 49 |
/// \brief Dummy type to make it easier to create invalid iterators. |
50 | 50 |
/// |
51 | 51 |
/// Dummy type to make it easier to create invalid iterators. |
52 | 52 |
/// See \ref INVALID for the usage. |
53 | 53 |
struct Invalid { |
54 | 54 |
public: |
55 | 55 |
bool operator==(Invalid) { return true; } |
56 | 56 |
bool operator!=(Invalid) { return false; } |
57 | 57 |
bool operator< (Invalid) { return false; } |
58 | 58 |
}; |
59 | 59 |
|
60 | 60 |
/// \brief Invalid iterators. |
61 | 61 |
/// |
62 | 62 |
/// \ref Invalid is a global type that converts to each iterator |
63 | 63 |
/// in such a way that the value of the target iterator will be invalid. |
64 | 64 |
#ifdef LEMON_ONLY_TEMPLATES |
65 | 65 |
const Invalid INVALID = Invalid(); |
66 | 66 |
#else |
67 | 67 |
extern const Invalid INVALID; |
68 | 68 |
#endif |
69 | 69 |
|
70 | 70 |
/// \addtogroup gutils |
71 | 71 |
/// @{ |
72 | 72 |
|
73 | 73 |
///Create convenience typedefs for the digraph types and iterators |
74 | 74 |
|
75 | 75 |
///This \c \#define creates convenient type definitions for the following |
76 | 76 |
///types of \c Digraph: \c Node, \c NodeIt, \c Arc, \c ArcIt, \c InArcIt, |
77 | 77 |
///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap, |
78 | 78 |
///\c BoolArcMap, \c IntArcMap, \c DoubleArcMap. |
79 | 79 |
/// |
80 | 80 |
///\note If the graph type is a dependent type, ie. the graph type depend |
81 | 81 |
///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS() |
82 | 82 |
///macro. |
83 | 83 |
#define DIGRAPH_TYPEDEFS(Digraph) \ |
84 | 84 |
typedef Digraph::Node Node; \ |
85 | 85 |
typedef Digraph::NodeIt NodeIt; \ |
86 | 86 |
typedef Digraph::Arc Arc; \ |
87 | 87 |
typedef Digraph::ArcIt ArcIt; \ |
88 | 88 |
typedef Digraph::InArcIt InArcIt; \ |
89 | 89 |
typedef Digraph::OutArcIt OutArcIt; \ |
90 | 90 |
typedef Digraph::NodeMap<bool> BoolNodeMap; \ |
91 | 91 |
typedef Digraph::NodeMap<int> IntNodeMap; \ |
92 | 92 |
typedef Digraph::NodeMap<double> DoubleNodeMap; \ |
93 | 93 |
typedef Digraph::ArcMap<bool> BoolArcMap; \ |
94 | 94 |
typedef Digraph::ArcMap<int> IntArcMap; \ |
95 | 95 |
typedef Digraph::ArcMap<double> DoubleArcMap |
96 | 96 |
|
97 | 97 |
///Create convenience typedefs for the digraph types and iterators |
98 | 98 |
|
99 | 99 |
///\see DIGRAPH_TYPEDEFS |
100 | 100 |
/// |
101 | 101 |
///\note Use this macro, if the graph type is a dependent type, |
102 | 102 |
///ie. the graph type depend on a template parameter. |
103 | 103 |
#define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph) \ |
104 | 104 |
typedef typename Digraph::Node Node; \ |
105 | 105 |
typedef typename Digraph::NodeIt NodeIt; \ |
106 | 106 |
typedef typename Digraph::Arc Arc; \ |
107 | 107 |
typedef typename Digraph::ArcIt ArcIt; \ |
108 | 108 |
typedef typename Digraph::InArcIt InArcIt; \ |
109 | 109 |
typedef typename Digraph::OutArcIt OutArcIt; \ |
110 | 110 |
typedef typename Digraph::template NodeMap<bool> BoolNodeMap; \ |
111 | 111 |
typedef typename Digraph::template NodeMap<int> IntNodeMap; \ |
112 | 112 |
typedef typename Digraph::template NodeMap<double> DoubleNodeMap; \ |
113 | 113 |
typedef typename Digraph::template ArcMap<bool> BoolArcMap; \ |
114 | 114 |
typedef typename Digraph::template ArcMap<int> IntArcMap; \ |
115 | 115 |
typedef typename Digraph::template ArcMap<double> DoubleArcMap |
116 | 116 |
|
117 | 117 |
///Create convenience typedefs for the graph types and iterators |
118 | 118 |
|
119 | 119 |
///This \c \#define creates the same convenient type definitions as defined |
120 | 120 |
///by \ref DIGRAPH_TYPEDEFS(Graph) and six more, namely it creates |
121 | 121 |
///\c Edge, \c EdgeIt, \c IncEdgeIt, \c BoolEdgeMap, \c IntEdgeMap, |
122 | 122 |
///\c DoubleEdgeMap. |
123 | 123 |
/// |
124 | 124 |
///\note If the graph type is a dependent type, ie. the graph type depend |
125 | 125 |
///on a template parameter, then use \c TEMPLATE_GRAPH_TYPEDEFS() |
126 | 126 |
///macro. |
127 | 127 |
#define GRAPH_TYPEDEFS(Graph) \ |
128 | 128 |
DIGRAPH_TYPEDEFS(Graph); \ |
129 | 129 |
typedef Graph::Edge Edge; \ |
130 | 130 |
typedef Graph::EdgeIt EdgeIt; \ |
131 | 131 |
typedef Graph::IncEdgeIt IncEdgeIt; \ |
132 | 132 |
typedef Graph::EdgeMap<bool> BoolEdgeMap; \ |
133 | 133 |
typedef Graph::EdgeMap<int> IntEdgeMap; \ |
134 | 134 |
typedef Graph::EdgeMap<double> DoubleEdgeMap |
135 | 135 |
|
136 | 136 |
///Create convenience typedefs for the graph types and iterators |
137 | 137 |
|
138 | 138 |
///\see GRAPH_TYPEDEFS |
139 | 139 |
/// |
140 | 140 |
///\note Use this macro, if the graph type is a dependent type, |
141 | 141 |
///ie. the graph type depend on a template parameter. |
142 | 142 |
#define TEMPLATE_GRAPH_TYPEDEFS(Graph) \ |
143 | 143 |
TEMPLATE_DIGRAPH_TYPEDEFS(Graph); \ |
144 | 144 |
typedef typename Graph::Edge Edge; \ |
145 | 145 |
typedef typename Graph::EdgeIt EdgeIt; \ |
146 | 146 |
typedef typename Graph::IncEdgeIt IncEdgeIt; \ |
147 | 147 |
typedef typename Graph::template EdgeMap<bool> BoolEdgeMap; \ |
148 | 148 |
typedef typename Graph::template EdgeMap<int> IntEdgeMap; \ |
149 | 149 |
typedef typename Graph::template EdgeMap<double> DoubleEdgeMap |
150 | 150 |
|
151 | 151 |
/// \brief Function to count the items in a graph. |
152 | 152 |
/// |
153 | 153 |
/// This function counts the items (nodes, arcs etc.) in a graph. |
154 | 154 |
/// The complexity of the function is linear because |
155 | 155 |
/// it iterates on all of the items. |
156 | 156 |
template <typename Graph, typename Item> |
157 | 157 |
inline int countItems(const Graph& g) { |
158 | 158 |
typedef typename ItemSetTraits<Graph, Item>::ItemIt ItemIt; |
159 | 159 |
int num = 0; |
160 | 160 |
for (ItemIt it(g); it != INVALID; ++it) { |
161 | 161 |
++num; |
162 | 162 |
} |
163 | 163 |
return num; |
164 | 164 |
} |
165 | 165 |
|
166 | 166 |
// Node counting: |
167 | 167 |
|
168 | 168 |
namespace _core_bits { |
169 | 169 |
|
170 | 170 |
template <typename Graph, typename Enable = void> |
171 | 171 |
struct CountNodesSelector { |
172 | 172 |
static int count(const Graph &g) { |
173 | 173 |
return countItems<Graph, typename Graph::Node>(g); |
174 | 174 |
} |
175 | 175 |
}; |
176 | 176 |
|
177 | 177 |
template <typename Graph> |
178 | 178 |
struct CountNodesSelector< |
179 | 179 |
Graph, typename |
180 | 180 |
enable_if<typename Graph::NodeNumTag, void>::type> |
181 | 181 |
{ |
182 | 182 |
static int count(const Graph &g) { |
183 | 183 |
return g.nodeNum(); |
184 | 184 |
} |
185 | 185 |
}; |
186 | 186 |
} |
187 | 187 |
|
188 | 188 |
/// \brief Function to count the nodes in the graph. |
189 | 189 |
/// |
190 | 190 |
/// This function counts the nodes in the graph. |
191 | 191 |
/// The complexity of the function is <em>O</em>(<em>n</em>), but for some |
192 | 192 |
/// graph structures it is specialized to run in <em>O</em>(1). |
193 | 193 |
/// |
194 | 194 |
/// \note If the graph contains a \c nodeNum() member function and a |
195 | 195 |
/// \c NodeNumTag tag then this function calls directly the member |
196 | 196 |
/// function to query the cardinality of the node set. |
197 | 197 |
template <typename Graph> |
198 | 198 |
inline int countNodes(const Graph& g) { |
199 | 199 |
return _core_bits::CountNodesSelector<Graph>::count(g); |
200 | 200 |
} |
201 | 201 |
|
202 | 202 |
// Arc counting: |
203 | 203 |
|
204 | 204 |
namespace _core_bits { |
205 | 205 |
|
206 | 206 |
template <typename Graph, typename Enable = void> |
207 | 207 |
struct CountArcsSelector { |
208 | 208 |
static int count(const Graph &g) { |
209 | 209 |
return countItems<Graph, typename Graph::Arc>(g); |
210 | 210 |
} |
211 | 211 |
}; |
212 | 212 |
|
213 | 213 |
template <typename Graph> |
214 | 214 |
struct CountArcsSelector< |
215 | 215 |
Graph, |
216 | 216 |
typename enable_if<typename Graph::ArcNumTag, void>::type> |
217 | 217 |
{ |
218 | 218 |
static int count(const Graph &g) { |
219 | 219 |
return g.arcNum(); |
220 | 220 |
} |
221 | 221 |
}; |
222 | 222 |
} |
223 | 223 |
|
224 | 224 |
/// \brief Function to count the arcs in the graph. |
225 | 225 |
/// |
226 | 226 |
/// This function counts the arcs in the graph. |
227 | 227 |
/// The complexity of the function is <em>O</em>(<em>m</em>), but for some |
228 | 228 |
/// graph structures it is specialized to run in <em>O</em>(1). |
229 | 229 |
/// |
230 | 230 |
/// \note If the graph contains a \c arcNum() member function and a |
231 | 231 |
/// \c ArcNumTag tag then this function calls directly the member |
232 | 232 |
/// function to query the cardinality of the arc set. |
233 | 233 |
template <typename Graph> |
234 | 234 |
inline int countArcs(const Graph& g) { |
235 | 235 |
return _core_bits::CountArcsSelector<Graph>::count(g); |
236 | 236 |
} |
237 | 237 |
|
238 | 238 |
// Edge counting: |
239 | 239 |
|
240 | 240 |
namespace _core_bits { |
241 | 241 |
|
242 | 242 |
template <typename Graph, typename Enable = void> |
243 | 243 |
struct CountEdgesSelector { |
244 | 244 |
static int count(const Graph &g) { |
245 | 245 |
return countItems<Graph, typename Graph::Edge>(g); |
246 | 246 |
} |
247 | 247 |
}; |
248 | 248 |
|
249 | 249 |
template <typename Graph> |
250 | 250 |
struct CountEdgesSelector< |
251 | 251 |
Graph, |
252 | 252 |
typename enable_if<typename Graph::EdgeNumTag, void>::type> |
253 | 253 |
{ |
254 | 254 |
static int count(const Graph &g) { |
255 | 255 |
return g.edgeNum(); |
256 | 256 |
} |
257 | 257 |
}; |
258 | 258 |
} |
259 | 259 |
|
260 | 260 |
/// \brief Function to count the edges in the graph. |
261 | 261 |
/// |
262 | 262 |
/// This function counts the edges in the graph. |
263 | 263 |
/// The complexity of the function is <em>O</em>(<em>m</em>), but for some |
264 | 264 |
/// graph structures it is specialized to run in <em>O</em>(1). |
265 | 265 |
/// |
266 | 266 |
/// \note If the graph contains a \c edgeNum() member function and a |
267 | 267 |
/// \c EdgeNumTag tag then this function calls directly the member |
268 | 268 |
/// function to query the cardinality of the edge set. |
269 | 269 |
template <typename Graph> |
270 | 270 |
inline int countEdges(const Graph& g) { |
271 | 271 |
return _core_bits::CountEdgesSelector<Graph>::count(g); |
272 | 272 |
|
273 | 273 |
} |
274 | 274 |
|
275 | 275 |
|
276 | 276 |
template <typename Graph, typename DegIt> |
277 | 277 |
inline int countNodeDegree(const Graph& _g, const typename Graph::Node& _n) { |
278 | 278 |
int num = 0; |
279 | 279 |
for (DegIt it(_g, _n); it != INVALID; ++it) { |
280 | 280 |
++num; |
281 | 281 |
} |
282 | 282 |
return num; |
283 | 283 |
} |
284 | 284 |
|
285 | 285 |
/// \brief Function to count the number of the out-arcs from node \c n. |
286 | 286 |
/// |
287 | 287 |
/// This function counts the number of the out-arcs from node \c n |
288 | 288 |
/// in the graph \c g. |
289 | 289 |
template <typename Graph> |
290 | 290 |
inline int countOutArcs(const Graph& g, const typename Graph::Node& n) { |
291 | 291 |
return countNodeDegree<Graph, typename Graph::OutArcIt>(g, n); |
292 | 292 |
} |
293 | 293 |
|
294 | 294 |
/// \brief Function to count the number of the in-arcs to node \c n. |
295 | 295 |
/// |
296 | 296 |
/// This function counts the number of the in-arcs to node \c n |
297 | 297 |
/// in the graph \c g. |
298 | 298 |
template <typename Graph> |
299 | 299 |
inline int countInArcs(const Graph& g, const typename Graph::Node& n) { |
300 | 300 |
return countNodeDegree<Graph, typename Graph::InArcIt>(g, n); |
301 | 301 |
} |
302 | 302 |
|
303 | 303 |
/// \brief Function to count the number of the inc-edges to node \c n. |
304 | 304 |
/// |
305 | 305 |
/// This function counts the number of the inc-edges to node \c n |
306 | 306 |
/// in the undirected graph \c g. |
307 | 307 |
template <typename Graph> |
308 | 308 |
inline int countIncEdges(const Graph& g, const typename Graph::Node& n) { |
309 | 309 |
return countNodeDegree<Graph, typename Graph::IncEdgeIt>(g, n); |
310 | 310 |
} |
311 | 311 |
|
312 | 312 |
namespace _core_bits { |
313 | 313 |
|
314 | 314 |
template <typename Digraph, typename Item, typename RefMap> |
315 | 315 |
class MapCopyBase { |
316 | 316 |
public: |
317 | 317 |
virtual void copy(const Digraph& from, const RefMap& refMap) = 0; |
318 | 318 |
|
319 | 319 |
virtual ~MapCopyBase() {} |
320 | 320 |
}; |
321 | 321 |
|
322 | 322 |
template <typename Digraph, typename Item, typename RefMap, |
323 | 323 |
typename FromMap, typename ToMap> |
324 | 324 |
class MapCopy : public MapCopyBase<Digraph, Item, RefMap> { |
325 | 325 |
public: |
326 | 326 |
|
327 | 327 |
MapCopy(const FromMap& map, ToMap& tmap) |
328 | 328 |
: _map(map), _tmap(tmap) {} |
329 | 329 |
|
330 | 330 |
virtual void copy(const Digraph& digraph, const RefMap& refMap) { |
331 | 331 |
typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt; |
332 | 332 |
for (ItemIt it(digraph); it != INVALID; ++it) { |
333 | 333 |
_tmap.set(refMap[it], _map[it]); |
334 | 334 |
} |
335 | 335 |
} |
336 | 336 |
|
337 | 337 |
private: |
338 | 338 |
const FromMap& _map; |
339 | 339 |
ToMap& _tmap; |
340 | 340 |
}; |
341 | 341 |
|
342 | 342 |
template <typename Digraph, typename Item, typename RefMap, typename It> |
343 | 343 |
class ItemCopy : public MapCopyBase<Digraph, Item, RefMap> { |
344 | 344 |
public: |
345 | 345 |
|
346 | 346 |
ItemCopy(const Item& item, It& it) : _item(item), _it(it) {} |
347 | 347 |
|
348 | 348 |
virtual void copy(const Digraph&, const RefMap& refMap) { |
349 | 349 |
_it = refMap[_item]; |
350 | 350 |
} |
351 | 351 |
|
352 | 352 |
private: |
353 | 353 |
Item _item; |
354 | 354 |
It& _it; |
355 | 355 |
}; |
356 | 356 |
|
357 | 357 |
template <typename Digraph, typename Item, typename RefMap, typename Ref> |
358 | 358 |
class RefCopy : public MapCopyBase<Digraph, Item, RefMap> { |
359 | 359 |
public: |
360 | 360 |
|
361 | 361 |
RefCopy(Ref& map) : _map(map) {} |
362 | 362 |
|
363 | 363 |
virtual void copy(const Digraph& digraph, const RefMap& refMap) { |
364 | 364 |
typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt; |
365 | 365 |
for (ItemIt it(digraph); it != INVALID; ++it) { |
366 | 366 |
_map.set(it, refMap[it]); |
367 | 367 |
} |
368 | 368 |
} |
369 | 369 |
|
370 | 370 |
private: |
371 | 371 |
Ref& _map; |
372 | 372 |
}; |
373 | 373 |
|
374 | 374 |
template <typename Digraph, typename Item, typename RefMap, |
375 | 375 |
typename CrossRef> |
376 | 376 |
class CrossRefCopy : public MapCopyBase<Digraph, Item, RefMap> { |
377 | 377 |
public: |
378 | 378 |
|
379 | 379 |
CrossRefCopy(CrossRef& cmap) : _cmap(cmap) {} |
380 | 380 |
|
381 | 381 |
virtual void copy(const Digraph& digraph, const RefMap& refMap) { |
382 | 382 |
typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt; |
383 | 383 |
for (ItemIt it(digraph); it != INVALID; ++it) { |
384 | 384 |
_cmap.set(refMap[it], it); |
385 | 385 |
} |
386 | 386 |
} |
387 | 387 |
|
388 | 388 |
private: |
389 | 389 |
CrossRef& _cmap; |
390 | 390 |
}; |
391 | 391 |
|
392 | 392 |
template <typename Digraph, typename Enable = void> |
393 | 393 |
struct DigraphCopySelector { |
394 | 394 |
template <typename From, typename NodeRefMap, typename ArcRefMap> |
395 | 395 |
static void copy(const From& from, Digraph &to, |
396 | 396 |
NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) { |
397 | 397 |
to.clear(); |
398 | 398 |
for (typename From::NodeIt it(from); it != INVALID; ++it) { |
399 | 399 |
nodeRefMap[it] = to.addNode(); |
400 | 400 |
} |
401 | 401 |
for (typename From::ArcIt it(from); it != INVALID; ++it) { |
402 | 402 |
arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)], |
403 | 403 |
nodeRefMap[from.target(it)]); |
404 | 404 |
} |
405 | 405 |
} |
406 | 406 |
}; |
407 | 407 |
|
408 | 408 |
template <typename Digraph> |
409 | 409 |
struct DigraphCopySelector< |
410 | 410 |
Digraph, |
411 | 411 |
typename enable_if<typename Digraph::BuildTag, void>::type> |
412 | 412 |
{ |
413 | 413 |
template <typename From, typename NodeRefMap, typename ArcRefMap> |
414 | 414 |
static void copy(const From& from, Digraph &to, |
415 | 415 |
NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) { |
416 | 416 |
to.build(from, nodeRefMap, arcRefMap); |
417 | 417 |
} |
418 | 418 |
}; |
419 | 419 |
|
420 | 420 |
template <typename Graph, typename Enable = void> |
421 | 421 |
struct GraphCopySelector { |
422 | 422 |
template <typename From, typename NodeRefMap, typename EdgeRefMap> |
423 | 423 |
static void copy(const From& from, Graph &to, |
424 | 424 |
NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) { |
425 | 425 |
to.clear(); |
426 | 426 |
for (typename From::NodeIt it(from); it != INVALID; ++it) { |
427 | 427 |
nodeRefMap[it] = to.addNode(); |
428 | 428 |
} |
429 | 429 |
for (typename From::EdgeIt it(from); it != INVALID; ++it) { |
430 | 430 |
edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)], |
431 | 431 |
nodeRefMap[from.v(it)]); |
432 | 432 |
} |
433 | 433 |
} |
434 | 434 |
}; |
435 | 435 |
|
436 | 436 |
template <typename Graph> |
437 | 437 |
struct GraphCopySelector< |
438 | 438 |
Graph, |
439 | 439 |
typename enable_if<typename Graph::BuildTag, void>::type> |
440 | 440 |
{ |
441 | 441 |
template <typename From, typename NodeRefMap, typename EdgeRefMap> |
442 | 442 |
static void copy(const From& from, Graph &to, |
443 | 443 |
NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) { |
444 | 444 |
to.build(from, nodeRefMap, edgeRefMap); |
445 | 445 |
} |
446 | 446 |
}; |
447 | 447 |
|
448 | 448 |
} |
449 | 449 |
|
450 |
/// Check whether a graph is undirected. |
|
450 |
/// \brief Check whether a graph is undirected. |
|
451 | 451 |
/// |
452 | 452 |
/// This function returns \c true if the given graph is undirected. |
453 | 453 |
#ifdef DOXYGEN |
454 | 454 |
template <typename GR> |
455 | 455 |
bool undirected(const GR& g) { return false; } |
456 | 456 |
#else |
457 | 457 |
template <typename GR> |
458 | 458 |
typename enable_if<UndirectedTagIndicator<GR>, bool>::type |
459 | 459 |
undirected(const GR&) { |
460 | 460 |
return true; |
461 | 461 |
} |
462 | 462 |
template <typename GR> |
463 | 463 |
typename disable_if<UndirectedTagIndicator<GR>, bool>::type |
464 | 464 |
undirected(const GR&) { |
465 | 465 |
return false; |
466 | 466 |
} |
467 | 467 |
#endif |
468 | 468 |
|
469 | 469 |
/// \brief Class to copy a digraph. |
470 | 470 |
/// |
471 | 471 |
/// Class to copy a digraph to another digraph (duplicate a digraph). The |
472 | 472 |
/// simplest way of using it is through the \c digraphCopy() function. |
473 | 473 |
/// |
474 | 474 |
/// This class not only make a copy of a digraph, but it can create |
475 | 475 |
/// references and cross references between the nodes and arcs of |
476 | 476 |
/// the two digraphs, and it can copy maps to use with the newly created |
477 | 477 |
/// digraph. |
478 | 478 |
/// |
479 | 479 |
/// To make a copy from a digraph, first an instance of DigraphCopy |
480 | 480 |
/// should be created, then the data belongs to the digraph should |
481 | 481 |
/// assigned to copy. In the end, the \c run() member should be |
482 | 482 |
/// called. |
483 | 483 |
/// |
484 | 484 |
/// The next code copies a digraph with several data: |
485 | 485 |
///\code |
486 | 486 |
/// DigraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph); |
487 | 487 |
/// // Create references for the nodes |
488 | 488 |
/// OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph); |
489 | 489 |
/// cg.nodeRef(nr); |
490 | 490 |
/// // Create cross references (inverse) for the arcs |
491 | 491 |
/// NewGraph::ArcMap<OrigGraph::Arc> acr(new_graph); |
492 | 492 |
/// cg.arcCrossRef(acr); |
493 | 493 |
/// // Copy an arc map |
494 | 494 |
/// OrigGraph::ArcMap<double> oamap(orig_graph); |
495 | 495 |
/// NewGraph::ArcMap<double> namap(new_graph); |
496 | 496 |
/// cg.arcMap(oamap, namap); |
497 | 497 |
/// // Copy a node |
498 | 498 |
/// OrigGraph::Node on; |
499 | 499 |
/// NewGraph::Node nn; |
500 | 500 |
/// cg.node(on, nn); |
501 | 501 |
/// // Execute copying |
502 | 502 |
/// cg.run(); |
503 | 503 |
///\endcode |
504 | 504 |
template <typename From, typename To> |
505 | 505 |
class DigraphCopy { |
506 | 506 |
private: |
507 | 507 |
|
508 | 508 |
typedef typename From::Node Node; |
509 | 509 |
typedef typename From::NodeIt NodeIt; |
510 | 510 |
typedef typename From::Arc Arc; |
511 | 511 |
typedef typename From::ArcIt ArcIt; |
512 | 512 |
|
513 | 513 |
typedef typename To::Node TNode; |
514 | 514 |
typedef typename To::Arc TArc; |
515 | 515 |
|
516 | 516 |
typedef typename From::template NodeMap<TNode> NodeRefMap; |
517 | 517 |
typedef typename From::template ArcMap<TArc> ArcRefMap; |
518 | 518 |
|
519 | 519 |
public: |
520 | 520 |
|
521 | 521 |
/// \brief Constructor of DigraphCopy. |
522 | 522 |
/// |
523 | 523 |
/// Constructor of DigraphCopy for copying the content of the |
524 | 524 |
/// \c from digraph into the \c to digraph. |
525 | 525 |
DigraphCopy(const From& from, To& to) |
526 | 526 |
: _from(from), _to(to) {} |
527 | 527 |
|
528 | 528 |
/// \brief Destructor of DigraphCopy |
529 | 529 |
/// |
530 | 530 |
/// Destructor of DigraphCopy. |
531 | 531 |
~DigraphCopy() { |
532 | 532 |
for (int i = 0; i < int(_node_maps.size()); ++i) { |
533 | 533 |
delete _node_maps[i]; |
534 | 534 |
} |
535 | 535 |
for (int i = 0; i < int(_arc_maps.size()); ++i) { |
536 | 536 |
delete _arc_maps[i]; |
537 | 537 |
} |
538 | 538 |
|
539 | 539 |
} |
540 | 540 |
|
541 | 541 |
/// \brief Copy the node references into the given map. |
542 | 542 |
/// |
543 | 543 |
/// This function copies the node references into the given map. |
544 | 544 |
/// The parameter should be a map, whose key type is the Node type of |
545 | 545 |
/// the source digraph, while the value type is the Node type of the |
546 | 546 |
/// destination digraph. |
547 | 547 |
template <typename NodeRef> |
548 | 548 |
DigraphCopy& nodeRef(NodeRef& map) { |
549 | 549 |
_node_maps.push_back(new _core_bits::RefCopy<From, Node, |
550 | 550 |
NodeRefMap, NodeRef>(map)); |
551 | 551 |
return *this; |
552 | 552 |
} |
553 | 553 |
|
554 | 554 |
/// \brief Copy the node cross references into the given map. |
555 | 555 |
/// |
556 | 556 |
/// This function copies the node cross references (reverse references) |
557 | 557 |
/// into the given map. The parameter should be a map, whose key type |
558 | 558 |
/// is the Node type of the destination digraph, while the value type is |
559 | 559 |
/// the Node type of the source digraph. |
560 | 560 |
template <typename NodeCrossRef> |
561 | 561 |
DigraphCopy& nodeCrossRef(NodeCrossRef& map) { |
562 | 562 |
_node_maps.push_back(new _core_bits::CrossRefCopy<From, Node, |
563 | 563 |
NodeRefMap, NodeCrossRef>(map)); |
564 | 564 |
return *this; |
565 | 565 |
} |
566 | 566 |
|
567 | 567 |
/// \brief Make a copy of the given node map. |
568 | 568 |
/// |
569 | 569 |
/// This function makes a copy of the given node map for the newly |
570 | 570 |
/// created digraph. |
571 | 571 |
/// The key type of the new map \c tmap should be the Node type of the |
572 | 572 |
/// destination digraph, and the key type of the original map \c map |
573 | 573 |
/// should be the Node type of the source digraph. |
574 | 574 |
template <typename FromMap, typename ToMap> |
575 | 575 |
DigraphCopy& nodeMap(const FromMap& map, ToMap& tmap) { |
576 | 576 |
_node_maps.push_back(new _core_bits::MapCopy<From, Node, |
577 | 577 |
NodeRefMap, FromMap, ToMap>(map, tmap)); |
578 | 578 |
return *this; |
579 | 579 |
} |
580 | 580 |
|
581 | 581 |
/// \brief Make a copy of the given node. |
582 | 582 |
/// |
583 | 583 |
/// This function makes a copy of the given node. |
584 | 584 |
DigraphCopy& node(const Node& node, TNode& tnode) { |
585 | 585 |
_node_maps.push_back(new _core_bits::ItemCopy<From, Node, |
586 | 586 |
NodeRefMap, TNode>(node, tnode)); |
587 | 587 |
return *this; |
588 | 588 |
} |
589 | 589 |
|
590 | 590 |
/// \brief Copy the arc references into the given map. |
591 | 591 |
/// |
592 | 592 |
/// This function copies the arc references into the given map. |
593 | 593 |
/// The parameter should be a map, whose key type is the Arc type of |
594 | 594 |
/// the source digraph, while the value type is the Arc type of the |
595 | 595 |
/// destination digraph. |
596 | 596 |
template <typename ArcRef> |
597 | 597 |
DigraphCopy& arcRef(ArcRef& map) { |
598 | 598 |
_arc_maps.push_back(new _core_bits::RefCopy<From, Arc, |
599 | 599 |
ArcRefMap, ArcRef>(map)); |
600 | 600 |
return *this; |
601 | 601 |
} |
602 | 602 |
|
603 | 603 |
/// \brief Copy the arc cross references into the given map. |
604 | 604 |
/// |
605 | 605 |
/// This function copies the arc cross references (reverse references) |
606 | 606 |
/// into the given map. The parameter should be a map, whose key type |
607 | 607 |
/// is the Arc type of the destination digraph, while the value type is |
608 | 608 |
/// the Arc type of the source digraph. |
609 | 609 |
template <typename ArcCrossRef> |
610 | 610 |
DigraphCopy& arcCrossRef(ArcCrossRef& map) { |
611 | 611 |
_arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc, |
612 | 612 |
ArcRefMap, ArcCrossRef>(map)); |
613 | 613 |
return *this; |
614 | 614 |
} |
615 | 615 |
|
616 | 616 |
/// \brief Make a copy of the given arc map. |
617 | 617 |
/// |
618 | 618 |
/// This function makes a copy of the given arc map for the newly |
619 | 619 |
/// created digraph. |
620 | 620 |
/// The key type of the new map \c tmap should be the Arc type of the |
621 | 621 |
/// destination digraph, and the key type of the original map \c map |
622 | 622 |
/// should be the Arc type of the source digraph. |
623 | 623 |
template <typename FromMap, typename ToMap> |
624 | 624 |
DigraphCopy& arcMap(const FromMap& map, ToMap& tmap) { |
625 | 625 |
_arc_maps.push_back(new _core_bits::MapCopy<From, Arc, |
626 | 626 |
ArcRefMap, FromMap, ToMap>(map, tmap)); |
627 | 627 |
return *this; |
628 | 628 |
} |
629 | 629 |
|
630 | 630 |
/// \brief Make a copy of the given arc. |
631 | 631 |
/// |
632 | 632 |
/// This function makes a copy of the given arc. |
633 | 633 |
DigraphCopy& arc(const Arc& arc, TArc& tarc) { |
634 | 634 |
_arc_maps.push_back(new _core_bits::ItemCopy<From, Arc, |
635 | 635 |
ArcRefMap, TArc>(arc, tarc)); |
636 | 636 |
return *this; |
637 | 637 |
} |
638 | 638 |
|
639 | 639 |
/// \brief Execute copying. |
640 | 640 |
/// |
641 | 641 |
/// This function executes the copying of the digraph along with the |
642 | 642 |
/// copying of the assigned data. |
643 | 643 |
void run() { |
644 | 644 |
NodeRefMap nodeRefMap(_from); |
645 | 645 |
ArcRefMap arcRefMap(_from); |
646 | 646 |
_core_bits::DigraphCopySelector<To>:: |
647 | 647 |
copy(_from, _to, nodeRefMap, arcRefMap); |
648 | 648 |
for (int i = 0; i < int(_node_maps.size()); ++i) { |
649 | 649 |
_node_maps[i]->copy(_from, nodeRefMap); |
650 | 650 |
} |
651 | 651 |
for (int i = 0; i < int(_arc_maps.size()); ++i) { |
652 | 652 |
_arc_maps[i]->copy(_from, arcRefMap); |
653 | 653 |
} |
654 | 654 |
} |
655 | 655 |
|
656 | 656 |
protected: |
657 | 657 |
|
658 | 658 |
const From& _from; |
659 | 659 |
To& _to; |
660 | 660 |
|
661 | 661 |
std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* > |
662 | 662 |
_node_maps; |
663 | 663 |
|
664 | 664 |
std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* > |
665 | 665 |
_arc_maps; |
666 | 666 |
|
667 | 667 |
}; |
668 | 668 |
|
669 | 669 |
/// \brief Copy a digraph to another digraph. |
670 | 670 |
/// |
671 | 671 |
/// This function copies a digraph to another digraph. |
672 | 672 |
/// The complete usage of it is detailed in the DigraphCopy class, but |
673 | 673 |
/// a short example shows a basic work: |
674 | 674 |
///\code |
675 | 675 |
/// digraphCopy(src, trg).nodeRef(nr).arcCrossRef(acr).run(); |
676 | 676 |
///\endcode |
677 | 677 |
/// |
678 | 678 |
/// After the copy the \c nr map will contain the mapping from the |
679 | 679 |
/// nodes of the \c from digraph to the nodes of the \c to digraph and |
680 | 680 |
/// \c acr will contain the mapping from the arcs of the \c to digraph |
681 | 681 |
/// to the arcs of the \c from digraph. |
682 | 682 |
/// |
683 | 683 |
/// \see DigraphCopy |
684 | 684 |
template <typename From, typename To> |
685 | 685 |
DigraphCopy<From, To> digraphCopy(const From& from, To& to) { |
686 | 686 |
return DigraphCopy<From, To>(from, to); |
687 | 687 |
} |
688 | 688 |
|
689 | 689 |
/// \brief Class to copy a graph. |
690 | 690 |
/// |
691 | 691 |
/// Class to copy a graph to another graph (duplicate a graph). The |
692 | 692 |
/// simplest way of using it is through the \c graphCopy() function. |
693 | 693 |
/// |
694 | 694 |
/// This class not only make a copy of a graph, but it can create |
695 | 695 |
/// references and cross references between the nodes, edges and arcs of |
696 | 696 |
/// the two graphs, and it can copy maps for using with the newly created |
697 | 697 |
/// graph. |
698 | 698 |
/// |
699 | 699 |
/// To make a copy from a graph, first an instance of GraphCopy |
700 | 700 |
/// should be created, then the data belongs to the graph should |
701 | 701 |
/// assigned to copy. In the end, the \c run() member should be |
702 | 702 |
/// called. |
703 | 703 |
/// |
704 | 704 |
/// The next code copies a graph with several data: |
705 | 705 |
///\code |
706 | 706 |
/// GraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph); |
707 | 707 |
/// // Create references for the nodes |
708 | 708 |
/// OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph); |
709 | 709 |
/// cg.nodeRef(nr); |
710 | 710 |
/// // Create cross references (inverse) for the edges |
711 | 711 |
/// NewGraph::EdgeMap<OrigGraph::Edge> ecr(new_graph); |
712 | 712 |
/// cg.edgeCrossRef(ecr); |
713 | 713 |
/// // Copy an edge map |
714 | 714 |
/// OrigGraph::EdgeMap<double> oemap(orig_graph); |
715 | 715 |
/// NewGraph::EdgeMap<double> nemap(new_graph); |
716 | 716 |
/// cg.edgeMap(oemap, nemap); |
717 | 717 |
/// // Copy a node |
718 | 718 |
/// OrigGraph::Node on; |
719 | 719 |
/// NewGraph::Node nn; |
720 | 720 |
/// cg.node(on, nn); |
721 | 721 |
/// // Execute copying |
722 | 722 |
/// cg.run(); |
723 | 723 |
///\endcode |
724 | 724 |
template <typename From, typename To> |
725 | 725 |
class GraphCopy { |
726 | 726 |
private: |
727 | 727 |
|
728 | 728 |
typedef typename From::Node Node; |
729 | 729 |
typedef typename From::NodeIt NodeIt; |
730 | 730 |
typedef typename From::Arc Arc; |
731 | 731 |
typedef typename From::ArcIt ArcIt; |
732 | 732 |
typedef typename From::Edge Edge; |
733 | 733 |
typedef typename From::EdgeIt EdgeIt; |
734 | 734 |
|
735 | 735 |
typedef typename To::Node TNode; |
736 | 736 |
typedef typename To::Arc TArc; |
737 | 737 |
typedef typename To::Edge TEdge; |
738 | 738 |
|
739 | 739 |
typedef typename From::template NodeMap<TNode> NodeRefMap; |
740 | 740 |
typedef typename From::template EdgeMap<TEdge> EdgeRefMap; |
741 | 741 |
|
742 | 742 |
struct ArcRefMap { |
743 | 743 |
ArcRefMap(const From& from, const To& to, |
744 | 744 |
const EdgeRefMap& edge_ref, const NodeRefMap& node_ref) |
745 | 745 |
: _from(from), _to(to), |
746 | 746 |
_edge_ref(edge_ref), _node_ref(node_ref) {} |
747 | 747 |
|
748 | 748 |
typedef typename From::Arc Key; |
749 | 749 |
typedef typename To::Arc Value; |
750 | 750 |
|
751 | 751 |
Value operator[](const Key& key) const { |
752 | 752 |
bool forward = _from.u(key) != _from.v(key) ? |
753 | 753 |
_node_ref[_from.source(key)] == |
754 | 754 |
_to.source(_to.direct(_edge_ref[key], true)) : |
755 | 755 |
_from.direction(key); |
756 | 756 |
return _to.direct(_edge_ref[key], forward); |
757 | 757 |
} |
758 | 758 |
|
759 | 759 |
const From& _from; |
760 | 760 |
const To& _to; |
761 | 761 |
const EdgeRefMap& _edge_ref; |
762 | 762 |
const NodeRefMap& _node_ref; |
763 | 763 |
}; |
764 | 764 |
|
765 | 765 |
public: |
766 | 766 |
|
767 | 767 |
/// \brief Constructor of GraphCopy. |
768 | 768 |
/// |
769 | 769 |
/// Constructor of GraphCopy for copying the content of the |
770 | 770 |
/// \c from graph into the \c to graph. |
771 | 771 |
GraphCopy(const From& from, To& to) |
772 | 772 |
: _from(from), _to(to) {} |
773 | 773 |
|
774 | 774 |
/// \brief Destructor of GraphCopy |
775 | 775 |
/// |
776 | 776 |
/// Destructor of GraphCopy. |
777 | 777 |
~GraphCopy() { |
778 | 778 |
for (int i = 0; i < int(_node_maps.size()); ++i) { |
779 | 779 |
delete _node_maps[i]; |
780 | 780 |
} |
781 | 781 |
for (int i = 0; i < int(_arc_maps.size()); ++i) { |
782 | 782 |
delete _arc_maps[i]; |
783 | 783 |
} |
784 | 784 |
for (int i = 0; i < int(_edge_maps.size()); ++i) { |
785 | 785 |
delete _edge_maps[i]; |
786 | 786 |
} |
787 | 787 |
} |
788 | 788 |
|
789 | 789 |
/// \brief Copy the node references into the given map. |
790 | 790 |
/// |
791 | 791 |
/// This function copies the node references into the given map. |
792 | 792 |
/// The parameter should be a map, whose key type is the Node type of |
793 | 793 |
/// the source graph, while the value type is the Node type of the |
794 | 794 |
/// destination graph. |
795 | 795 |
template <typename NodeRef> |
796 | 796 |
GraphCopy& nodeRef(NodeRef& map) { |
797 | 797 |
_node_maps.push_back(new _core_bits::RefCopy<From, Node, |
798 | 798 |
NodeRefMap, NodeRef>(map)); |
799 | 799 |
return *this; |
800 | 800 |
} |
801 | 801 |
|
802 | 802 |
/// \brief Copy the node cross references into the given map. |
803 | 803 |
/// |
804 | 804 |
/// This function copies the node cross references (reverse references) |
805 | 805 |
/// into the given map. The parameter should be a map, whose key type |
806 | 806 |
/// is the Node type of the destination graph, while the value type is |
807 | 807 |
/// the Node type of the source graph. |
808 | 808 |
template <typename NodeCrossRef> |
809 | 809 |
GraphCopy& nodeCrossRef(NodeCrossRef& map) { |
810 | 810 |
_node_maps.push_back(new _core_bits::CrossRefCopy<From, Node, |
811 | 811 |
NodeRefMap, NodeCrossRef>(map)); |
812 | 812 |
return *this; |
813 | 813 |
} |
814 | 814 |
|
815 | 815 |
/// \brief Make a copy of the given node map. |
816 | 816 |
/// |
817 | 817 |
/// This function makes a copy of the given node map for the newly |
818 | 818 |
/// created graph. |
819 | 819 |
/// The key type of the new map \c tmap should be the Node type of the |
820 | 820 |
/// destination graph, and the key type of the original map \c map |
821 | 821 |
/// should be the Node type of the source graph. |
822 | 822 |
template <typename FromMap, typename ToMap> |
823 | 823 |
GraphCopy& nodeMap(const FromMap& map, ToMap& tmap) { |
824 | 824 |
_node_maps.push_back(new _core_bits::MapCopy<From, Node, |
825 | 825 |
NodeRefMap, FromMap, ToMap>(map, tmap)); |
826 | 826 |
return *this; |
827 | 827 |
} |
828 | 828 |
|
829 | 829 |
/// \brief Make a copy of the given node. |
830 | 830 |
/// |
831 | 831 |
/// This function makes a copy of the given node. |
832 | 832 |
GraphCopy& node(const Node& node, TNode& tnode) { |
833 | 833 |
_node_maps.push_back(new _core_bits::ItemCopy<From, Node, |
834 | 834 |
NodeRefMap, TNode>(node, tnode)); |
835 | 835 |
return *this; |
836 | 836 |
} |
837 | 837 |
|
838 | 838 |
/// \brief Copy the arc references into the given map. |
839 | 839 |
/// |
840 | 840 |
/// This function copies the arc references into the given map. |
841 | 841 |
/// The parameter should be a map, whose key type is the Arc type of |
842 | 842 |
/// the source graph, while the value type is the Arc type of the |
843 | 843 |
/// destination graph. |
844 | 844 |
template <typename ArcRef> |
845 | 845 |
GraphCopy& arcRef(ArcRef& map) { |
846 | 846 |
_arc_maps.push_back(new _core_bits::RefCopy<From, Arc, |
847 | 847 |
ArcRefMap, ArcRef>(map)); |
848 | 848 |
return *this; |
849 | 849 |
} |
850 | 850 |
|
851 | 851 |
/// \brief Copy the arc cross references into the given map. |
852 | 852 |
/// |
853 | 853 |
/// This function copies the arc cross references (reverse references) |
854 | 854 |
/// into the given map. The parameter should be a map, whose key type |
855 | 855 |
/// is the Arc type of the destination graph, while the value type is |
856 | 856 |
/// the Arc type of the source graph. |
857 | 857 |
template <typename ArcCrossRef> |
858 | 858 |
GraphCopy& arcCrossRef(ArcCrossRef& map) { |
859 | 859 |
_arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc, |
860 | 860 |
ArcRefMap, ArcCrossRef>(map)); |
861 | 861 |
return *this; |
862 | 862 |
} |
863 | 863 |
|
864 | 864 |
/// \brief Make a copy of the given arc map. |
865 | 865 |
/// |
866 | 866 |
/// This function makes a copy of the given arc map for the newly |
867 | 867 |
/// created graph. |
868 | 868 |
/// The key type of the new map \c tmap should be the Arc type of the |
869 | 869 |
/// destination graph, and the key type of the original map \c map |
870 | 870 |
/// should be the Arc type of the source graph. |
871 | 871 |
template <typename FromMap, typename ToMap> |
872 | 872 |
GraphCopy& arcMap(const FromMap& map, ToMap& tmap) { |
873 | 873 |
_arc_maps.push_back(new _core_bits::MapCopy<From, Arc, |
874 | 874 |
ArcRefMap, FromMap, ToMap>(map, tmap)); |
875 | 875 |
return *this; |
876 | 876 |
} |
877 | 877 |
|
878 | 878 |
/// \brief Make a copy of the given arc. |
879 | 879 |
/// |
880 | 880 |
/// This function makes a copy of the given arc. |
881 | 881 |
GraphCopy& arc(const Arc& arc, TArc& tarc) { |
882 | 882 |
_arc_maps.push_back(new _core_bits::ItemCopy<From, Arc, |
883 | 883 |
ArcRefMap, TArc>(arc, tarc)); |
884 | 884 |
return *this; |
885 | 885 |
} |
886 | 886 |
|
887 | 887 |
/// \brief Copy the edge references into the given map. |
888 | 888 |
/// |
889 | 889 |
/// This function copies the edge references into the given map. |
890 | 890 |
/// The parameter should be a map, whose key type is the Edge type of |
891 | 891 |
/// the source graph, while the value type is the Edge type of the |
892 | 892 |
/// destination graph. |
893 | 893 |
template <typename EdgeRef> |
894 | 894 |
GraphCopy& edgeRef(EdgeRef& map) { |
895 | 895 |
_edge_maps.push_back(new _core_bits::RefCopy<From, Edge, |
896 | 896 |
EdgeRefMap, EdgeRef>(map)); |
897 | 897 |
return *this; |
898 | 898 |
} |
899 | 899 |
|
900 | 900 |
/// \brief Copy the edge cross references into the given map. |
901 | 901 |
/// |
902 | 902 |
/// This function copies the edge cross references (reverse references) |
903 | 903 |
/// into the given map. The parameter should be a map, whose key type |
904 | 904 |
/// is the Edge type of the destination graph, while the value type is |
905 | 905 |
/// the Edge type of the source graph. |
906 | 906 |
template <typename EdgeCrossRef> |
907 | 907 |
GraphCopy& edgeCrossRef(EdgeCrossRef& map) { |
908 | 908 |
_edge_maps.push_back(new _core_bits::CrossRefCopy<From, |
909 | 909 |
Edge, EdgeRefMap, EdgeCrossRef>(map)); |
910 | 910 |
return *this; |
911 | 911 |
} |
912 | 912 |
|
913 | 913 |
/// \brief Make a copy of the given edge map. |
914 | 914 |
/// |
915 | 915 |
/// This function makes a copy of the given edge map for the newly |
916 | 916 |
/// created graph. |
917 | 917 |
/// The key type of the new map \c tmap should be the Edge type of the |
918 | 918 |
/// destination graph, and the key type of the original map \c map |
919 | 919 |
/// should be the Edge type of the source graph. |
920 | 920 |
template <typename FromMap, typename ToMap> |
921 | 921 |
GraphCopy& edgeMap(const FromMap& map, ToMap& tmap) { |
922 | 922 |
_edge_maps.push_back(new _core_bits::MapCopy<From, Edge, |
923 | 923 |
EdgeRefMap, FromMap, ToMap>(map, tmap)); |
924 | 924 |
return *this; |
925 | 925 |
} |
926 | 926 |
|
927 | 927 |
/// \brief Make a copy of the given edge. |
928 | 928 |
/// |
929 | 929 |
/// This function makes a copy of the given edge. |
930 | 930 |
GraphCopy& edge(const Edge& edge, TEdge& tedge) { |
931 | 931 |
_edge_maps.push_back(new _core_bits::ItemCopy<From, Edge, |
932 | 932 |
EdgeRefMap, TEdge>(edge, tedge)); |
933 | 933 |
return *this; |
934 | 934 |
} |
935 | 935 |
|
936 | 936 |
/// \brief Execute copying. |
937 | 937 |
/// |
938 | 938 |
/// This function executes the copying of the graph along with the |
939 | 939 |
/// copying of the assigned data. |
940 | 940 |
void run() { |
941 | 941 |
NodeRefMap nodeRefMap(_from); |
942 | 942 |
EdgeRefMap edgeRefMap(_from); |
943 | 943 |
ArcRefMap arcRefMap(_from, _to, edgeRefMap, nodeRefMap); |
944 | 944 |
_core_bits::GraphCopySelector<To>:: |
945 | 945 |
copy(_from, _to, nodeRefMap, edgeRefMap); |
946 | 946 |
for (int i = 0; i < int(_node_maps.size()); ++i) { |
947 | 947 |
_node_maps[i]->copy(_from, nodeRefMap); |
948 | 948 |
} |
949 | 949 |
for (int i = 0; i < int(_edge_maps.size()); ++i) { |
950 | 950 |
_edge_maps[i]->copy(_from, edgeRefMap); |
951 | 951 |
} |
952 | 952 |
for (int i = 0; i < int(_arc_maps.size()); ++i) { |
953 | 953 |
_arc_maps[i]->copy(_from, arcRefMap); |
954 | 954 |
} |
955 | 955 |
} |
956 | 956 |
|
957 | 957 |
private: |
958 | 958 |
|
959 | 959 |
const From& _from; |
960 | 960 |
To& _to; |
961 | 961 |
|
962 | 962 |
std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* > |
963 | 963 |
_node_maps; |
964 | 964 |
|
965 | 965 |
std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* > |
966 | 966 |
_arc_maps; |
967 | 967 |
|
968 | 968 |
std::vector<_core_bits::MapCopyBase<From, Edge, EdgeRefMap>* > |
969 | 969 |
_edge_maps; |
970 | 970 |
|
971 | 971 |
}; |
972 | 972 |
|
973 | 973 |
/// \brief Copy a graph to another graph. |
974 | 974 |
/// |
975 | 975 |
/// This function copies a graph to another graph. |
976 | 976 |
/// The complete usage of it is detailed in the GraphCopy class, |
977 | 977 |
/// but a short example shows a basic work: |
978 | 978 |
///\code |
979 | 979 |
/// graphCopy(src, trg).nodeRef(nr).edgeCrossRef(ecr).run(); |
980 | 980 |
///\endcode |
981 | 981 |
/// |
982 | 982 |
/// After the copy the \c nr map will contain the mapping from the |
983 | 983 |
/// nodes of the \c from graph to the nodes of the \c to graph and |
984 | 984 |
/// \c ecr will contain the mapping from the edges of the \c to graph |
985 | 985 |
/// to the edges of the \c from graph. |
986 | 986 |
/// |
987 | 987 |
/// \see GraphCopy |
988 | 988 |
template <typename From, typename To> |
989 | 989 |
GraphCopy<From, To> |
990 | 990 |
graphCopy(const From& from, To& to) { |
991 | 991 |
return GraphCopy<From, To>(from, to); |
992 | 992 |
} |
993 | 993 |
|
994 | 994 |
namespace _core_bits { |
995 | 995 |
|
996 | 996 |
template <typename Graph, typename Enable = void> |
997 | 997 |
struct FindArcSelector { |
998 | 998 |
typedef typename Graph::Node Node; |
999 | 999 |
typedef typename Graph::Arc Arc; |
1000 | 1000 |
static Arc find(const Graph &g, Node u, Node v, Arc e) { |
1001 | 1001 |
if (e == INVALID) { |
1002 | 1002 |
g.firstOut(e, u); |
1003 | 1003 |
} else { |
1004 | 1004 |
g.nextOut(e); |
1005 | 1005 |
} |
1006 | 1006 |
while (e != INVALID && g.target(e) != v) { |
1007 | 1007 |
g.nextOut(e); |
1008 | 1008 |
} |
1009 | 1009 |
return e; |
1010 | 1010 |
} |
1011 | 1011 |
}; |
1012 | 1012 |
|
1013 | 1013 |
template <typename Graph> |
1014 | 1014 |
struct FindArcSelector< |
1015 | 1015 |
Graph, |
1016 | 1016 |
typename enable_if<typename Graph::FindArcTag, void>::type> |
1017 | 1017 |
{ |
1018 | 1018 |
typedef typename Graph::Node Node; |
1019 | 1019 |
typedef typename Graph::Arc Arc; |
1020 | 1020 |
static Arc find(const Graph &g, Node u, Node v, Arc prev) { |
1021 | 1021 |
return g.findArc(u, v, prev); |
1022 | 1022 |
} |
1023 | 1023 |
}; |
1024 | 1024 |
} |
1025 | 1025 |
|
1026 | 1026 |
/// \brief Find an arc between two nodes of a digraph. |
1027 | 1027 |
/// |
1028 | 1028 |
/// This function finds an arc from node \c u to node \c v in the |
1029 | 1029 |
/// digraph \c g. |
1030 | 1030 |
/// |
1031 | 1031 |
/// If \c prev is \ref INVALID (this is the default value), then |
1032 | 1032 |
/// it finds the first arc from \c u to \c v. Otherwise it looks for |
1033 | 1033 |
/// the next arc from \c u to \c v after \c prev. |
1034 | 1034 |
/// \return The found arc or \ref INVALID if there is no such an arc. |
1035 | 1035 |
/// |
1036 | 1036 |
/// Thus you can iterate through each arc from \c u to \c v as it follows. |
1037 | 1037 |
///\code |
1038 | 1038 |
/// for(Arc e = findArc(g,u,v); e != INVALID; e = findArc(g,u,v,e)) { |
1039 | 1039 |
/// ... |
1040 | 1040 |
/// } |
1041 | 1041 |
///\endcode |
1042 | 1042 |
/// |
1043 | 1043 |
/// \note \ref ConArcIt provides iterator interface for the same |
1044 | 1044 |
/// functionality. |
1045 | 1045 |
/// |
1046 | 1046 |
///\sa ConArcIt |
1047 | 1047 |
///\sa ArcLookUp, AllArcLookUp, DynArcLookUp |
1048 | 1048 |
template <typename Graph> |
1049 | 1049 |
inline typename Graph::Arc |
1050 | 1050 |
findArc(const Graph &g, typename Graph::Node u, typename Graph::Node v, |
1051 | 1051 |
typename Graph::Arc prev = INVALID) { |
1052 | 1052 |
return _core_bits::FindArcSelector<Graph>::find(g, u, v, prev); |
1053 | 1053 |
} |
1054 | 1054 |
|
1055 | 1055 |
/// \brief Iterator for iterating on parallel arcs connecting the same nodes. |
1056 | 1056 |
/// |
1057 | 1057 |
/// Iterator for iterating on parallel arcs connecting the same nodes. It is |
1058 | 1058 |
/// a higher level interface for the \ref findArc() function. You can |
1059 | 1059 |
/// use it the following way: |
1060 | 1060 |
///\code |
1061 | 1061 |
/// for (ConArcIt<Graph> it(g, src, trg); it != INVALID; ++it) { |
1062 | 1062 |
/// ... |
1063 | 1063 |
/// } |
1064 | 1064 |
///\endcode |
1065 | 1065 |
/// |
1066 | 1066 |
///\sa findArc() |
1067 | 1067 |
///\sa ArcLookUp, AllArcLookUp, DynArcLookUp |
1068 | 1068 |
template <typename GR> |
1069 | 1069 |
class ConArcIt : public GR::Arc { |
1070 | 1070 |
typedef typename GR::Arc Parent; |
1071 | 1071 |
|
1072 | 1072 |
public: |
1073 | 1073 |
|
1074 | 1074 |
typedef typename GR::Arc Arc; |
1075 | 1075 |
typedef typename GR::Node Node; |
1076 | 1076 |
|
1077 | 1077 |
/// \brief Constructor. |
1078 | 1078 |
/// |
1079 | 1079 |
/// Construct a new ConArcIt iterating on the arcs that |
1080 | 1080 |
/// connects nodes \c u and \c v. |
1081 | 1081 |
ConArcIt(const GR& g, Node u, Node v) : _graph(g) { |
1082 | 1082 |
Parent::operator=(findArc(_graph, u, v)); |
1083 | 1083 |
} |
1084 | 1084 |
|
1085 | 1085 |
/// \brief Constructor. |
1086 | 1086 |
/// |
1087 | 1087 |
/// Construct a new ConArcIt that continues the iterating from arc \c a. |
1088 | 1088 |
ConArcIt(const GR& g, Arc a) : Parent(a), _graph(g) {} |
1089 | 1089 |
|
1090 | 1090 |
/// \brief Increment operator. |
1091 | 1091 |
/// |
1092 | 1092 |
/// It increments the iterator and gives back the next arc. |
1093 | 1093 |
ConArcIt& operator++() { |
1094 | 1094 |
Parent::operator=(findArc(_graph, _graph.source(*this), |
1095 | 1095 |
_graph.target(*this), *this)); |
1096 | 1096 |
return *this; |
1097 | 1097 |
} |
1098 | 1098 |
private: |
1099 | 1099 |
const GR& _graph; |
1100 | 1100 |
}; |
1101 | 1101 |
|
1102 | 1102 |
namespace _core_bits { |
1103 | 1103 |
|
1104 | 1104 |
template <typename Graph, typename Enable = void> |
1105 | 1105 |
struct FindEdgeSelector { |
1106 | 1106 |
typedef typename Graph::Node Node; |
1107 | 1107 |
typedef typename Graph::Edge Edge; |
1108 | 1108 |
static Edge find(const Graph &g, Node u, Node v, Edge e) { |
1109 | 1109 |
bool b; |
1110 | 1110 |
if (u != v) { |
1111 | 1111 |
if (e == INVALID) { |
1112 | 1112 |
g.firstInc(e, b, u); |
1113 | 1113 |
} else { |
1114 | 1114 |
b = g.u(e) == u; |
1115 | 1115 |
g.nextInc(e, b); |
1116 | 1116 |
} |
1117 | 1117 |
while (e != INVALID && (b ? g.v(e) : g.u(e)) != v) { |
1118 | 1118 |
g.nextInc(e, b); |
1119 | 1119 |
} |
1120 | 1120 |
} else { |
1121 | 1121 |
if (e == INVALID) { |
1122 | 1122 |
g.firstInc(e, b, u); |
1123 | 1123 |
} else { |
1124 | 1124 |
b = true; |
1125 | 1125 |
g.nextInc(e, b); |
1126 | 1126 |
} |
1127 | 1127 |
while (e != INVALID && (!b || g.v(e) != v)) { |
1128 | 1128 |
g.nextInc(e, b); |
1129 | 1129 |
} |
1130 | 1130 |
} |
1131 | 1131 |
return e; |
1132 | 1132 |
} |
1133 | 1133 |
}; |
1134 | 1134 |
|
1135 | 1135 |
template <typename Graph> |
1136 | 1136 |
struct FindEdgeSelector< |
1137 | 1137 |
Graph, |
1138 | 1138 |
typename enable_if<typename Graph::FindEdgeTag, void>::type> |
1139 | 1139 |
{ |
1140 | 1140 |
typedef typename Graph::Node Node; |
1141 | 1141 |
typedef typename Graph::Edge Edge; |
1142 | 1142 |
static Edge find(const Graph &g, Node u, Node v, Edge prev) { |
1143 | 1143 |
return g.findEdge(u, v, prev); |
1144 | 1144 |
} |
1145 | 1145 |
}; |
1146 | 1146 |
} |
1147 | 1147 |
|
1148 | 1148 |
/// \brief Find an edge between two nodes of a graph. |
1149 | 1149 |
/// |
1150 | 1150 |
/// This function finds an edge from node \c u to node \c v in graph \c g. |
1151 | 1151 |
/// If node \c u and node \c v is equal then each loop edge |
1152 | 1152 |
/// will be enumerated once. |
1153 | 1153 |
/// |
1154 | 1154 |
/// If \c prev is \ref INVALID (this is the default value), then |
1155 | 1155 |
/// it finds the first edge from \c u to \c v. Otherwise it looks for |
1156 | 1156 |
/// the next edge from \c u to \c v after \c prev. |
1157 | 1157 |
/// \return The found edge or \ref INVALID if there is no such an edge. |
1158 | 1158 |
/// |
1159 | 1159 |
/// Thus you can iterate through each edge between \c u and \c v |
1160 | 1160 |
/// as it follows. |
1161 | 1161 |
///\code |
1162 | 1162 |
/// for(Edge e = findEdge(g,u,v); e != INVALID; e = findEdge(g,u,v,e)) { |
1163 | 1163 |
/// ... |
1164 | 1164 |
/// } |
1165 | 1165 |
///\endcode |
1166 | 1166 |
/// |
1167 | 1167 |
/// \note \ref ConEdgeIt provides iterator interface for the same |
1168 | 1168 |
/// functionality. |
1169 | 1169 |
/// |
1170 | 1170 |
///\sa ConEdgeIt |
1171 | 1171 |
template <typename Graph> |
1172 | 1172 |
inline typename Graph::Edge |
1173 | 1173 |
findEdge(const Graph &g, typename Graph::Node u, typename Graph::Node v, |
1174 | 1174 |
typename Graph::Edge p = INVALID) { |
1175 | 1175 |
return _core_bits::FindEdgeSelector<Graph>::find(g, u, v, p); |
1176 | 1176 |
} |
1177 | 1177 |
|
1178 | 1178 |
/// \brief Iterator for iterating on parallel edges connecting the same nodes. |
1179 | 1179 |
/// |
1180 | 1180 |
/// Iterator for iterating on parallel edges connecting the same nodes. |
1181 | 1181 |
/// It is a higher level interface for the findEdge() function. You can |
1182 | 1182 |
/// use it the following way: |
1183 | 1183 |
///\code |
1184 | 1184 |
/// for (ConEdgeIt<Graph> it(g, u, v); it != INVALID; ++it) { |
1185 | 1185 |
/// ... |
1186 | 1186 |
/// } |
1187 | 1187 |
///\endcode |
1188 | 1188 |
/// |
1189 | 1189 |
///\sa findEdge() |
1190 | 1190 |
template <typename GR> |
1191 | 1191 |
class ConEdgeIt : public GR::Edge { |
1192 | 1192 |
typedef typename GR::Edge Parent; |
1193 | 1193 |
|
1194 | 1194 |
public: |
1195 | 1195 |
|
1196 | 1196 |
typedef typename GR::Edge Edge; |
1197 | 1197 |
typedef typename GR::Node Node; |
1198 | 1198 |
|
1199 | 1199 |
/// \brief Constructor. |
1200 | 1200 |
/// |
1201 | 1201 |
/// Construct a new ConEdgeIt iterating on the edges that |
1202 | 1202 |
/// connects nodes \c u and \c v. |
1203 | 1203 |
ConEdgeIt(const GR& g, Node u, Node v) : _graph(g), _u(u), _v(v) { |
1204 | 1204 |
Parent::operator=(findEdge(_graph, _u, _v)); |
1205 | 1205 |
} |
1206 | 1206 |
|
1207 | 1207 |
/// \brief Constructor. |
1208 | 1208 |
/// |
1209 | 1209 |
/// Construct a new ConEdgeIt that continues iterating from edge \c e. |
1210 | 1210 |
ConEdgeIt(const GR& g, Edge e) : Parent(e), _graph(g) {} |
1211 | 1211 |
|
1212 | 1212 |
/// \brief Increment operator. |
1213 | 1213 |
/// |
1214 | 1214 |
/// It increments the iterator and gives back the next edge. |
1215 | 1215 |
ConEdgeIt& operator++() { |
1216 | 1216 |
Parent::operator=(findEdge(_graph, _u, _v, *this)); |
1217 | 1217 |
return *this; |
1218 | 1218 |
} |
1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2010 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
#ifndef LEMON_COST_SCALING_H |
20 | 20 |
#define LEMON_COST_SCALING_H |
21 | 21 |
|
22 | 22 |
/// \ingroup min_cost_flow_algs |
23 | 23 |
/// \file |
24 | 24 |
/// \brief Cost scaling algorithm for finding a minimum cost flow. |
25 | 25 |
|
26 | 26 |
#include <vector> |
27 | 27 |
#include <deque> |
28 | 28 |
#include <limits> |
29 | 29 |
|
30 | 30 |
#include <lemon/core.h> |
31 | 31 |
#include <lemon/maps.h> |
32 | 32 |
#include <lemon/math.h> |
33 | 33 |
#include <lemon/static_graph.h> |
34 | 34 |
#include <lemon/circulation.h> |
35 | 35 |
#include <lemon/bellman_ford.h> |
36 | 36 |
|
37 | 37 |
namespace lemon { |
38 | 38 |
|
39 | 39 |
/// \brief Default traits class of CostScaling algorithm. |
40 | 40 |
/// |
41 | 41 |
/// Default traits class of CostScaling algorithm. |
42 | 42 |
/// \tparam GR Digraph type. |
43 | 43 |
/// \tparam V The number type used for flow amounts, capacity bounds |
44 | 44 |
/// and supply values. By default it is \c int. |
45 | 45 |
/// \tparam C The number type used for costs and potentials. |
46 | 46 |
/// By default it is the same as \c V. |
47 | 47 |
#ifdef DOXYGEN |
48 | 48 |
template <typename GR, typename V = int, typename C = V> |
49 | 49 |
#else |
50 | 50 |
template < typename GR, typename V = int, typename C = V, |
51 | 51 |
bool integer = std::numeric_limits<C>::is_integer > |
52 | 52 |
#endif |
53 | 53 |
struct CostScalingDefaultTraits |
54 | 54 |
{ |
55 | 55 |
/// The type of the digraph |
56 | 56 |
typedef GR Digraph; |
57 | 57 |
/// The type of the flow amounts, capacity bounds and supply values |
58 | 58 |
typedef V Value; |
59 | 59 |
/// The type of the arc costs |
60 | 60 |
typedef C Cost; |
61 | 61 |
|
62 | 62 |
/// \brief The large cost type used for internal computations |
63 | 63 |
/// |
64 | 64 |
/// The large cost type used for internal computations. |
65 | 65 |
/// It is \c long \c long if the \c Cost type is integer, |
66 | 66 |
/// otherwise it is \c double. |
67 | 67 |
/// \c Cost must be convertible to \c LargeCost. |
68 | 68 |
typedef double LargeCost; |
69 | 69 |
}; |
70 | 70 |
|
71 | 71 |
// Default traits class for integer cost types |
72 | 72 |
template <typename GR, typename V, typename C> |
73 | 73 |
struct CostScalingDefaultTraits<GR, V, C, true> |
74 | 74 |
{ |
75 | 75 |
typedef GR Digraph; |
76 | 76 |
typedef V Value; |
77 | 77 |
typedef C Cost; |
78 | 78 |
#ifdef LEMON_HAVE_LONG_LONG |
79 | 79 |
typedef long long LargeCost; |
80 | 80 |
#else |
81 | 81 |
typedef long LargeCost; |
82 | 82 |
#endif |
83 | 83 |
}; |
84 | 84 |
|
85 | 85 |
|
86 | 86 |
/// \addtogroup min_cost_flow_algs |
87 | 87 |
/// @{ |
88 | 88 |
|
89 | 89 |
/// \brief Implementation of the Cost Scaling algorithm for |
90 | 90 |
/// finding a \ref min_cost_flow "minimum cost flow". |
91 | 91 |
/// |
92 | 92 |
/// \ref CostScaling implements a cost scaling algorithm that performs |
93 | 93 |
/// push/augment and relabel operations for finding a \ref min_cost_flow |
94 | 94 |
/// "minimum cost flow" \ref amo93networkflows, \ref goldberg90approximation, |
95 | 95 |
/// \ref goldberg97efficient, \ref bunnagel98efficient. |
96 | 96 |
/// It is a highly efficient primal-dual solution method, which |
97 | 97 |
/// can be viewed as the generalization of the \ref Preflow |
98 | 98 |
/// "preflow push-relabel" algorithm for the maximum flow problem. |
99 | 99 |
/// |
100 |
/// In general, \ref NetworkSimplex and \ref CostScaling are the fastest |
|
101 |
/// implementations available in LEMON for this problem. |
|
102 |
/// |
|
100 | 103 |
/// Most of the parameters of the problem (except for the digraph) |
101 | 104 |
/// can be given using separate functions, and the algorithm can be |
102 | 105 |
/// executed using the \ref run() function. If some parameters are not |
103 | 106 |
/// specified, then default values will be used. |
104 | 107 |
/// |
105 | 108 |
/// \tparam GR The digraph type the algorithm runs on. |
106 | 109 |
/// \tparam V The number type used for flow amounts, capacity bounds |
107 | 110 |
/// and supply values in the algorithm. By default, it is \c int. |
108 | 111 |
/// \tparam C The number type used for costs and potentials in the |
109 | 112 |
/// algorithm. By default, it is the same as \c V. |
110 | 113 |
/// \tparam TR The traits class that defines various types used by the |
111 | 114 |
/// algorithm. By default, it is \ref CostScalingDefaultTraits |
112 | 115 |
/// "CostScalingDefaultTraits<GR, V, C>". |
113 | 116 |
/// In most cases, this parameter should not be set directly, |
114 | 117 |
/// consider to use the named template parameters instead. |
115 | 118 |
/// |
116 | 119 |
/// \warning Both \c V and \c C must be signed number types. |
117 | 120 |
/// \warning All input data (capacities, supply values, and costs) must |
118 | 121 |
/// be integer. |
119 |
/// \warning This algorithm does not support negative costs for such |
|
120 |
/// arcs that have infinite upper bound. |
|
122 |
/// \warning This algorithm does not support negative costs for |
|
123 |
/// arcs having infinite upper bound. |
|
121 | 124 |
/// |
122 | 125 |
/// \note %CostScaling provides three different internal methods, |
123 | 126 |
/// from which the most efficient one is used by default. |
124 | 127 |
/// For more information, see \ref Method. |
125 | 128 |
#ifdef DOXYGEN |
126 | 129 |
template <typename GR, typename V, typename C, typename TR> |
127 | 130 |
#else |
128 | 131 |
template < typename GR, typename V = int, typename C = V, |
129 | 132 |
typename TR = CostScalingDefaultTraits<GR, V, C> > |
130 | 133 |
#endif |
131 | 134 |
class CostScaling |
132 | 135 |
{ |
133 | 136 |
public: |
134 | 137 |
|
135 | 138 |
/// The type of the digraph |
136 | 139 |
typedef typename TR::Digraph Digraph; |
137 | 140 |
/// The type of the flow amounts, capacity bounds and supply values |
138 | 141 |
typedef typename TR::Value Value; |
139 | 142 |
/// The type of the arc costs |
140 | 143 |
typedef typename TR::Cost Cost; |
141 | 144 |
|
142 | 145 |
/// \brief The large cost type |
143 | 146 |
/// |
144 | 147 |
/// The large cost type used for internal computations. |
145 | 148 |
/// By default, it is \c long \c long if the \c Cost type is integer, |
146 | 149 |
/// otherwise it is \c double. |
147 | 150 |
typedef typename TR::LargeCost LargeCost; |
148 | 151 |
|
149 | 152 |
/// The \ref CostScalingDefaultTraits "traits class" of the algorithm |
150 | 153 |
typedef TR Traits; |
151 | 154 |
|
152 | 155 |
public: |
153 | 156 |
|
154 | 157 |
/// \brief Problem type constants for the \c run() function. |
155 | 158 |
/// |
156 | 159 |
/// Enum type containing the problem type constants that can be |
157 | 160 |
/// returned by the \ref run() function of the algorithm. |
158 | 161 |
enum ProblemType { |
159 | 162 |
/// The problem has no feasible solution (flow). |
160 | 163 |
INFEASIBLE, |
161 | 164 |
/// The problem has optimal solution (i.e. it is feasible and |
162 | 165 |
/// bounded), and the algorithm has found optimal flow and node |
163 | 166 |
/// potentials (primal and dual solutions). |
164 | 167 |
OPTIMAL, |
165 | 168 |
/// The digraph contains an arc of negative cost and infinite |
166 | 169 |
/// upper bound. It means that the objective function is unbounded |
167 | 170 |
/// on that arc, however, note that it could actually be bounded |
168 | 171 |
/// over the feasible flows, but this algroithm cannot handle |
169 | 172 |
/// these cases. |
170 | 173 |
UNBOUNDED |
171 | 174 |
}; |
172 | 175 |
|
173 | 176 |
/// \brief Constants for selecting the internal method. |
174 | 177 |
/// |
175 | 178 |
/// Enum type containing constants for selecting the internal method |
176 | 179 |
/// for the \ref run() function. |
177 | 180 |
/// |
178 | 181 |
/// \ref CostScaling provides three internal methods that differ mainly |
179 | 182 |
/// in their base operations, which are used in conjunction with the |
180 | 183 |
/// relabel operation. |
181 | 184 |
/// By default, the so called \ref PARTIAL_AUGMENT |
182 |
/// "Partial Augment-Relabel" method is used, which |
|
185 |
/// "Partial Augment-Relabel" method is used, which turned out to be |
|
183 | 186 |
/// the most efficient and the most robust on various test inputs. |
184 | 187 |
/// However, the other methods can be selected using the \ref run() |
185 | 188 |
/// function with the proper parameter. |
186 | 189 |
enum Method { |
187 | 190 |
/// Local push operations are used, i.e. flow is moved only on one |
188 | 191 |
/// admissible arc at once. |
189 | 192 |
PUSH, |
190 | 193 |
/// Augment operations are used, i.e. flow is moved on admissible |
191 | 194 |
/// paths from a node with excess to a node with deficit. |
192 | 195 |
AUGMENT, |
193 | 196 |
/// Partial augment operations are used, i.e. flow is moved on |
194 | 197 |
/// admissible paths started from a node with excess, but the |
195 | 198 |
/// lengths of these paths are limited. This method can be viewed |
196 | 199 |
/// as a combined version of the previous two operations. |
197 | 200 |
PARTIAL_AUGMENT |
198 | 201 |
}; |
199 | 202 |
|
200 | 203 |
private: |
201 | 204 |
|
202 | 205 |
TEMPLATE_DIGRAPH_TYPEDEFS(GR); |
203 | 206 |
|
204 | 207 |
typedef std::vector<int> IntVector; |
205 | 208 |
typedef std::vector<Value> ValueVector; |
206 | 209 |
typedef std::vector<Cost> CostVector; |
207 | 210 |
typedef std::vector<LargeCost> LargeCostVector; |
208 | 211 |
typedef std::vector<char> BoolVector; |
209 | 212 |
// Note: vector<char> is used instead of vector<bool> for efficiency reasons |
210 | 213 |
|
211 | 214 |
private: |
212 | 215 |
|
213 | 216 |
template <typename KT, typename VT> |
214 | 217 |
class StaticVectorMap { |
215 | 218 |
public: |
216 | 219 |
typedef KT Key; |
217 | 220 |
typedef VT Value; |
218 | 221 |
|
219 | 222 |
StaticVectorMap(std::vector<Value>& v) : _v(v) {} |
220 | 223 |
|
221 | 224 |
const Value& operator[](const Key& key) const { |
222 | 225 |
return _v[StaticDigraph::id(key)]; |
223 | 226 |
} |
224 | 227 |
|
225 | 228 |
Value& operator[](const Key& key) { |
226 | 229 |
return _v[StaticDigraph::id(key)]; |
227 | 230 |
} |
228 | 231 |
|
229 | 232 |
void set(const Key& key, const Value& val) { |
230 | 233 |
_v[StaticDigraph::id(key)] = val; |
231 | 234 |
} |
232 | 235 |
|
233 | 236 |
private: |
234 | 237 |
std::vector<Value>& _v; |
235 | 238 |
}; |
236 | 239 |
|
237 | 240 |
typedef StaticVectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap; |
238 | 241 |
typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap; |
239 | 242 |
|
240 | 243 |
private: |
241 | 244 |
|
242 | 245 |
// Data related to the underlying digraph |
243 | 246 |
const GR &_graph; |
244 | 247 |
int _node_num; |
245 | 248 |
int _arc_num; |
246 | 249 |
int _res_node_num; |
247 | 250 |
int _res_arc_num; |
248 | 251 |
int _root; |
249 | 252 |
|
250 | 253 |
// Parameters of the problem |
251 | 254 |
bool _have_lower; |
252 | 255 |
Value _sum_supply; |
253 | 256 |
int _sup_node_num; |
254 | 257 |
|
255 | 258 |
// Data structures for storing the digraph |
256 | 259 |
IntNodeMap _node_id; |
257 | 260 |
IntArcMap _arc_idf; |
258 | 261 |
IntArcMap _arc_idb; |
259 | 262 |
IntVector _first_out; |
260 | 263 |
BoolVector _forward; |
261 | 264 |
IntVector _source; |
262 | 265 |
IntVector _target; |
263 | 266 |
IntVector _reverse; |
264 | 267 |
|
265 | 268 |
// Node and arc data |
266 | 269 |
ValueVector _lower; |
267 | 270 |
ValueVector _upper; |
268 | 271 |
CostVector _scost; |
269 | 272 |
ValueVector _supply; |
270 | 273 |
|
271 | 274 |
ValueVector _res_cap; |
272 | 275 |
LargeCostVector _cost; |
273 | 276 |
LargeCostVector _pi; |
274 | 277 |
ValueVector _excess; |
275 | 278 |
IntVector _next_out; |
276 | 279 |
std::deque<int> _active_nodes; |
277 | 280 |
|
278 | 281 |
// Data for scaling |
279 | 282 |
LargeCost _epsilon; |
280 | 283 |
int _alpha; |
281 | 284 |
|
282 | 285 |
IntVector _buckets; |
283 | 286 |
IntVector _bucket_next; |
284 | 287 |
IntVector _bucket_prev; |
285 | 288 |
IntVector _rank; |
286 | 289 |
int _max_rank; |
287 | 290 |
|
288 | 291 |
// Data for a StaticDigraph structure |
289 | 292 |
typedef std::pair<int, int> IntPair; |
290 | 293 |
StaticDigraph _sgr; |
291 | 294 |
std::vector<IntPair> _arc_vec; |
292 | 295 |
std::vector<LargeCost> _cost_vec; |
293 | 296 |
LargeCostArcMap _cost_map; |
294 | 297 |
LargeCostNodeMap _pi_map; |
295 | 298 |
|
296 | 299 |
public: |
297 | 300 |
|
298 | 301 |
/// \brief Constant for infinite upper bounds (capacities). |
299 | 302 |
/// |
300 | 303 |
/// Constant for infinite upper bounds (capacities). |
301 | 304 |
/// It is \c std::numeric_limits<Value>::infinity() if available, |
302 | 305 |
/// \c std::numeric_limits<Value>::max() otherwise. |
303 | 306 |
const Value INF; |
304 | 307 |
|
305 | 308 |
public: |
306 | 309 |
|
307 | 310 |
/// \name Named Template Parameters |
308 | 311 |
/// @{ |
309 | 312 |
|
310 | 313 |
template <typename T> |
311 | 314 |
struct SetLargeCostTraits : public Traits { |
312 | 315 |
typedef T LargeCost; |
313 | 316 |
}; |
314 | 317 |
|
315 | 318 |
/// \brief \ref named-templ-param "Named parameter" for setting |
316 | 319 |
/// \c LargeCost type. |
317 | 320 |
/// |
318 | 321 |
/// \ref named-templ-param "Named parameter" for setting \c LargeCost |
319 | 322 |
/// type, which is used for internal computations in the algorithm. |
320 | 323 |
/// \c Cost must be convertible to \c LargeCost. |
321 | 324 |
template <typename T> |
322 | 325 |
struct SetLargeCost |
323 | 326 |
: public CostScaling<GR, V, C, SetLargeCostTraits<T> > { |
324 | 327 |
typedef CostScaling<GR, V, C, SetLargeCostTraits<T> > Create; |
325 | 328 |
}; |
326 | 329 |
|
327 | 330 |
/// @} |
328 | 331 |
|
329 | 332 |
protected: |
330 | 333 |
|
331 | 334 |
CostScaling() {} |
332 | 335 |
|
333 | 336 |
public: |
334 | 337 |
|
335 | 338 |
/// \brief Constructor. |
336 | 339 |
/// |
337 | 340 |
/// The constructor of the class. |
338 | 341 |
/// |
339 | 342 |
/// \param graph The digraph the algorithm runs on. |
340 | 343 |
CostScaling(const GR& graph) : |
341 | 344 |
_graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph), |
342 | 345 |
_cost_map(_cost_vec), _pi_map(_pi), |
343 | 346 |
INF(std::numeric_limits<Value>::has_infinity ? |
344 | 347 |
std::numeric_limits<Value>::infinity() : |
345 | 348 |
std::numeric_limits<Value>::max()) |
346 | 349 |
{ |
347 | 350 |
// Check the number types |
348 | 351 |
LEMON_ASSERT(std::numeric_limits<Value>::is_signed, |
349 | 352 |
"The flow type of CostScaling must be signed"); |
350 | 353 |
LEMON_ASSERT(std::numeric_limits<Cost>::is_signed, |
351 | 354 |
"The cost type of CostScaling must be signed"); |
352 | 355 |
|
353 | 356 |
// Reset data structures |
354 | 357 |
reset(); |
355 | 358 |
} |
356 | 359 |
|
357 | 360 |
/// \name Parameters |
358 | 361 |
/// The parameters of the algorithm can be specified using these |
359 | 362 |
/// functions. |
360 | 363 |
|
361 | 364 |
/// @{ |
362 | 365 |
|
363 | 366 |
/// \brief Set the lower bounds on the arcs. |
364 | 367 |
/// |
365 | 368 |
/// This function sets the lower bounds on the arcs. |
366 | 369 |
/// If it is not used before calling \ref run(), the lower bounds |
367 | 370 |
/// will be set to zero on all arcs. |
368 | 371 |
/// |
369 | 372 |
/// \param map An arc map storing the lower bounds. |
370 | 373 |
/// Its \c Value type must be convertible to the \c Value type |
371 | 374 |
/// of the algorithm. |
372 | 375 |
/// |
373 | 376 |
/// \return <tt>(*this)</tt> |
374 | 377 |
template <typename LowerMap> |
375 | 378 |
CostScaling& lowerMap(const LowerMap& map) { |
376 | 379 |
_have_lower = true; |
377 | 380 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
378 | 381 |
_lower[_arc_idf[a]] = map[a]; |
379 | 382 |
_lower[_arc_idb[a]] = map[a]; |
380 | 383 |
} |
381 | 384 |
return *this; |
382 | 385 |
} |
383 | 386 |
|
384 | 387 |
/// \brief Set the upper bounds (capacities) on the arcs. |
385 | 388 |
/// |
386 | 389 |
/// This function sets the upper bounds (capacities) on the arcs. |
387 | 390 |
/// If it is not used before calling \ref run(), the upper bounds |
388 | 391 |
/// will be set to \ref INF on all arcs (i.e. the flow value will be |
389 | 392 |
/// unbounded from above). |
390 | 393 |
/// |
391 | 394 |
/// \param map An arc map storing the upper bounds. |
392 | 395 |
/// Its \c Value type must be convertible to the \c Value type |
393 | 396 |
/// of the algorithm. |
394 | 397 |
/// |
395 | 398 |
/// \return <tt>(*this)</tt> |
396 | 399 |
template<typename UpperMap> |
397 | 400 |
CostScaling& upperMap(const UpperMap& map) { |
398 | 401 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
399 | 402 |
_upper[_arc_idf[a]] = map[a]; |
400 | 403 |
} |
401 | 404 |
return *this; |
402 | 405 |
} |
403 | 406 |
|
404 | 407 |
/// \brief Set the costs of the arcs. |
405 | 408 |
/// |
406 | 409 |
/// This function sets the costs of the arcs. |
407 | 410 |
/// If it is not used before calling \ref run(), the costs |
408 | 411 |
/// will be set to \c 1 on all arcs. |
409 | 412 |
/// |
410 | 413 |
/// \param map An arc map storing the costs. |
411 | 414 |
/// Its \c Value type must be convertible to the \c Cost type |
412 | 415 |
/// of the algorithm. |
413 | 416 |
/// |
414 | 417 |
/// \return <tt>(*this)</tt> |
415 | 418 |
template<typename CostMap> |
416 | 419 |
CostScaling& costMap(const CostMap& map) { |
417 | 420 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
418 | 421 |
_scost[_arc_idf[a]] = map[a]; |
419 | 422 |
_scost[_arc_idb[a]] = -map[a]; |
420 | 423 |
} |
421 | 424 |
return *this; |
422 | 425 |
} |
423 | 426 |
|
424 | 427 |
/// \brief Set the supply values of the nodes. |
425 | 428 |
/// |
426 | 429 |
/// This function sets the supply values of the nodes. |
427 | 430 |
/// If neither this function nor \ref stSupply() is used before |
428 | 431 |
/// calling \ref run(), the supply of each node will be set to zero. |
429 | 432 |
/// |
430 | 433 |
/// \param map A node map storing the supply values. |
431 | 434 |
/// Its \c Value type must be convertible to the \c Value type |
432 | 435 |
/// of the algorithm. |
433 | 436 |
/// |
434 | 437 |
/// \return <tt>(*this)</tt> |
435 | 438 |
template<typename SupplyMap> |
436 | 439 |
CostScaling& supplyMap(const SupplyMap& map) { |
437 | 440 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
438 | 441 |
_supply[_node_id[n]] = map[n]; |
439 | 442 |
} |
440 | 443 |
return *this; |
441 | 444 |
} |
442 | 445 |
|
443 | 446 |
/// \brief Set single source and target nodes and a supply value. |
444 | 447 |
/// |
445 | 448 |
/// This function sets a single source node and a single target node |
446 | 449 |
/// and the required flow value. |
447 | 450 |
/// If neither this function nor \ref supplyMap() is used before |
448 | 451 |
/// calling \ref run(), the supply of each node will be set to zero. |
449 | 452 |
/// |
450 | 453 |
/// Using this function has the same effect as using \ref supplyMap() |
451 |
/// with |
|
454 |
/// with a map in which \c k is assigned to \c s, \c -k is |
|
452 | 455 |
/// assigned to \c t and all other nodes have zero supply value. |
453 | 456 |
/// |
454 | 457 |
/// \param s The source node. |
455 | 458 |
/// \param t The target node. |
456 | 459 |
/// \param k The required amount of flow from node \c s to node \c t |
457 | 460 |
/// (i.e. the supply of \c s and the demand of \c t). |
458 | 461 |
/// |
459 | 462 |
/// \return <tt>(*this)</tt> |
460 | 463 |
CostScaling& stSupply(const Node& s, const Node& t, Value k) { |
461 | 464 |
for (int i = 0; i != _res_node_num; ++i) { |
462 | 465 |
_supply[i] = 0; |
463 | 466 |
} |
464 | 467 |
_supply[_node_id[s]] = k; |
465 | 468 |
_supply[_node_id[t]] = -k; |
466 | 469 |
return *this; |
467 | 470 |
} |
468 | 471 |
|
469 | 472 |
/// @} |
470 | 473 |
|
471 | 474 |
/// \name Execution control |
472 | 475 |
/// The algorithm can be executed using \ref run(). |
473 | 476 |
|
474 | 477 |
/// @{ |
475 | 478 |
|
476 | 479 |
/// \brief Run the algorithm. |
477 | 480 |
/// |
478 | 481 |
/// This function runs the algorithm. |
479 | 482 |
/// The paramters can be specified using functions \ref lowerMap(), |
480 | 483 |
/// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). |
481 | 484 |
/// For example, |
482 | 485 |
/// \code |
483 | 486 |
/// CostScaling<ListDigraph> cs(graph); |
484 | 487 |
/// cs.lowerMap(lower).upperMap(upper).costMap(cost) |
485 | 488 |
/// .supplyMap(sup).run(); |
486 | 489 |
/// \endcode |
487 | 490 |
/// |
488 | 491 |
/// This function can be called more than once. All the given parameters |
489 | 492 |
/// are kept for the next call, unless \ref resetParams() or \ref reset() |
490 | 493 |
/// is used, thus only the modified parameters have to be set again. |
491 | 494 |
/// If the underlying digraph was also modified after the construction |
492 | 495 |
/// of the class (or the last \ref reset() call), then the \ref reset() |
493 | 496 |
/// function must be called. |
494 | 497 |
/// |
495 | 498 |
/// \param method The internal method that will be used in the |
496 | 499 |
/// algorithm. For more information, see \ref Method. |
497 | 500 |
/// \param factor The cost scaling factor. It must be larger than one. |
498 | 501 |
/// |
499 | 502 |
/// \return \c INFEASIBLE if no feasible flow exists, |
500 | 503 |
/// \n \c OPTIMAL if the problem has optimal solution |
501 | 504 |
/// (i.e. it is feasible and bounded), and the algorithm has found |
502 | 505 |
/// optimal flow and node potentials (primal and dual solutions), |
503 | 506 |
/// \n \c UNBOUNDED if the digraph contains an arc of negative cost |
504 | 507 |
/// and infinite upper bound. It means that the objective function |
505 | 508 |
/// is unbounded on that arc, however, note that it could actually be |
506 | 509 |
/// bounded over the feasible flows, but this algroithm cannot handle |
507 | 510 |
/// these cases. |
508 | 511 |
/// |
509 | 512 |
/// \see ProblemType, Method |
510 | 513 |
/// \see resetParams(), reset() |
511 | 514 |
ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) { |
512 | 515 |
_alpha = factor; |
513 | 516 |
ProblemType pt = init(); |
514 | 517 |
if (pt != OPTIMAL) return pt; |
515 | 518 |
start(method); |
516 | 519 |
return OPTIMAL; |
517 | 520 |
} |
518 | 521 |
|
519 | 522 |
/// \brief Reset all the parameters that have been given before. |
520 | 523 |
/// |
521 | 524 |
/// This function resets all the paramaters that have been given |
522 | 525 |
/// before using functions \ref lowerMap(), \ref upperMap(), |
523 | 526 |
/// \ref costMap(), \ref supplyMap(), \ref stSupply(). |
524 | 527 |
/// |
525 | 528 |
/// It is useful for multiple \ref run() calls. Basically, all the given |
526 | 529 |
/// parameters are kept for the next \ref run() call, unless |
527 | 530 |
/// \ref resetParams() or \ref reset() is used. |
528 | 531 |
/// If the underlying digraph was also modified after the construction |
529 | 532 |
/// of the class or the last \ref reset() call, then the \ref reset() |
530 | 533 |
/// function must be used, otherwise \ref resetParams() is sufficient. |
531 | 534 |
/// |
532 | 535 |
/// For example, |
533 | 536 |
/// \code |
534 | 537 |
/// CostScaling<ListDigraph> cs(graph); |
535 | 538 |
/// |
536 | 539 |
/// // First run |
537 | 540 |
/// cs.lowerMap(lower).upperMap(upper).costMap(cost) |
538 | 541 |
/// .supplyMap(sup).run(); |
539 | 542 |
/// |
540 | 543 |
/// // Run again with modified cost map (resetParams() is not called, |
541 | 544 |
/// // so only the cost map have to be set again) |
542 | 545 |
/// cost[e] += 100; |
543 | 546 |
/// cs.costMap(cost).run(); |
544 | 547 |
/// |
545 | 548 |
/// // Run again from scratch using resetParams() |
546 | 549 |
/// // (the lower bounds will be set to zero on all arcs) |
547 | 550 |
/// cs.resetParams(); |
548 | 551 |
/// cs.upperMap(capacity).costMap(cost) |
549 | 552 |
/// .supplyMap(sup).run(); |
550 | 553 |
/// \endcode |
551 | 554 |
/// |
552 | 555 |
/// \return <tt>(*this)</tt> |
553 | 556 |
/// |
554 | 557 |
/// \see reset(), run() |
555 | 558 |
CostScaling& resetParams() { |
556 | 559 |
for (int i = 0; i != _res_node_num; ++i) { |
557 | 560 |
_supply[i] = 0; |
558 | 561 |
} |
559 | 562 |
int limit = _first_out[_root]; |
560 | 563 |
for (int j = 0; j != limit; ++j) { |
561 | 564 |
_lower[j] = 0; |
562 | 565 |
_upper[j] = INF; |
563 | 566 |
_scost[j] = _forward[j] ? 1 : -1; |
564 | 567 |
} |
565 | 568 |
for (int j = limit; j != _res_arc_num; ++j) { |
566 | 569 |
_lower[j] = 0; |
567 | 570 |
_upper[j] = INF; |
568 | 571 |
_scost[j] = 0; |
569 | 572 |
_scost[_reverse[j]] = 0; |
570 | 573 |
} |
571 | 574 |
_have_lower = false; |
572 | 575 |
return *this; |
573 | 576 |
} |
574 | 577 |
|
575 | 578 |
/// \brief Reset all the parameters that have been given before. |
576 | 579 |
/// |
577 | 580 |
/// This function resets all the paramaters that have been given |
578 | 581 |
/// before using functions \ref lowerMap(), \ref upperMap(), |
579 | 582 |
/// \ref costMap(), \ref supplyMap(), \ref stSupply(). |
580 | 583 |
/// |
581 | 584 |
/// It is useful for multiple run() calls. If this function is not |
582 | 585 |
/// used, all the parameters given before are kept for the next |
583 | 586 |
/// \ref run() call. |
584 | 587 |
/// However, the underlying digraph must not be modified after this |
585 | 588 |
/// class have been constructed, since it copies and extends the graph. |
586 | 589 |
/// \return <tt>(*this)</tt> |
587 | 590 |
CostScaling& reset() { |
588 | 591 |
// Resize vectors |
589 | 592 |
_node_num = countNodes(_graph); |
590 | 593 |
_arc_num = countArcs(_graph); |
591 | 594 |
_res_node_num = _node_num + 1; |
592 | 595 |
_res_arc_num = 2 * (_arc_num + _node_num); |
593 | 596 |
_root = _node_num; |
594 | 597 |
|
595 | 598 |
_first_out.resize(_res_node_num + 1); |
596 | 599 |
_forward.resize(_res_arc_num); |
597 | 600 |
_source.resize(_res_arc_num); |
598 | 601 |
_target.resize(_res_arc_num); |
599 | 602 |
_reverse.resize(_res_arc_num); |
600 | 603 |
|
601 | 604 |
_lower.resize(_res_arc_num); |
602 | 605 |
_upper.resize(_res_arc_num); |
603 | 606 |
_scost.resize(_res_arc_num); |
604 | 607 |
_supply.resize(_res_node_num); |
605 | 608 |
|
606 | 609 |
_res_cap.resize(_res_arc_num); |
607 | 610 |
_cost.resize(_res_arc_num); |
608 | 611 |
_pi.resize(_res_node_num); |
609 | 612 |
_excess.resize(_res_node_num); |
610 | 613 |
_next_out.resize(_res_node_num); |
611 | 614 |
|
612 | 615 |
_arc_vec.reserve(_res_arc_num); |
613 | 616 |
_cost_vec.reserve(_res_arc_num); |
614 | 617 |
|
615 | 618 |
// Copy the graph |
616 | 619 |
int i = 0, j = 0, k = 2 * _arc_num + _node_num; |
617 | 620 |
for (NodeIt n(_graph); n != INVALID; ++n, ++i) { |
618 | 621 |
_node_id[n] = i; |
619 | 622 |
} |
620 | 623 |
i = 0; |
621 | 624 |
for (NodeIt n(_graph); n != INVALID; ++n, ++i) { |
622 | 625 |
_first_out[i] = j; |
623 | 626 |
for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) { |
624 | 627 |
_arc_idf[a] = j; |
625 | 628 |
_forward[j] = true; |
626 | 629 |
_source[j] = i; |
627 | 630 |
_target[j] = _node_id[_graph.runningNode(a)]; |
628 | 631 |
} |
629 | 632 |
for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) { |
630 | 633 |
_arc_idb[a] = j; |
631 | 634 |
_forward[j] = false; |
632 | 635 |
_source[j] = i; |
633 | 636 |
_target[j] = _node_id[_graph.runningNode(a)]; |
634 | 637 |
} |
635 | 638 |
_forward[j] = false; |
636 | 639 |
_source[j] = i; |
637 | 640 |
_target[j] = _root; |
638 | 641 |
_reverse[j] = k; |
639 | 642 |
_forward[k] = true; |
640 | 643 |
_source[k] = _root; |
641 | 644 |
_target[k] = i; |
642 | 645 |
_reverse[k] = j; |
643 | 646 |
++j; ++k; |
644 | 647 |
} |
645 | 648 |
_first_out[i] = j; |
646 | 649 |
_first_out[_res_node_num] = k; |
647 | 650 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
648 | 651 |
int fi = _arc_idf[a]; |
649 | 652 |
int bi = _arc_idb[a]; |
650 | 653 |
_reverse[fi] = bi; |
651 | 654 |
_reverse[bi] = fi; |
652 | 655 |
} |
653 | 656 |
|
654 | 657 |
// Reset parameters |
655 | 658 |
resetParams(); |
656 | 659 |
return *this; |
657 | 660 |
} |
658 | 661 |
|
659 | 662 |
/// @} |
660 | 663 |
|
661 | 664 |
/// \name Query Functions |
662 | 665 |
/// The results of the algorithm can be obtained using these |
663 | 666 |
/// functions.\n |
664 | 667 |
/// The \ref run() function must be called before using them. |
665 | 668 |
|
666 | 669 |
/// @{ |
667 | 670 |
|
668 | 671 |
/// \brief Return the total cost of the found flow. |
669 | 672 |
/// |
670 | 673 |
/// This function returns the total cost of the found flow. |
671 | 674 |
/// Its complexity is O(e). |
672 | 675 |
/// |
673 | 676 |
/// \note The return type of the function can be specified as a |
674 | 677 |
/// template parameter. For example, |
675 | 678 |
/// \code |
676 | 679 |
/// cs.totalCost<double>(); |
677 | 680 |
/// \endcode |
678 | 681 |
/// It is useful if the total cost cannot be stored in the \c Cost |
679 | 682 |
/// type of the algorithm, which is the default return type of the |
680 | 683 |
/// function. |
681 | 684 |
/// |
682 | 685 |
/// \pre \ref run() must be called before using this function. |
683 | 686 |
template <typename Number> |
684 | 687 |
Number totalCost() const { |
685 | 688 |
Number c = 0; |
686 | 689 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
687 | 690 |
int i = _arc_idb[a]; |
688 | 691 |
c += static_cast<Number>(_res_cap[i]) * |
689 | 692 |
(-static_cast<Number>(_scost[i])); |
690 | 693 |
} |
691 | 694 |
return c; |
692 | 695 |
} |
693 | 696 |
|
694 | 697 |
#ifndef DOXYGEN |
695 | 698 |
Cost totalCost() const { |
696 | 699 |
return totalCost<Cost>(); |
697 | 700 |
} |
698 | 701 |
#endif |
699 | 702 |
|
700 | 703 |
/// \brief Return the flow on the given arc. |
701 | 704 |
/// |
702 | 705 |
/// This function returns the flow on the given arc. |
703 | 706 |
/// |
704 | 707 |
/// \pre \ref run() must be called before using this function. |
705 | 708 |
Value flow(const Arc& a) const { |
706 | 709 |
return _res_cap[_arc_idb[a]]; |
707 | 710 |
} |
708 | 711 |
|
709 | 712 |
/// \brief Return the flow map (the primal solution). |
710 | 713 |
/// |
711 | 714 |
/// This function copies the flow value on each arc into the given |
712 | 715 |
/// map. The \c Value type of the algorithm must be convertible to |
713 | 716 |
/// the \c Value type of the map. |
714 | 717 |
/// |
715 | 718 |
/// \pre \ref run() must be called before using this function. |
716 | 719 |
template <typename FlowMap> |
717 | 720 |
void flowMap(FlowMap &map) const { |
718 | 721 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
719 | 722 |
map.set(a, _res_cap[_arc_idb[a]]); |
720 | 723 |
} |
721 | 724 |
} |
722 | 725 |
|
723 | 726 |
/// \brief Return the potential (dual value) of the given node. |
724 | 727 |
/// |
725 | 728 |
/// This function returns the potential (dual value) of the |
726 | 729 |
/// given node. |
727 | 730 |
/// |
728 | 731 |
/// \pre \ref run() must be called before using this function. |
729 | 732 |
Cost potential(const Node& n) const { |
730 | 733 |
return static_cast<Cost>(_pi[_node_id[n]]); |
731 | 734 |
} |
732 | 735 |
|
733 | 736 |
/// \brief Return the potential map (the dual solution). |
734 | 737 |
/// |
735 | 738 |
/// This function copies the potential (dual value) of each node |
736 | 739 |
/// into the given map. |
737 | 740 |
/// The \c Cost type of the algorithm must be convertible to the |
738 | 741 |
/// \c Value type of the map. |
739 | 742 |
/// |
740 | 743 |
/// \pre \ref run() must be called before using this function. |
741 | 744 |
template <typename PotentialMap> |
742 | 745 |
void potentialMap(PotentialMap &map) const { |
743 | 746 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
744 | 747 |
map.set(n, static_cast<Cost>(_pi[_node_id[n]])); |
745 | 748 |
} |
746 | 749 |
} |
747 | 750 |
|
748 | 751 |
/// @} |
749 | 752 |
|
750 | 753 |
private: |
751 | 754 |
|
752 | 755 |
// Initialize the algorithm |
753 | 756 |
ProblemType init() { |
754 | 757 |
if (_res_node_num <= 1) return INFEASIBLE; |
755 | 758 |
|
756 | 759 |
// Check the sum of supply values |
757 | 760 |
_sum_supply = 0; |
758 | 761 |
for (int i = 0; i != _root; ++i) { |
759 | 762 |
_sum_supply += _supply[i]; |
760 | 763 |
} |
761 | 764 |
if (_sum_supply > 0) return INFEASIBLE; |
762 | 765 |
|
763 | 766 |
|
764 | 767 |
// Initialize vectors |
765 | 768 |
for (int i = 0; i != _res_node_num; ++i) { |
766 | 769 |
_pi[i] = 0; |
767 | 770 |
_excess[i] = _supply[i]; |
768 | 771 |
} |
769 | 772 |
|
770 | 773 |
// Remove infinite upper bounds and check negative arcs |
771 | 774 |
const Value MAX = std::numeric_limits<Value>::max(); |
772 | 775 |
int last_out; |
773 | 776 |
if (_have_lower) { |
774 | 777 |
for (int i = 0; i != _root; ++i) { |
775 | 778 |
last_out = _first_out[i+1]; |
776 | 779 |
for (int j = _first_out[i]; j != last_out; ++j) { |
777 | 780 |
if (_forward[j]) { |
778 | 781 |
Value c = _scost[j] < 0 ? _upper[j] : _lower[j]; |
779 | 782 |
if (c >= MAX) return UNBOUNDED; |
780 | 783 |
_excess[i] -= c; |
781 | 784 |
_excess[_target[j]] += c; |
782 | 785 |
} |
783 | 786 |
} |
784 | 787 |
} |
785 | 788 |
} else { |
786 | 789 |
for (int i = 0; i != _root; ++i) { |
787 | 790 |
last_out = _first_out[i+1]; |
788 | 791 |
for (int j = _first_out[i]; j != last_out; ++j) { |
789 | 792 |
if (_forward[j] && _scost[j] < 0) { |
790 | 793 |
Value c = _upper[j]; |
791 | 794 |
if (c >= MAX) return UNBOUNDED; |
792 | 795 |
_excess[i] -= c; |
793 | 796 |
_excess[_target[j]] += c; |
794 | 797 |
} |
795 | 798 |
} |
796 | 799 |
} |
797 | 800 |
} |
798 | 801 |
Value ex, max_cap = 0; |
799 | 802 |
for (int i = 0; i != _res_node_num; ++i) { |
800 | 803 |
ex = _excess[i]; |
801 | 804 |
_excess[i] = 0; |
802 | 805 |
if (ex < 0) max_cap -= ex; |
803 | 806 |
} |
804 | 807 |
for (int j = 0; j != _res_arc_num; ++j) { |
805 | 808 |
if (_upper[j] >= MAX) _upper[j] = max_cap; |
806 | 809 |
} |
807 | 810 |
|
808 | 811 |
// Initialize the large cost vector and the epsilon parameter |
809 | 812 |
_epsilon = 0; |
810 | 813 |
LargeCost lc; |
811 | 814 |
for (int i = 0; i != _root; ++i) { |
812 | 815 |
last_out = _first_out[i+1]; |
813 | 816 |
for (int j = _first_out[i]; j != last_out; ++j) { |
814 | 817 |
lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha; |
815 | 818 |
_cost[j] = lc; |
816 | 819 |
if (lc > _epsilon) _epsilon = lc; |
817 | 820 |
} |
818 | 821 |
} |
819 | 822 |
_epsilon /= _alpha; |
820 | 823 |
|
821 | 824 |
// Initialize maps for Circulation and remove non-zero lower bounds |
822 | 825 |
ConstMap<Arc, Value> low(0); |
823 | 826 |
typedef typename Digraph::template ArcMap<Value> ValueArcMap; |
824 | 827 |
typedef typename Digraph::template NodeMap<Value> ValueNodeMap; |
825 | 828 |
ValueArcMap cap(_graph), flow(_graph); |
826 | 829 |
ValueNodeMap sup(_graph); |
827 | 830 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
828 | 831 |
sup[n] = _supply[_node_id[n]]; |
829 | 832 |
} |
830 | 833 |
if (_have_lower) { |
831 | 834 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
832 | 835 |
int j = _arc_idf[a]; |
833 | 836 |
Value c = _lower[j]; |
834 | 837 |
cap[a] = _upper[j] - c; |
835 | 838 |
sup[_graph.source(a)] -= c; |
836 | 839 |
sup[_graph.target(a)] += c; |
837 | 840 |
} |
838 | 841 |
} else { |
839 | 842 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
840 | 843 |
cap[a] = _upper[_arc_idf[a]]; |
841 | 844 |
} |
842 | 845 |
} |
843 | 846 |
|
844 | 847 |
_sup_node_num = 0; |
845 | 848 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
846 | 849 |
if (sup[n] > 0) ++_sup_node_num; |
847 | 850 |
} |
848 | 851 |
|
849 | 852 |
// Find a feasible flow using Circulation |
850 | 853 |
Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap> |
851 | 854 |
circ(_graph, low, cap, sup); |
852 | 855 |
if (!circ.flowMap(flow).run()) return INFEASIBLE; |
853 | 856 |
|
854 | 857 |
// Set residual capacities and handle GEQ supply type |
855 | 858 |
if (_sum_supply < 0) { |
856 | 859 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
857 | 860 |
Value fa = flow[a]; |
858 | 861 |
_res_cap[_arc_idf[a]] = cap[a] - fa; |
859 | 862 |
_res_cap[_arc_idb[a]] = fa; |
860 | 863 |
sup[_graph.source(a)] -= fa; |
861 | 864 |
sup[_graph.target(a)] += fa; |
862 | 865 |
} |
863 | 866 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
864 | 867 |
_excess[_node_id[n]] = sup[n]; |
865 | 868 |
} |
866 | 869 |
for (int a = _first_out[_root]; a != _res_arc_num; ++a) { |
867 | 870 |
int u = _target[a]; |
868 | 871 |
int ra = _reverse[a]; |
869 | 872 |
_res_cap[a] = -_sum_supply + 1; |
870 | 873 |
_res_cap[ra] = -_excess[u]; |
871 | 874 |
_cost[a] = 0; |
872 | 875 |
_cost[ra] = 0; |
873 | 876 |
_excess[u] = 0; |
874 | 877 |
} |
875 | 878 |
} else { |
876 | 879 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
877 | 880 |
Value fa = flow[a]; |
878 | 881 |
_res_cap[_arc_idf[a]] = cap[a] - fa; |
879 | 882 |
_res_cap[_arc_idb[a]] = fa; |
880 | 883 |
} |
881 | 884 |
for (int a = _first_out[_root]; a != _res_arc_num; ++a) { |
882 | 885 |
int ra = _reverse[a]; |
883 | 886 |
_res_cap[a] = 0; |
884 | 887 |
_res_cap[ra] = 0; |
885 | 888 |
_cost[a] = 0; |
886 | 889 |
_cost[ra] = 0; |
887 | 890 |
} |
888 | 891 |
} |
889 | 892 |
|
890 | 893 |
return OPTIMAL; |
891 | 894 |
} |
892 | 895 |
|
893 | 896 |
// Execute the algorithm and transform the results |
894 | 897 |
void start(Method method) { |
895 | 898 |
// Maximum path length for partial augment |
896 | 899 |
const int MAX_PATH_LENGTH = 4; |
897 | 900 |
|
898 | 901 |
// Initialize data structures for buckets |
899 | 902 |
_max_rank = _alpha * _res_node_num; |
900 | 903 |
_buckets.resize(_max_rank); |
901 | 904 |
_bucket_next.resize(_res_node_num + 1); |
902 | 905 |
_bucket_prev.resize(_res_node_num + 1); |
903 | 906 |
_rank.resize(_res_node_num + 1); |
904 | 907 |
|
905 | 908 |
// Execute the algorithm |
906 | 909 |
switch (method) { |
907 | 910 |
case PUSH: |
908 | 911 |
startPush(); |
909 | 912 |
break; |
910 | 913 |
case AUGMENT: |
911 | 914 |
startAugment(); |
912 | 915 |
break; |
913 | 916 |
case PARTIAL_AUGMENT: |
914 | 917 |
startAugment(MAX_PATH_LENGTH); |
915 | 918 |
break; |
916 | 919 |
} |
917 | 920 |
|
918 | 921 |
// Compute node potentials for the original costs |
919 | 922 |
_arc_vec.clear(); |
920 | 923 |
_cost_vec.clear(); |
921 | 924 |
for (int j = 0; j != _res_arc_num; ++j) { |
922 | 925 |
if (_res_cap[j] > 0) { |
923 | 926 |
_arc_vec.push_back(IntPair(_source[j], _target[j])); |
924 | 927 |
_cost_vec.push_back(_scost[j]); |
925 | 928 |
} |
926 | 929 |
} |
927 | 930 |
_sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end()); |
928 | 931 |
|
929 | 932 |
typename BellmanFord<StaticDigraph, LargeCostArcMap> |
930 | 933 |
::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map); |
931 | 934 |
bf.distMap(_pi_map); |
932 | 935 |
bf.init(0); |
933 | 936 |
bf.start(); |
934 | 937 |
|
935 | 938 |
// Handle non-zero lower bounds |
936 | 939 |
if (_have_lower) { |
937 | 940 |
int limit = _first_out[_root]; |
938 | 941 |
for (int j = 0; j != limit; ++j) { |
939 | 942 |
if (!_forward[j]) _res_cap[j] += _lower[j]; |
940 | 943 |
} |
941 | 944 |
} |
942 | 945 |
} |
943 | 946 |
|
944 | 947 |
// Initialize a cost scaling phase |
945 | 948 |
void initPhase() { |
946 | 949 |
// Saturate arcs not satisfying the optimality condition |
947 | 950 |
for (int u = 0; u != _res_node_num; ++u) { |
948 | 951 |
int last_out = _first_out[u+1]; |
949 | 952 |
LargeCost pi_u = _pi[u]; |
950 | 953 |
for (int a = _first_out[u]; a != last_out; ++a) { |
951 | 954 |
int v = _target[a]; |
952 | 955 |
if (_res_cap[a] > 0 && _cost[a] + pi_u - _pi[v] < 0) { |
953 | 956 |
Value delta = _res_cap[a]; |
954 | 957 |
_excess[u] -= delta; |
955 | 958 |
_excess[v] += delta; |
956 | 959 |
_res_cap[a] = 0; |
957 | 960 |
_res_cap[_reverse[a]] += delta; |
958 | 961 |
} |
959 | 962 |
} |
960 | 963 |
} |
961 | 964 |
|
962 | 965 |
// Find active nodes (i.e. nodes with positive excess) |
963 | 966 |
for (int u = 0; u != _res_node_num; ++u) { |
964 | 967 |
if (_excess[u] > 0) _active_nodes.push_back(u); |
965 | 968 |
} |
966 | 969 |
|
967 | 970 |
// Initialize the next arcs |
968 | 971 |
for (int u = 0; u != _res_node_num; ++u) { |
969 | 972 |
_next_out[u] = _first_out[u]; |
970 | 973 |
} |
971 | 974 |
} |
972 | 975 |
|
973 | 976 |
// Early termination heuristic |
974 | 977 |
bool earlyTermination() { |
975 | 978 |
const double EARLY_TERM_FACTOR = 3.0; |
976 | 979 |
|
977 | 980 |
// Build a static residual graph |
978 | 981 |
_arc_vec.clear(); |
979 | 982 |
_cost_vec.clear(); |
980 | 983 |
for (int j = 0; j != _res_arc_num; ++j) { |
981 | 984 |
if (_res_cap[j] > 0) { |
982 | 985 |
_arc_vec.push_back(IntPair(_source[j], _target[j])); |
983 | 986 |
_cost_vec.push_back(_cost[j] + 1); |
984 | 987 |
} |
985 | 988 |
} |
986 | 989 |
_sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end()); |
987 | 990 |
|
988 | 991 |
// Run Bellman-Ford algorithm to check if the current flow is optimal |
989 | 992 |
BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map); |
990 | 993 |
bf.init(0); |
991 | 994 |
bool done = false; |
992 | 995 |
int K = int(EARLY_TERM_FACTOR * std::sqrt(double(_res_node_num))); |
993 | 996 |
for (int i = 0; i < K && !done; ++i) { |
994 | 997 |
done = bf.processNextWeakRound(); |
995 | 998 |
} |
996 | 999 |
return done; |
997 | 1000 |
} |
998 | 1001 |
|
999 | 1002 |
// Global potential update heuristic |
1000 | 1003 |
void globalUpdate() { |
1001 | 1004 |
int bucket_end = _root + 1; |
1002 | 1005 |
|
1003 | 1006 |
// Initialize buckets |
1004 | 1007 |
for (int r = 0; r != _max_rank; ++r) { |
1005 | 1008 |
_buckets[r] = bucket_end; |
1006 | 1009 |
} |
1007 | 1010 |
Value total_excess = 0; |
1008 | 1011 |
for (int i = 0; i != _res_node_num; ++i) { |
1009 | 1012 |
if (_excess[i] < 0) { |
1010 | 1013 |
_rank[i] = 0; |
1011 | 1014 |
_bucket_next[i] = _buckets[0]; |
1012 | 1015 |
_bucket_prev[_buckets[0]] = i; |
1013 | 1016 |
_buckets[0] = i; |
1014 | 1017 |
} else { |
1015 | 1018 |
total_excess += _excess[i]; |
1016 | 1019 |
_rank[i] = _max_rank; |
1017 | 1020 |
} |
1018 | 1021 |
} |
1019 | 1022 |
if (total_excess == 0) return; |
1020 | 1023 |
|
1021 | 1024 |
// Search the buckets |
1022 | 1025 |
int r = 0; |
1023 | 1026 |
for ( ; r != _max_rank; ++r) { |
1024 | 1027 |
while (_buckets[r] != bucket_end) { |
1025 | 1028 |
// Remove the first node from the current bucket |
1026 | 1029 |
int u = _buckets[r]; |
1027 | 1030 |
_buckets[r] = _bucket_next[u]; |
1028 | 1031 |
|
1029 | 1032 |
// Search the incomming arcs of u |
1030 | 1033 |
LargeCost pi_u = _pi[u]; |
1031 | 1034 |
int last_out = _first_out[u+1]; |
1032 | 1035 |
for (int a = _first_out[u]; a != last_out; ++a) { |
1033 | 1036 |
int ra = _reverse[a]; |
1034 | 1037 |
if (_res_cap[ra] > 0) { |
1035 | 1038 |
int v = _source[ra]; |
1036 | 1039 |
int old_rank_v = _rank[v]; |
1037 | 1040 |
if (r < old_rank_v) { |
1038 | 1041 |
// Compute the new rank of v |
1039 | 1042 |
LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon; |
1040 | 1043 |
int new_rank_v = old_rank_v; |
1041 | 1044 |
if (nrc < LargeCost(_max_rank)) |
1042 | 1045 |
new_rank_v = r + 1 + int(nrc); |
1043 | 1046 |
|
1044 | 1047 |
// Change the rank of v |
1045 | 1048 |
if (new_rank_v < old_rank_v) { |
1046 | 1049 |
_rank[v] = new_rank_v; |
1047 | 1050 |
_next_out[v] = _first_out[v]; |
1048 | 1051 |
|
1049 | 1052 |
// Remove v from its old bucket |
1050 | 1053 |
if (old_rank_v < _max_rank) { |
1051 | 1054 |
if (_buckets[old_rank_v] == v) { |
1052 | 1055 |
_buckets[old_rank_v] = _bucket_next[v]; |
1053 | 1056 |
} else { |
1054 | 1057 |
_bucket_next[_bucket_prev[v]] = _bucket_next[v]; |
1055 | 1058 |
_bucket_prev[_bucket_next[v]] = _bucket_prev[v]; |
1056 | 1059 |
} |
1057 | 1060 |
} |
1058 | 1061 |
|
1059 | 1062 |
// Insert v to its new bucket |
1060 | 1063 |
_bucket_next[v] = _buckets[new_rank_v]; |
1061 | 1064 |
_bucket_prev[_buckets[new_rank_v]] = v; |
1062 | 1065 |
_buckets[new_rank_v] = v; |
1063 | 1066 |
} |
1064 | 1067 |
} |
1065 | 1068 |
} |
1066 | 1069 |
} |
1067 | 1070 |
|
1068 | 1071 |
// Finish search if there are no more active nodes |
1069 | 1072 |
if (_excess[u] > 0) { |
1070 | 1073 |
total_excess -= _excess[u]; |
1071 | 1074 |
if (total_excess <= 0) break; |
1072 | 1075 |
} |
1073 | 1076 |
} |
1074 | 1077 |
if (total_excess <= 0) break; |
1075 | 1078 |
} |
1076 | 1079 |
|
1077 | 1080 |
// Relabel nodes |
1078 | 1081 |
for (int u = 0; u != _res_node_num; ++u) { |
1079 | 1082 |
int k = std::min(_rank[u], r); |
1080 | 1083 |
if (k > 0) { |
1081 | 1084 |
_pi[u] -= _epsilon * k; |
1082 | 1085 |
_next_out[u] = _first_out[u]; |
1083 | 1086 |
} |
1084 | 1087 |
} |
1085 | 1088 |
} |
1086 | 1089 |
|
1087 | 1090 |
/// Execute the algorithm performing augment and relabel operations |
1088 | 1091 |
void startAugment(int max_length = std::numeric_limits<int>::max()) { |
1089 | 1092 |
// Paramters for heuristics |
1090 | 1093 |
const int EARLY_TERM_EPSILON_LIMIT = 1000; |
1091 | 1094 |
const double GLOBAL_UPDATE_FACTOR = 3.0; |
1092 | 1095 |
|
1093 | 1096 |
const int global_update_freq = int(GLOBAL_UPDATE_FACTOR * |
1094 | 1097 |
(_res_node_num + _sup_node_num * _sup_node_num)); |
1095 | 1098 |
int next_update_limit = global_update_freq; |
1096 | 1099 |
|
1097 | 1100 |
int relabel_cnt = 0; |
1098 | 1101 |
|
1099 | 1102 |
// Perform cost scaling phases |
1100 | 1103 |
std::vector<int> path; |
1101 | 1104 |
for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ? |
1102 | 1105 |
1 : _epsilon / _alpha ) |
1103 | 1106 |
{ |
1104 | 1107 |
// Early termination heuristic |
1105 | 1108 |
if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) { |
1106 | 1109 |
if (earlyTermination()) break; |
1107 | 1110 |
} |
1108 | 1111 |
|
1109 | 1112 |
// Initialize current phase |
1110 | 1113 |
initPhase(); |
1111 | 1114 |
|
1112 | 1115 |
// Perform partial augment and relabel operations |
1113 | 1116 |
while (true) { |
1114 | 1117 |
// Select an active node (FIFO selection) |
1115 | 1118 |
while (_active_nodes.size() > 0 && |
1116 | 1119 |
_excess[_active_nodes.front()] <= 0) { |
1117 | 1120 |
_active_nodes.pop_front(); |
1118 | 1121 |
} |
1119 | 1122 |
if (_active_nodes.size() == 0) break; |
1120 | 1123 |
int start = _active_nodes.front(); |
1121 | 1124 |
|
1122 | 1125 |
// Find an augmenting path from the start node |
1123 | 1126 |
path.clear(); |
1124 | 1127 |
int tip = start; |
1125 | 1128 |
while (_excess[tip] >= 0 && int(path.size()) < max_length) { |
1126 | 1129 |
int u; |
1127 | 1130 |
LargeCost min_red_cost, rc, pi_tip = _pi[tip]; |
1128 | 1131 |
int last_out = _first_out[tip+1]; |
1129 | 1132 |
for (int a = _next_out[tip]; a != last_out; ++a) { |
1130 | 1133 |
u = _target[a]; |
1131 | 1134 |
if (_res_cap[a] > 0 && _cost[a] + pi_tip - _pi[u] < 0) { |
1132 | 1135 |
path.push_back(a); |
1133 | 1136 |
_next_out[tip] = a; |
1134 | 1137 |
tip = u; |
1135 | 1138 |
goto next_step; |
1136 | 1139 |
} |
1137 | 1140 |
} |
1138 | 1141 |
|
1139 | 1142 |
// Relabel tip node |
1140 | 1143 |
min_red_cost = std::numeric_limits<LargeCost>::max(); |
1141 | 1144 |
if (tip != start) { |
1142 | 1145 |
int ra = _reverse[path.back()]; |
1143 | 1146 |
min_red_cost = _cost[ra] + pi_tip - _pi[_target[ra]]; |
1144 | 1147 |
} |
1145 | 1148 |
for (int a = _first_out[tip]; a != last_out; ++a) { |
1146 | 1149 |
rc = _cost[a] + pi_tip - _pi[_target[a]]; |
1147 | 1150 |
if (_res_cap[a] > 0 && rc < min_red_cost) { |
1148 | 1151 |
min_red_cost = rc; |
1149 | 1152 |
} |
1150 | 1153 |
} |
1151 | 1154 |
_pi[tip] -= min_red_cost + _epsilon; |
1152 | 1155 |
_next_out[tip] = _first_out[tip]; |
1153 | 1156 |
++relabel_cnt; |
1154 | 1157 |
|
1155 | 1158 |
// Step back |
1156 | 1159 |
if (tip != start) { |
1157 | 1160 |
tip = _source[path.back()]; |
1158 | 1161 |
path.pop_back(); |
1159 | 1162 |
} |
1160 | 1163 |
|
1161 | 1164 |
next_step: ; |
1162 | 1165 |
} |
1163 | 1166 |
|
1164 | 1167 |
// Augment along the found path (as much flow as possible) |
1165 | 1168 |
Value delta; |
1166 | 1169 |
int pa, u, v = start; |
1167 | 1170 |
for (int i = 0; i != int(path.size()); ++i) { |
1168 | 1171 |
pa = path[i]; |
1169 | 1172 |
u = v; |
1170 | 1173 |
v = _target[pa]; |
1171 | 1174 |
delta = std::min(_res_cap[pa], _excess[u]); |
1172 | 1175 |
_res_cap[pa] -= delta; |
1173 | 1176 |
_res_cap[_reverse[pa]] += delta; |
1174 | 1177 |
_excess[u] -= delta; |
1175 | 1178 |
_excess[v] += delta; |
1176 | 1179 |
if (_excess[v] > 0 && _excess[v] <= delta) |
1177 | 1180 |
_active_nodes.push_back(v); |
1178 | 1181 |
} |
1179 | 1182 |
|
1180 | 1183 |
// Global update heuristic |
1181 | 1184 |
if (relabel_cnt >= next_update_limit) { |
1182 | 1185 |
globalUpdate(); |
1183 | 1186 |
next_update_limit += global_update_freq; |
1184 | 1187 |
} |
1185 | 1188 |
} |
1186 | 1189 |
} |
1187 | 1190 |
} |
1188 | 1191 |
|
1189 | 1192 |
/// Execute the algorithm performing push and relabel operations |
1190 | 1193 |
void startPush() { |
1191 | 1194 |
// Paramters for heuristics |
1192 | 1195 |
const int EARLY_TERM_EPSILON_LIMIT = 1000; |
1193 | 1196 |
const double GLOBAL_UPDATE_FACTOR = 2.0; |
1194 | 1197 |
|
1195 | 1198 |
const int global_update_freq = int(GLOBAL_UPDATE_FACTOR * |
1196 | 1199 |
(_res_node_num + _sup_node_num * _sup_node_num)); |
1197 | 1200 |
int next_update_limit = global_update_freq; |
1198 | 1201 |
|
1199 | 1202 |
int relabel_cnt = 0; |
1200 | 1203 |
|
1201 | 1204 |
// Perform cost scaling phases |
1202 | 1205 |
BoolVector hyper(_res_node_num, false); |
1203 | 1206 |
LargeCostVector hyper_cost(_res_node_num); |
1204 | 1207 |
for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ? |
1205 | 1208 |
1 : _epsilon / _alpha ) |
1206 | 1209 |
{ |
1207 | 1210 |
// Early termination heuristic |
1208 | 1211 |
if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) { |
1209 | 1212 |
if (earlyTermination()) break; |
1210 | 1213 |
} |
1211 | 1214 |
|
1212 | 1215 |
// Initialize current phase |
1213 | 1216 |
initPhase(); |
1214 | 1217 |
|
1215 | 1218 |
// Perform push and relabel operations |
1216 | 1219 |
while (_active_nodes.size() > 0) { |
1217 | 1220 |
LargeCost min_red_cost, rc, pi_n; |
1218 | 1221 |
Value delta; |
1219 | 1222 |
int n, t, a, last_out = _res_arc_num; |
1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2010 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
#ifndef LEMON_CYCLE_CANCELING_H |
20 | 20 |
#define LEMON_CYCLE_CANCELING_H |
21 | 21 |
|
22 | 22 |
/// \ingroup min_cost_flow_algs |
23 | 23 |
/// \file |
24 | 24 |
/// \brief Cycle-canceling algorithms for finding a minimum cost flow. |
25 | 25 |
|
26 | 26 |
#include <vector> |
27 | 27 |
#include <limits> |
28 | 28 |
|
29 | 29 |
#include <lemon/core.h> |
30 | 30 |
#include <lemon/maps.h> |
31 | 31 |
#include <lemon/path.h> |
32 | 32 |
#include <lemon/math.h> |
33 | 33 |
#include <lemon/static_graph.h> |
34 | 34 |
#include <lemon/adaptors.h> |
35 | 35 |
#include <lemon/circulation.h> |
36 | 36 |
#include <lemon/bellman_ford.h> |
37 | 37 |
#include <lemon/howard_mmc.h> |
38 | 38 |
|
39 | 39 |
namespace lemon { |
40 | 40 |
|
41 | 41 |
/// \addtogroup min_cost_flow_algs |
42 | 42 |
/// @{ |
43 | 43 |
|
44 | 44 |
/// \brief Implementation of cycle-canceling algorithms for |
45 | 45 |
/// finding a \ref min_cost_flow "minimum cost flow". |
46 | 46 |
/// |
47 | 47 |
/// \ref CycleCanceling implements three different cycle-canceling |
48 | 48 |
/// algorithms for finding a \ref min_cost_flow "minimum cost flow" |
49 | 49 |
/// \ref amo93networkflows, \ref klein67primal, |
50 | 50 |
/// \ref goldberg89cyclecanceling. |
51 | 51 |
/// The most efficent one (both theoretically and practically) |
52 | 52 |
/// is the \ref CANCEL_AND_TIGHTEN "Cancel and Tighten" algorithm, |
53 | 53 |
/// thus it is the default method. |
54 | 54 |
/// It is strongly polynomial, but in practice, it is typically much |
55 | 55 |
/// slower than the scaling algorithms and NetworkSimplex. |
56 | 56 |
/// |
57 | 57 |
/// Most of the parameters of the problem (except for the digraph) |
58 | 58 |
/// can be given using separate functions, and the algorithm can be |
59 | 59 |
/// executed using the \ref run() function. If some parameters are not |
60 | 60 |
/// specified, then default values will be used. |
61 | 61 |
/// |
62 | 62 |
/// \tparam GR The digraph type the algorithm runs on. |
63 | 63 |
/// \tparam V The number type used for flow amounts, capacity bounds |
64 | 64 |
/// and supply values in the algorithm. By default, it is \c int. |
65 | 65 |
/// \tparam C The number type used for costs and potentials in the |
66 | 66 |
/// algorithm. By default, it is the same as \c V. |
67 | 67 |
/// |
68 | 68 |
/// \warning Both \c V and \c C must be signed number types. |
69 | 69 |
/// \warning All input data (capacities, supply values, and costs) must |
70 | 70 |
/// be integer. |
71 |
/// \warning This algorithm does not support negative costs for such |
|
72 |
/// arcs that have infinite upper bound. |
|
71 |
/// \warning This algorithm does not support negative costs for |
|
72 |
/// arcs having infinite upper bound. |
|
73 | 73 |
/// |
74 | 74 |
/// \note For more information about the three available methods, |
75 | 75 |
/// see \ref Method. |
76 | 76 |
#ifdef DOXYGEN |
77 | 77 |
template <typename GR, typename V, typename C> |
78 | 78 |
#else |
79 | 79 |
template <typename GR, typename V = int, typename C = V> |
80 | 80 |
#endif |
81 | 81 |
class CycleCanceling |
82 | 82 |
{ |
83 | 83 |
public: |
84 | 84 |
|
85 | 85 |
/// The type of the digraph |
86 | 86 |
typedef GR Digraph; |
87 | 87 |
/// The type of the flow amounts, capacity bounds and supply values |
88 | 88 |
typedef V Value; |
89 | 89 |
/// The type of the arc costs |
90 | 90 |
typedef C Cost; |
91 | 91 |
|
92 | 92 |
public: |
93 | 93 |
|
94 | 94 |
/// \brief Problem type constants for the \c run() function. |
95 | 95 |
/// |
96 | 96 |
/// Enum type containing the problem type constants that can be |
97 | 97 |
/// returned by the \ref run() function of the algorithm. |
98 | 98 |
enum ProblemType { |
99 | 99 |
/// The problem has no feasible solution (flow). |
100 | 100 |
INFEASIBLE, |
101 | 101 |
/// The problem has optimal solution (i.e. it is feasible and |
102 | 102 |
/// bounded), and the algorithm has found optimal flow and node |
103 | 103 |
/// potentials (primal and dual solutions). |
104 | 104 |
OPTIMAL, |
105 | 105 |
/// The digraph contains an arc of negative cost and infinite |
106 | 106 |
/// upper bound. It means that the objective function is unbounded |
107 | 107 |
/// on that arc, however, note that it could actually be bounded |
108 | 108 |
/// over the feasible flows, but this algroithm cannot handle |
109 | 109 |
/// these cases. |
110 | 110 |
UNBOUNDED |
111 | 111 |
}; |
112 | 112 |
|
113 | 113 |
/// \brief Constants for selecting the used method. |
114 | 114 |
/// |
115 | 115 |
/// Enum type containing constants for selecting the used method |
116 | 116 |
/// for the \ref run() function. |
117 | 117 |
/// |
118 | 118 |
/// \ref CycleCanceling provides three different cycle-canceling |
119 | 119 |
/// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel and Tighten" |
120 |
/// is used, which proved to be the most efficient and the most robust |
|
121 |
/// on various test inputs. |
|
120 |
/// is used, which is by far the most efficient and the most robust. |
|
122 | 121 |
/// However, the other methods can be selected using the \ref run() |
123 | 122 |
/// function with the proper parameter. |
124 | 123 |
enum Method { |
125 | 124 |
/// A simple cycle-canceling method, which uses the |
126 | 125 |
/// \ref BellmanFord "Bellman-Ford" algorithm with limited iteration |
127 | 126 |
/// number for detecting negative cycles in the residual network. |
128 | 127 |
SIMPLE_CYCLE_CANCELING, |
129 | 128 |
/// The "Minimum Mean Cycle-Canceling" algorithm, which is a |
130 | 129 |
/// well-known strongly polynomial method |
131 | 130 |
/// \ref goldberg89cyclecanceling. It improves along a |
132 | 131 |
/// \ref min_mean_cycle "minimum mean cycle" in each iteration. |
133 | 132 |
/// Its running time complexity is O(n<sup>2</sup>m<sup>3</sup>log(n)). |
134 | 133 |
MINIMUM_MEAN_CYCLE_CANCELING, |
135 | 134 |
/// The "Cancel And Tighten" algorithm, which can be viewed as an |
136 | 135 |
/// improved version of the previous method |
137 | 136 |
/// \ref goldberg89cyclecanceling. |
138 | 137 |
/// It is faster both in theory and in practice, its running time |
139 | 138 |
/// complexity is O(n<sup>2</sup>m<sup>2</sup>log(n)). |
140 | 139 |
CANCEL_AND_TIGHTEN |
141 | 140 |
}; |
142 | 141 |
|
143 | 142 |
private: |
144 | 143 |
|
145 | 144 |
TEMPLATE_DIGRAPH_TYPEDEFS(GR); |
146 | 145 |
|
147 | 146 |
typedef std::vector<int> IntVector; |
148 | 147 |
typedef std::vector<double> DoubleVector; |
149 | 148 |
typedef std::vector<Value> ValueVector; |
150 | 149 |
typedef std::vector<Cost> CostVector; |
151 | 150 |
typedef std::vector<char> BoolVector; |
152 | 151 |
// Note: vector<char> is used instead of vector<bool> for efficiency reasons |
153 | 152 |
|
154 | 153 |
private: |
155 | 154 |
|
156 | 155 |
template <typename KT, typename VT> |
157 | 156 |
class StaticVectorMap { |
158 | 157 |
public: |
159 | 158 |
typedef KT Key; |
160 | 159 |
typedef VT Value; |
161 | 160 |
|
162 | 161 |
StaticVectorMap(std::vector<Value>& v) : _v(v) {} |
163 | 162 |
|
164 | 163 |
const Value& operator[](const Key& key) const { |
165 | 164 |
return _v[StaticDigraph::id(key)]; |
166 | 165 |
} |
167 | 166 |
|
168 | 167 |
Value& operator[](const Key& key) { |
169 | 168 |
return _v[StaticDigraph::id(key)]; |
170 | 169 |
} |
171 | 170 |
|
172 | 171 |
void set(const Key& key, const Value& val) { |
173 | 172 |
_v[StaticDigraph::id(key)] = val; |
174 | 173 |
} |
175 | 174 |
|
176 | 175 |
private: |
177 | 176 |
std::vector<Value>& _v; |
178 | 177 |
}; |
179 | 178 |
|
180 | 179 |
typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap; |
181 | 180 |
typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap; |
182 | 181 |
|
183 | 182 |
private: |
184 | 183 |
|
185 | 184 |
|
186 | 185 |
// Data related to the underlying digraph |
187 | 186 |
const GR &_graph; |
188 | 187 |
int _node_num; |
189 | 188 |
int _arc_num; |
190 | 189 |
int _res_node_num; |
191 | 190 |
int _res_arc_num; |
192 | 191 |
int _root; |
193 | 192 |
|
194 | 193 |
// Parameters of the problem |
195 | 194 |
bool _have_lower; |
196 | 195 |
Value _sum_supply; |
197 | 196 |
|
198 | 197 |
// Data structures for storing the digraph |
199 | 198 |
IntNodeMap _node_id; |
200 | 199 |
IntArcMap _arc_idf; |
201 | 200 |
IntArcMap _arc_idb; |
202 | 201 |
IntVector _first_out; |
203 | 202 |
BoolVector _forward; |
204 | 203 |
IntVector _source; |
205 | 204 |
IntVector _target; |
206 | 205 |
IntVector _reverse; |
207 | 206 |
|
208 | 207 |
// Node and arc data |
209 | 208 |
ValueVector _lower; |
210 | 209 |
ValueVector _upper; |
211 | 210 |
CostVector _cost; |
212 | 211 |
ValueVector _supply; |
213 | 212 |
|
214 | 213 |
ValueVector _res_cap; |
215 | 214 |
CostVector _pi; |
216 | 215 |
|
217 | 216 |
// Data for a StaticDigraph structure |
218 | 217 |
typedef std::pair<int, int> IntPair; |
219 | 218 |
StaticDigraph _sgr; |
220 | 219 |
std::vector<IntPair> _arc_vec; |
221 | 220 |
std::vector<Cost> _cost_vec; |
222 | 221 |
IntVector _id_vec; |
223 | 222 |
CostArcMap _cost_map; |
224 | 223 |
CostNodeMap _pi_map; |
225 | 224 |
|
226 | 225 |
public: |
227 | 226 |
|
228 | 227 |
/// \brief Constant for infinite upper bounds (capacities). |
229 | 228 |
/// |
230 | 229 |
/// Constant for infinite upper bounds (capacities). |
231 | 230 |
/// It is \c std::numeric_limits<Value>::infinity() if available, |
232 | 231 |
/// \c std::numeric_limits<Value>::max() otherwise. |
233 | 232 |
const Value INF; |
234 | 233 |
|
235 | 234 |
public: |
236 | 235 |
|
237 | 236 |
/// \brief Constructor. |
238 | 237 |
/// |
239 | 238 |
/// The constructor of the class. |
240 | 239 |
/// |
241 | 240 |
/// \param graph The digraph the algorithm runs on. |
242 | 241 |
CycleCanceling(const GR& graph) : |
243 | 242 |
_graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph), |
244 | 243 |
_cost_map(_cost_vec), _pi_map(_pi), |
245 | 244 |
INF(std::numeric_limits<Value>::has_infinity ? |
246 | 245 |
std::numeric_limits<Value>::infinity() : |
247 | 246 |
std::numeric_limits<Value>::max()) |
248 | 247 |
{ |
249 | 248 |
// Check the number types |
250 | 249 |
LEMON_ASSERT(std::numeric_limits<Value>::is_signed, |
251 | 250 |
"The flow type of CycleCanceling must be signed"); |
252 | 251 |
LEMON_ASSERT(std::numeric_limits<Cost>::is_signed, |
253 | 252 |
"The cost type of CycleCanceling must be signed"); |
254 | 253 |
|
255 | 254 |
// Reset data structures |
256 | 255 |
reset(); |
257 | 256 |
} |
258 | 257 |
|
259 | 258 |
/// \name Parameters |
260 | 259 |
/// The parameters of the algorithm can be specified using these |
261 | 260 |
/// functions. |
262 | 261 |
|
263 | 262 |
/// @{ |
264 | 263 |
|
265 | 264 |
/// \brief Set the lower bounds on the arcs. |
266 | 265 |
/// |
267 | 266 |
/// This function sets the lower bounds on the arcs. |
268 | 267 |
/// If it is not used before calling \ref run(), the lower bounds |
269 | 268 |
/// will be set to zero on all arcs. |
270 | 269 |
/// |
271 | 270 |
/// \param map An arc map storing the lower bounds. |
272 | 271 |
/// Its \c Value type must be convertible to the \c Value type |
273 | 272 |
/// of the algorithm. |
274 | 273 |
/// |
275 | 274 |
/// \return <tt>(*this)</tt> |
276 | 275 |
template <typename LowerMap> |
277 | 276 |
CycleCanceling& lowerMap(const LowerMap& map) { |
278 | 277 |
_have_lower = true; |
279 | 278 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
280 | 279 |
_lower[_arc_idf[a]] = map[a]; |
281 | 280 |
_lower[_arc_idb[a]] = map[a]; |
282 | 281 |
} |
283 | 282 |
return *this; |
284 | 283 |
} |
285 | 284 |
|
286 | 285 |
/// \brief Set the upper bounds (capacities) on the arcs. |
287 | 286 |
/// |
288 | 287 |
/// This function sets the upper bounds (capacities) on the arcs. |
289 | 288 |
/// If it is not used before calling \ref run(), the upper bounds |
290 | 289 |
/// will be set to \ref INF on all arcs (i.e. the flow value will be |
291 | 290 |
/// unbounded from above). |
292 | 291 |
/// |
293 | 292 |
/// \param map An arc map storing the upper bounds. |
294 | 293 |
/// Its \c Value type must be convertible to the \c Value type |
295 | 294 |
/// of the algorithm. |
296 | 295 |
/// |
297 | 296 |
/// \return <tt>(*this)</tt> |
298 | 297 |
template<typename UpperMap> |
299 | 298 |
CycleCanceling& upperMap(const UpperMap& map) { |
300 | 299 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
301 | 300 |
_upper[_arc_idf[a]] = map[a]; |
302 | 301 |
} |
303 | 302 |
return *this; |
304 | 303 |
} |
305 | 304 |
|
306 | 305 |
/// \brief Set the costs of the arcs. |
307 | 306 |
/// |
308 | 307 |
/// This function sets the costs of the arcs. |
309 | 308 |
/// If it is not used before calling \ref run(), the costs |
310 | 309 |
/// will be set to \c 1 on all arcs. |
311 | 310 |
/// |
312 | 311 |
/// \param map An arc map storing the costs. |
313 | 312 |
/// Its \c Value type must be convertible to the \c Cost type |
314 | 313 |
/// of the algorithm. |
315 | 314 |
/// |
316 | 315 |
/// \return <tt>(*this)</tt> |
317 | 316 |
template<typename CostMap> |
318 | 317 |
CycleCanceling& costMap(const CostMap& map) { |
319 | 318 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
320 | 319 |
_cost[_arc_idf[a]] = map[a]; |
321 | 320 |
_cost[_arc_idb[a]] = -map[a]; |
322 | 321 |
} |
323 | 322 |
return *this; |
324 | 323 |
} |
325 | 324 |
|
326 | 325 |
/// \brief Set the supply values of the nodes. |
327 | 326 |
/// |
328 | 327 |
/// This function sets the supply values of the nodes. |
329 | 328 |
/// If neither this function nor \ref stSupply() is used before |
330 | 329 |
/// calling \ref run(), the supply of each node will be set to zero. |
331 | 330 |
/// |
332 | 331 |
/// \param map A node map storing the supply values. |
333 | 332 |
/// Its \c Value type must be convertible to the \c Value type |
334 | 333 |
/// of the algorithm. |
335 | 334 |
/// |
336 | 335 |
/// \return <tt>(*this)</tt> |
337 | 336 |
template<typename SupplyMap> |
338 | 337 |
CycleCanceling& supplyMap(const SupplyMap& map) { |
339 | 338 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
340 | 339 |
_supply[_node_id[n]] = map[n]; |
341 | 340 |
} |
342 | 341 |
return *this; |
343 | 342 |
} |
344 | 343 |
|
345 | 344 |
/// \brief Set single source and target nodes and a supply value. |
346 | 345 |
/// |
347 | 346 |
/// This function sets a single source node and a single target node |
348 | 347 |
/// and the required flow value. |
349 | 348 |
/// If neither this function nor \ref supplyMap() is used before |
350 | 349 |
/// calling \ref run(), the supply of each node will be set to zero. |
351 | 350 |
/// |
352 | 351 |
/// Using this function has the same effect as using \ref supplyMap() |
353 |
/// with |
|
352 |
/// with a map in which \c k is assigned to \c s, \c -k is |
|
354 | 353 |
/// assigned to \c t and all other nodes have zero supply value. |
355 | 354 |
/// |
356 | 355 |
/// \param s The source node. |
357 | 356 |
/// \param t The target node. |
358 | 357 |
/// \param k The required amount of flow from node \c s to node \c t |
359 | 358 |
/// (i.e. the supply of \c s and the demand of \c t). |
360 | 359 |
/// |
361 | 360 |
/// \return <tt>(*this)</tt> |
362 | 361 |
CycleCanceling& stSupply(const Node& s, const Node& t, Value k) { |
363 | 362 |
for (int i = 0; i != _res_node_num; ++i) { |
364 | 363 |
_supply[i] = 0; |
365 | 364 |
} |
366 | 365 |
_supply[_node_id[s]] = k; |
367 | 366 |
_supply[_node_id[t]] = -k; |
368 | 367 |
return *this; |
369 | 368 |
} |
370 | 369 |
|
371 | 370 |
/// @} |
372 | 371 |
|
373 | 372 |
/// \name Execution control |
374 | 373 |
/// The algorithm can be executed using \ref run(). |
375 | 374 |
|
376 | 375 |
/// @{ |
377 | 376 |
|
378 | 377 |
/// \brief Run the algorithm. |
379 | 378 |
/// |
380 | 379 |
/// This function runs the algorithm. |
381 | 380 |
/// The paramters can be specified using functions \ref lowerMap(), |
382 | 381 |
/// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). |
383 | 382 |
/// For example, |
384 | 383 |
/// \code |
385 | 384 |
/// CycleCanceling<ListDigraph> cc(graph); |
386 | 385 |
/// cc.lowerMap(lower).upperMap(upper).costMap(cost) |
387 | 386 |
/// .supplyMap(sup).run(); |
388 | 387 |
/// \endcode |
389 | 388 |
/// |
390 | 389 |
/// This function can be called more than once. All the given parameters |
391 | 390 |
/// are kept for the next call, unless \ref resetParams() or \ref reset() |
392 | 391 |
/// is used, thus only the modified parameters have to be set again. |
393 | 392 |
/// If the underlying digraph was also modified after the construction |
394 | 393 |
/// of the class (or the last \ref reset() call), then the \ref reset() |
395 | 394 |
/// function must be called. |
396 | 395 |
/// |
397 | 396 |
/// \param method The cycle-canceling method that will be used. |
398 | 397 |
/// For more information, see \ref Method. |
399 | 398 |
/// |
400 | 399 |
/// \return \c INFEASIBLE if no feasible flow exists, |
401 | 400 |
/// \n \c OPTIMAL if the problem has optimal solution |
402 | 401 |
/// (i.e. it is feasible and bounded), and the algorithm has found |
403 | 402 |
/// optimal flow and node potentials (primal and dual solutions), |
404 | 403 |
/// \n \c UNBOUNDED if the digraph contains an arc of negative cost |
405 | 404 |
/// and infinite upper bound. It means that the objective function |
406 | 405 |
/// is unbounded on that arc, however, note that it could actually be |
407 | 406 |
/// bounded over the feasible flows, but this algroithm cannot handle |
408 | 407 |
/// these cases. |
409 | 408 |
/// |
410 | 409 |
/// \see ProblemType, Method |
411 | 410 |
/// \see resetParams(), reset() |
412 | 411 |
ProblemType run(Method method = CANCEL_AND_TIGHTEN) { |
413 | 412 |
ProblemType pt = init(); |
414 | 413 |
if (pt != OPTIMAL) return pt; |
415 | 414 |
start(method); |
416 | 415 |
return OPTIMAL; |
417 | 416 |
} |
418 | 417 |
|
419 | 418 |
/// \brief Reset all the parameters that have been given before. |
420 | 419 |
/// |
421 | 420 |
/// This function resets all the paramaters that have been given |
422 | 421 |
/// before using functions \ref lowerMap(), \ref upperMap(), |
423 | 422 |
/// \ref costMap(), \ref supplyMap(), \ref stSupply(). |
424 | 423 |
/// |
425 | 424 |
/// It is useful for multiple \ref run() calls. Basically, all the given |
426 | 425 |
/// parameters are kept for the next \ref run() call, unless |
427 | 426 |
/// \ref resetParams() or \ref reset() is used. |
428 | 427 |
/// If the underlying digraph was also modified after the construction |
429 | 428 |
/// of the class or the last \ref reset() call, then the \ref reset() |
430 | 429 |
/// function must be used, otherwise \ref resetParams() is sufficient. |
431 | 430 |
/// |
432 | 431 |
/// For example, |
433 | 432 |
/// \code |
434 | 433 |
/// CycleCanceling<ListDigraph> cs(graph); |
435 | 434 |
/// |
436 | 435 |
/// // First run |
437 | 436 |
/// cc.lowerMap(lower).upperMap(upper).costMap(cost) |
438 | 437 |
/// .supplyMap(sup).run(); |
439 | 438 |
/// |
440 | 439 |
/// // Run again with modified cost map (resetParams() is not called, |
441 | 440 |
/// // so only the cost map have to be set again) |
442 | 441 |
/// cost[e] += 100; |
443 | 442 |
/// cc.costMap(cost).run(); |
444 | 443 |
/// |
445 | 444 |
/// // Run again from scratch using resetParams() |
446 | 445 |
/// // (the lower bounds will be set to zero on all arcs) |
447 | 446 |
/// cc.resetParams(); |
448 | 447 |
/// cc.upperMap(capacity).costMap(cost) |
449 | 448 |
/// .supplyMap(sup).run(); |
450 | 449 |
/// \endcode |
451 | 450 |
/// |
452 | 451 |
/// \return <tt>(*this)</tt> |
453 | 452 |
/// |
454 | 453 |
/// \see reset(), run() |
455 | 454 |
CycleCanceling& resetParams() { |
456 | 455 |
for (int i = 0; i != _res_node_num; ++i) { |
457 | 456 |
_supply[i] = 0; |
458 | 457 |
} |
459 | 458 |
int limit = _first_out[_root]; |
460 | 459 |
for (int j = 0; j != limit; ++j) { |
461 | 460 |
_lower[j] = 0; |
462 | 461 |
_upper[j] = INF; |
463 | 462 |
_cost[j] = _forward[j] ? 1 : -1; |
464 | 463 |
} |
465 | 464 |
for (int j = limit; j != _res_arc_num; ++j) { |
466 | 465 |
_lower[j] = 0; |
467 | 466 |
_upper[j] = INF; |
468 | 467 |
_cost[j] = 0; |
469 | 468 |
_cost[_reverse[j]] = 0; |
470 | 469 |
} |
471 | 470 |
_have_lower = false; |
472 | 471 |
return *this; |
473 | 472 |
} |
474 | 473 |
|
475 | 474 |
/// \brief Reset the internal data structures and all the parameters |
476 | 475 |
/// that have been given before. |
477 | 476 |
/// |
478 | 477 |
/// This function resets the internal data structures and all the |
479 | 478 |
/// paramaters that have been given before using functions \ref lowerMap(), |
480 | 479 |
/// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(). |
481 | 480 |
/// |
482 | 481 |
/// It is useful for multiple \ref run() calls. Basically, all the given |
483 | 482 |
/// parameters are kept for the next \ref run() call, unless |
484 | 483 |
/// \ref resetParams() or \ref reset() is used. |
485 | 484 |
/// If the underlying digraph was also modified after the construction |
486 | 485 |
/// of the class or the last \ref reset() call, then the \ref reset() |
487 | 486 |
/// function must be used, otherwise \ref resetParams() is sufficient. |
488 | 487 |
/// |
489 | 488 |
/// See \ref resetParams() for examples. |
490 | 489 |
/// |
491 | 490 |
/// \return <tt>(*this)</tt> |
492 | 491 |
/// |
493 | 492 |
/// \see resetParams(), run() |
494 | 493 |
CycleCanceling& reset() { |
495 | 494 |
// Resize vectors |
496 | 495 |
_node_num = countNodes(_graph); |
497 | 496 |
_arc_num = countArcs(_graph); |
498 | 497 |
_res_node_num = _node_num + 1; |
499 | 498 |
_res_arc_num = 2 * (_arc_num + _node_num); |
500 | 499 |
_root = _node_num; |
501 | 500 |
|
502 | 501 |
_first_out.resize(_res_node_num + 1); |
503 | 502 |
_forward.resize(_res_arc_num); |
504 | 503 |
_source.resize(_res_arc_num); |
505 | 504 |
_target.resize(_res_arc_num); |
506 | 505 |
_reverse.resize(_res_arc_num); |
507 | 506 |
|
508 | 507 |
_lower.resize(_res_arc_num); |
509 | 508 |
_upper.resize(_res_arc_num); |
510 | 509 |
_cost.resize(_res_arc_num); |
511 | 510 |
_supply.resize(_res_node_num); |
512 | 511 |
|
513 | 512 |
_res_cap.resize(_res_arc_num); |
514 | 513 |
_pi.resize(_res_node_num); |
515 | 514 |
|
516 | 515 |
_arc_vec.reserve(_res_arc_num); |
517 | 516 |
_cost_vec.reserve(_res_arc_num); |
518 | 517 |
_id_vec.reserve(_res_arc_num); |
519 | 518 |
|
520 | 519 |
// Copy the graph |
521 | 520 |
int i = 0, j = 0, k = 2 * _arc_num + _node_num; |
522 | 521 |
for (NodeIt n(_graph); n != INVALID; ++n, ++i) { |
523 | 522 |
_node_id[n] = i; |
524 | 523 |
} |
525 | 524 |
i = 0; |
526 | 525 |
for (NodeIt n(_graph); n != INVALID; ++n, ++i) { |
527 | 526 |
_first_out[i] = j; |
528 | 527 |
for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) { |
529 | 528 |
_arc_idf[a] = j; |
530 | 529 |
_forward[j] = true; |
531 | 530 |
_source[j] = i; |
532 | 531 |
_target[j] = _node_id[_graph.runningNode(a)]; |
533 | 532 |
} |
534 | 533 |
for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) { |
535 | 534 |
_arc_idb[a] = j; |
536 | 535 |
_forward[j] = false; |
537 | 536 |
_source[j] = i; |
538 | 537 |
_target[j] = _node_id[_graph.runningNode(a)]; |
539 | 538 |
} |
540 | 539 |
_forward[j] = false; |
541 | 540 |
_source[j] = i; |
542 | 541 |
_target[j] = _root; |
543 | 542 |
_reverse[j] = k; |
544 | 543 |
_forward[k] = true; |
545 | 544 |
_source[k] = _root; |
546 | 545 |
_target[k] = i; |
547 | 546 |
_reverse[k] = j; |
548 | 547 |
++j; ++k; |
549 | 548 |
} |
550 | 549 |
_first_out[i] = j; |
551 | 550 |
_first_out[_res_node_num] = k; |
552 | 551 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
553 | 552 |
int fi = _arc_idf[a]; |
554 | 553 |
int bi = _arc_idb[a]; |
555 | 554 |
_reverse[fi] = bi; |
556 | 555 |
_reverse[bi] = fi; |
557 | 556 |
} |
558 | 557 |
|
559 | 558 |
// Reset parameters |
560 | 559 |
resetParams(); |
561 | 560 |
return *this; |
562 | 561 |
} |
563 | 562 |
|
564 | 563 |
/// @} |
565 | 564 |
|
566 | 565 |
/// \name Query Functions |
567 | 566 |
/// The results of the algorithm can be obtained using these |
568 | 567 |
/// functions.\n |
569 | 568 |
/// The \ref run() function must be called before using them. |
570 | 569 |
|
571 | 570 |
/// @{ |
572 | 571 |
|
573 | 572 |
/// \brief Return the total cost of the found flow. |
574 | 573 |
/// |
575 | 574 |
/// This function returns the total cost of the found flow. |
576 | 575 |
/// Its complexity is O(e). |
577 | 576 |
/// |
578 | 577 |
/// \note The return type of the function can be specified as a |
579 | 578 |
/// template parameter. For example, |
580 | 579 |
/// \code |
581 | 580 |
/// cc.totalCost<double>(); |
582 | 581 |
/// \endcode |
583 | 582 |
/// It is useful if the total cost cannot be stored in the \c Cost |
584 | 583 |
/// type of the algorithm, which is the default return type of the |
585 | 584 |
/// function. |
586 | 585 |
/// |
587 | 586 |
/// \pre \ref run() must be called before using this function. |
588 | 587 |
template <typename Number> |
589 | 588 |
Number totalCost() const { |
590 | 589 |
Number c = 0; |
591 | 590 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
592 | 591 |
int i = _arc_idb[a]; |
593 | 592 |
c += static_cast<Number>(_res_cap[i]) * |
594 | 593 |
(-static_cast<Number>(_cost[i])); |
595 | 594 |
} |
596 | 595 |
return c; |
597 | 596 |
} |
598 | 597 |
|
599 | 598 |
#ifndef DOXYGEN |
600 | 599 |
Cost totalCost() const { |
601 | 600 |
return totalCost<Cost>(); |
602 | 601 |
} |
603 | 602 |
#endif |
604 | 603 |
|
605 | 604 |
/// \brief Return the flow on the given arc. |
606 | 605 |
/// |
607 | 606 |
/// This function returns the flow on the given arc. |
608 | 607 |
/// |
609 | 608 |
/// \pre \ref run() must be called before using this function. |
610 | 609 |
Value flow(const Arc& a) const { |
611 | 610 |
return _res_cap[_arc_idb[a]]; |
612 | 611 |
} |
613 | 612 |
|
614 | 613 |
/// \brief Return the flow map (the primal solution). |
615 | 614 |
/// |
616 | 615 |
/// This function copies the flow value on each arc into the given |
617 | 616 |
/// map. The \c Value type of the algorithm must be convertible to |
618 | 617 |
/// the \c Value type of the map. |
619 | 618 |
/// |
620 | 619 |
/// \pre \ref run() must be called before using this function. |
621 | 620 |
template <typename FlowMap> |
622 | 621 |
void flowMap(FlowMap &map) const { |
623 | 622 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
624 | 623 |
map.set(a, _res_cap[_arc_idb[a]]); |
625 | 624 |
} |
626 | 625 |
} |
627 | 626 |
|
628 | 627 |
/// \brief Return the potential (dual value) of the given node. |
629 | 628 |
/// |
630 | 629 |
/// This function returns the potential (dual value) of the |
631 | 630 |
/// given node. |
632 | 631 |
/// |
633 | 632 |
/// \pre \ref run() must be called before using this function. |
634 | 633 |
Cost potential(const Node& n) const { |
635 | 634 |
return static_cast<Cost>(_pi[_node_id[n]]); |
636 | 635 |
} |
637 | 636 |
|
638 | 637 |
/// \brief Return the potential map (the dual solution). |
639 | 638 |
/// |
640 | 639 |
/// This function copies the potential (dual value) of each node |
641 | 640 |
/// into the given map. |
642 | 641 |
/// The \c Cost type of the algorithm must be convertible to the |
643 | 642 |
/// \c Value type of the map. |
644 | 643 |
/// |
645 | 644 |
/// \pre \ref run() must be called before using this function. |
646 | 645 |
template <typename PotentialMap> |
647 | 646 |
void potentialMap(PotentialMap &map) const { |
648 | 647 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
649 | 648 |
map.set(n, static_cast<Cost>(_pi[_node_id[n]])); |
650 | 649 |
} |
651 | 650 |
} |
652 | 651 |
|
653 | 652 |
/// @} |
654 | 653 |
|
655 | 654 |
private: |
656 | 655 |
|
657 | 656 |
// Initialize the algorithm |
658 | 657 |
ProblemType init() { |
659 | 658 |
if (_res_node_num <= 1) return INFEASIBLE; |
660 | 659 |
|
661 | 660 |
// Check the sum of supply values |
662 | 661 |
_sum_supply = 0; |
663 | 662 |
for (int i = 0; i != _root; ++i) { |
664 | 663 |
_sum_supply += _supply[i]; |
665 | 664 |
} |
666 | 665 |
if (_sum_supply > 0) return INFEASIBLE; |
667 | 666 |
|
668 | 667 |
|
669 | 668 |
// Initialize vectors |
670 | 669 |
for (int i = 0; i != _res_node_num; ++i) { |
671 | 670 |
_pi[i] = 0; |
672 | 671 |
} |
673 | 672 |
ValueVector excess(_supply); |
674 | 673 |
|
675 | 674 |
// Remove infinite upper bounds and check negative arcs |
676 | 675 |
const Value MAX = std::numeric_limits<Value>::max(); |
677 | 676 |
int last_out; |
678 | 677 |
if (_have_lower) { |
679 | 678 |
for (int i = 0; i != _root; ++i) { |
680 | 679 |
last_out = _first_out[i+1]; |
681 | 680 |
for (int j = _first_out[i]; j != last_out; ++j) { |
682 | 681 |
if (_forward[j]) { |
683 | 682 |
Value c = _cost[j] < 0 ? _upper[j] : _lower[j]; |
684 | 683 |
if (c >= MAX) return UNBOUNDED; |
685 | 684 |
excess[i] -= c; |
686 | 685 |
excess[_target[j]] += c; |
687 | 686 |
} |
688 | 687 |
} |
689 | 688 |
} |
690 | 689 |
} else { |
691 | 690 |
for (int i = 0; i != _root; ++i) { |
692 | 691 |
last_out = _first_out[i+1]; |
693 | 692 |
for (int j = _first_out[i]; j != last_out; ++j) { |
694 | 693 |
if (_forward[j] && _cost[j] < 0) { |
695 | 694 |
Value c = _upper[j]; |
696 | 695 |
if (c >= MAX) return UNBOUNDED; |
697 | 696 |
excess[i] -= c; |
698 | 697 |
excess[_target[j]] += c; |
699 | 698 |
} |
700 | 699 |
} |
701 | 700 |
} |
702 | 701 |
} |
703 | 702 |
Value ex, max_cap = 0; |
704 | 703 |
for (int i = 0; i != _res_node_num; ++i) { |
705 | 704 |
ex = excess[i]; |
706 | 705 |
if (ex < 0) max_cap -= ex; |
707 | 706 |
} |
708 | 707 |
for (int j = 0; j != _res_arc_num; ++j) { |
709 | 708 |
if (_upper[j] >= MAX) _upper[j] = max_cap; |
710 | 709 |
} |
711 | 710 |
|
712 | 711 |
// Initialize maps for Circulation and remove non-zero lower bounds |
713 | 712 |
ConstMap<Arc, Value> low(0); |
714 | 713 |
typedef typename Digraph::template ArcMap<Value> ValueArcMap; |
715 | 714 |
typedef typename Digraph::template NodeMap<Value> ValueNodeMap; |
716 | 715 |
ValueArcMap cap(_graph), flow(_graph); |
717 | 716 |
ValueNodeMap sup(_graph); |
718 | 717 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
719 | 718 |
sup[n] = _supply[_node_id[n]]; |
720 | 719 |
} |
721 | 720 |
if (_have_lower) { |
722 | 721 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
723 | 722 |
int j = _arc_idf[a]; |
724 | 723 |
Value c = _lower[j]; |
725 | 724 |
cap[a] = _upper[j] - c; |
726 | 725 |
sup[_graph.source(a)] -= c; |
727 | 726 |
sup[_graph.target(a)] += c; |
728 | 727 |
} |
729 | 728 |
} else { |
730 | 729 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
731 | 730 |
cap[a] = _upper[_arc_idf[a]]; |
732 | 731 |
} |
733 | 732 |
} |
734 | 733 |
|
735 | 734 |
// Find a feasible flow using Circulation |
736 | 735 |
Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap> |
737 | 736 |
circ(_graph, low, cap, sup); |
738 | 737 |
if (!circ.flowMap(flow).run()) return INFEASIBLE; |
739 | 738 |
|
740 | 739 |
// Set residual capacities and handle GEQ supply type |
741 | 740 |
if (_sum_supply < 0) { |
742 | 741 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
743 | 742 |
Value fa = flow[a]; |
744 | 743 |
_res_cap[_arc_idf[a]] = cap[a] - fa; |
745 | 744 |
_res_cap[_arc_idb[a]] = fa; |
746 | 745 |
sup[_graph.source(a)] -= fa; |
747 | 746 |
sup[_graph.target(a)] += fa; |
748 | 747 |
} |
749 | 748 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
750 | 749 |
excess[_node_id[n]] = sup[n]; |
751 | 750 |
} |
752 | 751 |
for (int a = _first_out[_root]; a != _res_arc_num; ++a) { |
753 | 752 |
int u = _target[a]; |
754 | 753 |
int ra = _reverse[a]; |
755 | 754 |
_res_cap[a] = -_sum_supply + 1; |
756 | 755 |
_res_cap[ra] = -excess[u]; |
757 | 756 |
_cost[a] = 0; |
758 | 757 |
_cost[ra] = 0; |
759 | 758 |
} |
760 | 759 |
} else { |
761 | 760 |
for (ArcIt a(_graph); a != INVALID; ++a) { |
762 | 761 |
Value fa = flow[a]; |
763 | 762 |
_res_cap[_arc_idf[a]] = cap[a] - fa; |
764 | 763 |
_res_cap[_arc_idb[a]] = fa; |
765 | 764 |
} |
766 | 765 |
for (int a = _first_out[_root]; a != _res_arc_num; ++a) { |
767 | 766 |
int ra = _reverse[a]; |
768 | 767 |
_res_cap[a] = 1; |
769 | 768 |
_res_cap[ra] = 0; |
770 | 769 |
_cost[a] = 0; |
771 | 770 |
_cost[ra] = 0; |
772 | 771 |
} |
773 | 772 |
} |
774 | 773 |
|
775 | 774 |
return OPTIMAL; |
776 | 775 |
} |
777 | 776 |
|
778 | 777 |
// Build a StaticDigraph structure containing the current |
779 | 778 |
// residual network |
780 | 779 |
void buildResidualNetwork() { |
781 | 780 |
_arc_vec.clear(); |
782 | 781 |
_cost_vec.clear(); |
783 | 782 |
_id_vec.clear(); |
784 | 783 |
for (int j = 0; j != _res_arc_num; ++j) { |
785 | 784 |
if (_res_cap[j] > 0) { |
786 | 785 |
_arc_vec.push_back(IntPair(_source[j], _target[j])); |
787 | 786 |
_cost_vec.push_back(_cost[j]); |
788 | 787 |
_id_vec.push_back(j); |
789 | 788 |
} |
790 | 789 |
} |
791 | 790 |
_sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end()); |
792 | 791 |
} |
793 | 792 |
|
794 | 793 |
// Execute the algorithm and transform the results |
795 | 794 |
void start(Method method) { |
796 | 795 |
// Execute the algorithm |
797 | 796 |
switch (method) { |
798 | 797 |
case SIMPLE_CYCLE_CANCELING: |
799 | 798 |
startSimpleCycleCanceling(); |
800 | 799 |
break; |
801 | 800 |
case MINIMUM_MEAN_CYCLE_CANCELING: |
802 | 801 |
startMinMeanCycleCanceling(); |
803 | 802 |
break; |
804 | 803 |
case CANCEL_AND_TIGHTEN: |
805 | 804 |
startCancelAndTighten(); |
806 | 805 |
break; |
807 | 806 |
} |
808 | 807 |
|
809 | 808 |
// Compute node potentials |
810 | 809 |
if (method != SIMPLE_CYCLE_CANCELING) { |
811 | 810 |
buildResidualNetwork(); |
812 | 811 |
typename BellmanFord<StaticDigraph, CostArcMap> |
813 | 812 |
::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map); |
814 | 813 |
bf.distMap(_pi_map); |
815 | 814 |
bf.init(0); |
816 | 815 |
bf.start(); |
817 | 816 |
} |
818 | 817 |
|
819 | 818 |
// Handle non-zero lower bounds |
820 | 819 |
if (_have_lower) { |
821 | 820 |
int limit = _first_out[_root]; |
822 | 821 |
for (int j = 0; j != limit; ++j) { |
823 | 822 |
if (!_forward[j]) _res_cap[j] += _lower[j]; |
824 | 823 |
} |
825 | 824 |
} |
826 | 825 |
} |
827 | 826 |
|
828 | 827 |
// Execute the "Simple Cycle Canceling" method |
829 | 828 |
void startSimpleCycleCanceling() { |
830 | 829 |
// Constants for computing the iteration limits |
831 | 830 |
const int BF_FIRST_LIMIT = 2; |
832 | 831 |
const double BF_LIMIT_FACTOR = 1.5; |
833 | 832 |
|
834 | 833 |
typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap; |
835 | 834 |
typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph; |
836 | 835 |
typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap; |
837 | 836 |
typedef typename BellmanFord<ResDigraph, CostArcMap> |
838 | 837 |
::template SetDistMap<CostNodeMap> |
839 | 838 |
::template SetPredMap<PredMap>::Create BF; |
840 | 839 |
|
841 | 840 |
// Build the residual network |
842 | 841 |
_arc_vec.clear(); |
843 | 842 |
_cost_vec.clear(); |
844 | 843 |
for (int j = 0; j != _res_arc_num; ++j) { |
845 | 844 |
_arc_vec.push_back(IntPair(_source[j], _target[j])); |
846 | 845 |
_cost_vec.push_back(_cost[j]); |
847 | 846 |
} |
848 | 847 |
_sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end()); |
849 | 848 |
|
850 | 849 |
FilterMap filter_map(_res_cap); |
851 | 850 |
ResDigraph rgr(_sgr, filter_map); |
852 | 851 |
std::vector<int> cycle; |
853 | 852 |
std::vector<StaticDigraph::Arc> pred(_res_arc_num); |
854 | 853 |
PredMap pred_map(pred); |
855 | 854 |
BF bf(rgr, _cost_map); |
856 | 855 |
bf.distMap(_pi_map).predMap(pred_map); |
857 | 856 |
|
858 | 857 |
int length_bound = BF_FIRST_LIMIT; |
859 | 858 |
bool optimal = false; |
860 | 859 |
while (!optimal) { |
861 | 860 |
bf.init(0); |
862 | 861 |
int iter_num = 0; |
863 | 862 |
bool cycle_found = false; |
864 | 863 |
while (!cycle_found) { |
865 | 864 |
// Perform some iterations of the Bellman-Ford algorithm |
866 | 865 |
int curr_iter_num = iter_num + length_bound <= _node_num ? |
867 | 866 |
length_bound : _node_num - iter_num; |
868 | 867 |
iter_num += curr_iter_num; |
869 | 868 |
int real_iter_num = curr_iter_num; |
870 | 869 |
for (int i = 0; i < curr_iter_num; ++i) { |
871 | 870 |
if (bf.processNextWeakRound()) { |
872 | 871 |
real_iter_num = i; |
873 | 872 |
break; |
874 | 873 |
} |
875 | 874 |
} |
876 | 875 |
if (real_iter_num < curr_iter_num) { |
877 | 876 |
// Optimal flow is found |
878 | 877 |
optimal = true; |
879 | 878 |
break; |
880 | 879 |
} else { |
881 | 880 |
// Search for node disjoint negative cycles |
882 | 881 |
std::vector<int> state(_res_node_num, 0); |
883 | 882 |
int id = 0; |
884 | 883 |
for (int u = 0; u != _res_node_num; ++u) { |
885 | 884 |
if (state[u] != 0) continue; |
886 | 885 |
++id; |
887 | 886 |
int v = u; |
888 | 887 |
for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ? |
889 | 888 |
-1 : rgr.id(rgr.source(pred[v]))) { |
890 | 889 |
state[v] = id; |
891 | 890 |
} |
892 | 891 |
if (v != -1 && state[v] == id) { |
893 | 892 |
// A negative cycle is found |
894 | 893 |
cycle_found = true; |
895 | 894 |
cycle.clear(); |
896 | 895 |
StaticDigraph::Arc a = pred[v]; |
897 | 896 |
Value d, delta = _res_cap[rgr.id(a)]; |
898 | 897 |
cycle.push_back(rgr.id(a)); |
899 | 898 |
while (rgr.id(rgr.source(a)) != v) { |
900 | 899 |
a = pred_map[rgr.source(a)]; |
901 | 900 |
d = _res_cap[rgr.id(a)]; |
902 | 901 |
if (d < delta) delta = d; |
903 | 902 |
cycle.push_back(rgr.id(a)); |
904 | 903 |
} |
905 | 904 |
|
906 | 905 |
// Augment along the cycle |
907 | 906 |
for (int i = 0; i < int(cycle.size()); ++i) { |
908 | 907 |
int j = cycle[i]; |
909 | 908 |
_res_cap[j] -= delta; |
910 | 909 |
_res_cap[_reverse[j]] += delta; |
911 | 910 |
} |
912 | 911 |
} |
913 | 912 |
} |
914 | 913 |
} |
915 | 914 |
|
916 | 915 |
// Increase iteration limit if no cycle is found |
917 | 916 |
if (!cycle_found) { |
918 | 917 |
length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR); |
919 | 918 |
} |
920 | 919 |
} |
921 | 920 |
} |
922 | 921 |
} |
923 | 922 |
|
924 | 923 |
// Execute the "Minimum Mean Cycle Canceling" method |
925 | 924 |
void startMinMeanCycleCanceling() { |
926 | 925 |
typedef SimplePath<StaticDigraph> SPath; |
927 | 926 |
typedef typename SPath::ArcIt SPathArcIt; |
928 | 927 |
typedef typename HowardMmc<StaticDigraph, CostArcMap> |
929 | 928 |
::template SetPath<SPath>::Create MMC; |
930 | 929 |
|
931 | 930 |
SPath cycle; |
932 | 931 |
MMC mmc(_sgr, _cost_map); |
933 | 932 |
mmc.cycle(cycle); |
934 | 933 |
buildResidualNetwork(); |
935 | 934 |
while (mmc.findCycleMean() && mmc.cycleCost() < 0) { |
936 | 935 |
// Find the cycle |
937 | 936 |
mmc.findCycle(); |
938 | 937 |
|
939 | 938 |
// Compute delta value |
940 | 939 |
Value delta = INF; |
941 | 940 |
for (SPathArcIt a(cycle); a != INVALID; ++a) { |
942 | 941 |
Value d = _res_cap[_id_vec[_sgr.id(a)]]; |
943 | 942 |
if (d < delta) delta = d; |
944 | 943 |
} |
945 | 944 |
|
946 | 945 |
// Augment along the cycle |
947 | 946 |
for (SPathArcIt a(cycle); a != INVALID; ++a) { |
948 | 947 |
int j = _id_vec[_sgr.id(a)]; |
949 | 948 |
_res_cap[j] -= delta; |
950 | 949 |
_res_cap[_reverse[j]] += delta; |
951 | 950 |
} |
952 | 951 |
|
953 | 952 |
// Rebuild the residual network |
954 | 953 |
buildResidualNetwork(); |
955 | 954 |
} |
956 | 955 |
} |
957 | 956 |
|
958 | 957 |
// Execute the "Cancel And Tighten" method |
959 | 958 |
void startCancelAndTighten() { |
960 | 959 |
// Constants for the min mean cycle computations |
961 | 960 |
const double LIMIT_FACTOR = 1.0; |
962 | 961 |
const int MIN_LIMIT = 5; |
963 | 962 |
|
964 | 963 |
// Contruct auxiliary data vectors |
965 | 964 |
DoubleVector pi(_res_node_num, 0.0); |
966 | 965 |
IntVector level(_res_node_num); |
967 | 966 |
BoolVector reached(_res_node_num); |
968 | 967 |
BoolVector processed(_res_node_num); |
969 | 968 |
IntVector pred_node(_res_node_num); |
970 | 969 |
IntVector pred_arc(_res_node_num); |
971 | 970 |
std::vector<int> stack(_res_node_num); |
972 | 971 |
std::vector<int> proc_vector(_res_node_num); |
973 | 972 |
|
974 | 973 |
// Initialize epsilon |
975 | 974 |
double epsilon = 0; |
976 | 975 |
for (int a = 0; a != _res_arc_num; ++a) { |
977 | 976 |
if (_res_cap[a] > 0 && -_cost[a] > epsilon) |
978 | 977 |
epsilon = -_cost[a]; |
979 | 978 |
} |
980 | 979 |
|
981 | 980 |
// Start phases |
982 | 981 |
Tolerance<double> tol; |
983 | 982 |
tol.epsilon(1e-6); |
984 | 983 |
int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num))); |
985 | 984 |
if (limit < MIN_LIMIT) limit = MIN_LIMIT; |
986 | 985 |
int iter = limit; |
987 | 986 |
while (epsilon * _res_node_num >= 1) { |
988 | 987 |
// Find and cancel cycles in the admissible network using DFS |
989 | 988 |
for (int u = 0; u != _res_node_num; ++u) { |
990 | 989 |
reached[u] = false; |
991 | 990 |
processed[u] = false; |
992 | 991 |
} |
993 | 992 |
int stack_head = -1; |
994 | 993 |
int proc_head = -1; |
995 | 994 |
for (int start = 0; start != _res_node_num; ++start) { |
996 | 995 |
if (reached[start]) continue; |
997 | 996 |
|
998 | 997 |
// New start node |
999 | 998 |
reached[start] = true; |
1000 | 999 |
pred_arc[start] = -1; |
1001 | 1000 |
pred_node[start] = -1; |
1002 | 1001 |
|
1003 | 1002 |
// Find the first admissible outgoing arc |
1004 | 1003 |
double p = pi[start]; |
1005 | 1004 |
int a = _first_out[start]; |
1006 | 1005 |
int last_out = _first_out[start+1]; |
1007 | 1006 |
for (; a != last_out && (_res_cap[a] == 0 || |
1008 | 1007 |
!tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ; |
1009 | 1008 |
if (a == last_out) { |
1010 | 1009 |
processed[start] = true; |
1011 | 1010 |
proc_vector[++proc_head] = start; |
1012 | 1011 |
continue; |
1013 | 1012 |
} |
1014 | 1013 |
stack[++stack_head] = a; |
1015 | 1014 |
|
1016 | 1015 |
while (stack_head >= 0) { |
1017 | 1016 |
int sa = stack[stack_head]; |
1018 | 1017 |
int u = _source[sa]; |
1019 | 1018 |
int v = _target[sa]; |
1020 | 1019 |
|
1021 | 1020 |
if (!reached[v]) { |
1022 | 1021 |
// A new node is reached |
1023 | 1022 |
reached[v] = true; |
1024 | 1023 |
pred_node[v] = u; |
1025 | 1024 |
pred_arc[v] = sa; |
1026 | 1025 |
p = pi[v]; |
1027 | 1026 |
a = _first_out[v]; |
1028 | 1027 |
last_out = _first_out[v+1]; |
1029 | 1028 |
for (; a != last_out && (_res_cap[a] == 0 || |
1030 | 1029 |
!tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ; |
1031 | 1030 |
stack[++stack_head] = a == last_out ? -1 : a; |
1032 | 1031 |
} else { |
1033 | 1032 |
if (!processed[v]) { |
1034 | 1033 |
// A cycle is found |
1035 | 1034 |
int n, w = u; |
1036 | 1035 |
Value d, delta = _res_cap[sa]; |
1037 | 1036 |
for (n = u; n != v; n = pred_node[n]) { |
1038 | 1037 |
d = _res_cap[pred_arc[n]]; |
1039 | 1038 |
if (d <= delta) { |
1040 | 1039 |
delta = d; |
1041 | 1040 |
w = pred_node[n]; |
1042 | 1041 |
} |
1043 | 1042 |
} |
1044 | 1043 |
|
1045 | 1044 |
// Augment along the cycle |
1046 | 1045 |
_res_cap[sa] -= delta; |
1047 | 1046 |
_res_cap[_reverse[sa]] += delta; |
1048 | 1047 |
for (n = u; n != v; n = pred_node[n]) { |
1049 | 1048 |
int pa = pred_arc[n]; |
1050 | 1049 |
_res_cap[pa] -= delta; |
1051 | 1050 |
_res_cap[_reverse[pa]] += delta; |
1052 | 1051 |
} |
1053 | 1052 |
for (n = u; stack_head > 0 && n != w; n = pred_node[n]) { |
1054 | 1053 |
--stack_head; |
1055 | 1054 |
reached[n] = false; |
1056 | 1055 |
} |
1057 | 1056 |
u = w; |
1058 | 1057 |
} |
1059 | 1058 |
v = u; |
1060 | 1059 |
|
1061 | 1060 |
// Find the next admissible outgoing arc |
1062 | 1061 |
p = pi[v]; |
1063 | 1062 |
a = stack[stack_head] + 1; |
1064 | 1063 |
last_out = _first_out[v+1]; |
1065 | 1064 |
for (; a != last_out && (_res_cap[a] == 0 || |
1066 | 1065 |
!tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ; |
1067 | 1066 |
stack[stack_head] = a == last_out ? -1 : a; |
1068 | 1067 |
} |
1069 | 1068 |
|
1070 | 1069 |
while (stack_head >= 0 && stack[stack_head] == -1) { |
1071 | 1070 |
processed[v] = true; |
1072 | 1071 |
proc_vector[++proc_head] = v; |
1073 | 1072 |
if (--stack_head >= 0) { |
1074 | 1073 |
// Find the next admissible outgoing arc |
1075 | 1074 |
v = _source[stack[stack_head]]; |
1076 | 1075 |
p = pi[v]; |
1077 | 1076 |
a = stack[stack_head] + 1; |
1078 | 1077 |
last_out = _first_out[v+1]; |
1079 | 1078 |
for (; a != last_out && (_res_cap[a] == 0 || |
1080 | 1079 |
!tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ; |
1081 | 1080 |
stack[stack_head] = a == last_out ? -1 : a; |
1082 | 1081 |
} |
1083 | 1082 |
} |
1084 | 1083 |
} |
1085 | 1084 |
} |
1086 | 1085 |
|
1087 | 1086 |
// Tighten potentials and epsilon |
1088 | 1087 |
if (--iter > 0) { |
1089 | 1088 |
for (int u = 0; u != _res_node_num; ++u) { |
1090 | 1089 |
level[u] = 0; |
1091 | 1090 |
} |
1092 | 1091 |
for (int i = proc_head; i > 0; --i) { |
1093 | 1092 |
int u = proc_vector[i]; |
1094 | 1093 |
double p = pi[u]; |
1095 | 1094 |
int l = level[u] + 1; |
1096 | 1095 |
int last_out = _first_out[u+1]; |
1097 | 1096 |
for (int a = _first_out[u]; a != last_out; ++a) { |
1098 | 1097 |
int v = _target[a]; |
1099 | 1098 |
if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) && |
1100 | 1099 |
l > level[v]) level[v] = l; |
1101 | 1100 |
} |
1102 | 1101 |
} |
1103 | 1102 |
|
1104 | 1103 |
// Modify potentials |
1105 | 1104 |
double q = std::numeric_limits<double>::max(); |
1106 | 1105 |
for (int u = 0; u != _res_node_num; ++u) { |
1107 | 1106 |
int lu = level[u]; |
1108 | 1107 |
double p, pu = pi[u]; |
1109 | 1108 |
int last_out = _first_out[u+1]; |
1110 | 1109 |
for (int a = _first_out[u]; a != last_out; ++a) { |
1111 | 1110 |
if (_res_cap[a] == 0) continue; |
1112 | 1111 |
int v = _target[a]; |
1113 | 1112 |
int ld = lu - level[v]; |
1114 | 1113 |
if (ld > 0) { |
1115 | 1114 |
p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1); |
1116 | 1115 |
if (p < q) q = p; |
1117 | 1116 |
} |
1118 | 1117 |
} |
1119 | 1118 |
} |
1120 | 1119 |
for (int u = 0; u != _res_node_num; ++u) { |
1121 | 1120 |
pi[u] -= q * level[u]; |
1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2010 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
#ifndef LEMON_EULER_H |
20 | 20 |
#define LEMON_EULER_H |
21 | 21 |
|
22 | 22 |
#include<lemon/core.h> |
23 | 23 |
#include<lemon/adaptors.h> |
24 | 24 |
#include<lemon/connectivity.h> |
25 | 25 |
#include <list> |
26 | 26 |
|
27 | 27 |
/// \ingroup graph_properties |
28 | 28 |
/// \file |
29 | 29 |
/// \brief Euler tour iterators and a function for checking the \e Eulerian |
30 | 30 |
/// property. |
31 | 31 |
/// |
32 | 32 |
///This file provides Euler tour iterators and a function to check |
33 | 33 |
///if a (di)graph is \e Eulerian. |
34 | 34 |
|
35 | 35 |
namespace lemon { |
36 | 36 |
|
37 | 37 |
///Euler tour iterator for digraphs. |
38 | 38 |
|
39 |
/// \ingroup |
|
39 |
/// \ingroup graph_properties |
|
40 | 40 |
///This iterator provides an Euler tour (Eulerian circuit) of a \e directed |
41 | 41 |
///graph (if there exists) and it converts to the \c Arc type of the digraph. |
42 | 42 |
/// |
43 | 43 |
///For example, if the given digraph has an Euler tour (i.e it has only one |
44 | 44 |
///non-trivial component and the in-degree is equal to the out-degree |
45 | 45 |
///for all nodes), then the following code will put the arcs of \c g |
46 | 46 |
///to the vector \c et according to an Euler tour of \c g. |
47 | 47 |
///\code |
48 | 48 |
/// std::vector<ListDigraph::Arc> et; |
49 | 49 |
/// for(DiEulerIt<ListDigraph> e(g); e!=INVALID; ++e) |
50 | 50 |
/// et.push_back(e); |
51 | 51 |
///\endcode |
52 | 52 |
///If \c g has no Euler tour, then the resulted walk will not be closed |
53 | 53 |
///or not contain all arcs. |
54 | 54 |
///\sa EulerIt |
55 | 55 |
template<typename GR> |
56 | 56 |
class DiEulerIt |
57 | 57 |
{ |
58 | 58 |
typedef typename GR::Node Node; |
59 | 59 |
typedef typename GR::NodeIt NodeIt; |
60 | 60 |
typedef typename GR::Arc Arc; |
61 | 61 |
typedef typename GR::ArcIt ArcIt; |
62 | 62 |
typedef typename GR::OutArcIt OutArcIt; |
63 | 63 |
typedef typename GR::InArcIt InArcIt; |
64 | 64 |
|
65 | 65 |
const GR &g; |
66 | 66 |
typename GR::template NodeMap<OutArcIt> narc; |
67 | 67 |
std::list<Arc> euler; |
68 | 68 |
|
69 | 69 |
public: |
70 | 70 |
|
71 | 71 |
///Constructor |
72 | 72 |
|
73 | 73 |
///Constructor. |
74 | 74 |
///\param gr A digraph. |
75 | 75 |
///\param start The starting point of the tour. If it is not given, |
76 | 76 |
///the tour will start from the first node that has an outgoing arc. |
77 | 77 |
DiEulerIt(const GR &gr, typename GR::Node start = INVALID) |
78 | 78 |
: g(gr), narc(g) |
79 | 79 |
{ |
80 | 80 |
if (start==INVALID) { |
81 | 81 |
NodeIt n(g); |
82 | 82 |
while (n!=INVALID && OutArcIt(g,n)==INVALID) ++n; |
83 | 83 |
start=n; |
84 | 84 |
} |
85 | 85 |
if (start!=INVALID) { |
86 | 86 |
for (NodeIt n(g); n!=INVALID; ++n) narc[n]=OutArcIt(g,n); |
87 | 87 |
while (narc[start]!=INVALID) { |
88 | 88 |
euler.push_back(narc[start]); |
89 | 89 |
Node next=g.target(narc[start]); |
90 | 90 |
++narc[start]; |
91 | 91 |
start=next; |
92 | 92 |
} |
93 | 93 |
} |
94 | 94 |
} |
95 | 95 |
|
96 | 96 |
///Arc conversion |
97 | 97 |
operator Arc() { return euler.empty()?INVALID:euler.front(); } |
98 | 98 |
///Compare with \c INVALID |
99 | 99 |
bool operator==(Invalid) { return euler.empty(); } |
100 | 100 |
///Compare with \c INVALID |
101 | 101 |
bool operator!=(Invalid) { return !euler.empty(); } |
102 | 102 |
|
103 | 103 |
///Next arc of the tour |
104 | 104 |
|
105 | 105 |
///Next arc of the tour |
106 | 106 |
/// |
107 | 107 |
DiEulerIt &operator++() { |
108 | 108 |
Node s=g.target(euler.front()); |
109 | 109 |
euler.pop_front(); |
110 | 110 |
typename std::list<Arc>::iterator next=euler.begin(); |
111 | 111 |
while(narc[s]!=INVALID) { |
112 | 112 |
euler.insert(next,narc[s]); |
113 | 113 |
Node n=g.target(narc[s]); |
114 | 114 |
++narc[s]; |
115 | 115 |
s=n; |
116 | 116 |
} |
117 | 117 |
return *this; |
118 | 118 |
} |
119 | 119 |
///Postfix incrementation |
120 | 120 |
|
121 | 121 |
/// Postfix incrementation. |
122 | 122 |
/// |
123 | 123 |
///\warning This incrementation |
124 | 124 |
///returns an \c Arc, not a \ref DiEulerIt, as one may |
125 | 125 |
///expect. |
126 | 126 |
Arc operator++(int) |
127 | 127 |
{ |
128 | 128 |
Arc e=*this; |
129 | 129 |
++(*this); |
130 | 130 |
return e; |
131 | 131 |
} |
132 | 132 |
}; |
133 | 133 |
|
134 | 134 |
///Euler tour iterator for graphs. |
135 | 135 |
|
136 | 136 |
/// \ingroup graph_properties |
137 | 137 |
///This iterator provides an Euler tour (Eulerian circuit) of an |
138 | 138 |
///\e undirected graph (if there exists) and it converts to the \c Arc |
139 | 139 |
///and \c Edge types of the graph. |
140 | 140 |
/// |
141 | 141 |
///For example, if the given graph has an Euler tour (i.e it has only one |
142 | 142 |
///non-trivial component and the degree of each node is even), |
143 | 143 |
///the following code will print the arc IDs according to an |
144 | 144 |
///Euler tour of \c g. |
145 | 145 |
///\code |
146 | 146 |
/// for(EulerIt<ListGraph> e(g); e!=INVALID; ++e) { |
147 | 147 |
/// std::cout << g.id(Edge(e)) << std::eol; |
148 | 148 |
/// } |
149 | 149 |
///\endcode |
150 | 150 |
///Although this iterator is for undirected graphs, it still returns |
151 | 151 |
///arcs in order to indicate the direction of the tour. |
152 | 152 |
///(But arcs convert to edges, of course.) |
153 | 153 |
/// |
154 | 154 |
///If \c g has no Euler tour, then the resulted walk will not be closed |
155 | 155 |
///or not contain all edges. |
156 | 156 |
template<typename GR> |
157 | 157 |
class EulerIt |
158 | 158 |
{ |
159 | 159 |
typedef typename GR::Node Node; |
160 | 160 |
typedef typename GR::NodeIt NodeIt; |
161 | 161 |
typedef typename GR::Arc Arc; |
162 | 162 |
typedef typename GR::Edge Edge; |
163 | 163 |
typedef typename GR::ArcIt ArcIt; |
164 | 164 |
typedef typename GR::OutArcIt OutArcIt; |
165 | 165 |
typedef typename GR::InArcIt InArcIt; |
166 | 166 |
|
167 | 167 |
const GR &g; |
168 | 168 |
typename GR::template NodeMap<OutArcIt> narc; |
169 | 169 |
typename GR::template EdgeMap<bool> visited; |
170 | 170 |
std::list<Arc> euler; |
171 | 171 |
|
172 | 172 |
public: |
173 | 173 |
|
174 | 174 |
///Constructor |
175 | 175 |
|
176 | 176 |
///Constructor. |
177 | 177 |
///\param gr A graph. |
178 | 178 |
///\param start The starting point of the tour. If it is not given, |
179 | 179 |
///the tour will start from the first node that has an incident edge. |
180 | 180 |
EulerIt(const GR &gr, typename GR::Node start = INVALID) |
181 | 181 |
: g(gr), narc(g), visited(g, false) |
182 | 182 |
{ |
183 | 183 |
if (start==INVALID) { |
184 | 184 |
NodeIt n(g); |
185 | 185 |
while (n!=INVALID && OutArcIt(g,n)==INVALID) ++n; |
186 | 186 |
start=n; |
187 | 187 |
} |
188 | 188 |
if (start!=INVALID) { |
189 | 189 |
for (NodeIt n(g); n!=INVALID; ++n) narc[n]=OutArcIt(g,n); |
190 | 190 |
while(narc[start]!=INVALID) { |
191 | 191 |
euler.push_back(narc[start]); |
192 | 192 |
visited[narc[start]]=true; |
193 | 193 |
Node next=g.target(narc[start]); |
194 | 194 |
++narc[start]; |
195 | 195 |
start=next; |
196 | 196 |
while(narc[start]!=INVALID && visited[narc[start]]) ++narc[start]; |
197 | 197 |
} |
198 | 198 |
} |
199 | 199 |
} |
200 | 200 |
|
201 | 201 |
///Arc conversion |
202 | 202 |
operator Arc() const { return euler.empty()?INVALID:euler.front(); } |
203 | 203 |
///Edge conversion |
204 | 204 |
operator Edge() const { return euler.empty()?INVALID:euler.front(); } |
205 | 205 |
///Compare with \c INVALID |
206 | 206 |
bool operator==(Invalid) const { return euler.empty(); } |
207 | 207 |
///Compare with \c INVALID |
208 | 208 |
bool operator!=(Invalid) const { return !euler.empty(); } |
209 | 209 |
|
210 | 210 |
///Next arc of the tour |
211 | 211 |
|
212 | 212 |
///Next arc of the tour |
213 | 213 |
/// |
214 | 214 |
EulerIt &operator++() { |
215 | 215 |
Node s=g.target(euler.front()); |
216 | 216 |
euler.pop_front(); |
217 | 217 |
typename std::list<Arc>::iterator next=euler.begin(); |
218 | 218 |
while(narc[s]!=INVALID) { |
219 | 219 |
while(narc[s]!=INVALID && visited[narc[s]]) ++narc[s]; |
220 | 220 |
if(narc[s]==INVALID) break; |
221 | 221 |
else { |
222 | 222 |
euler.insert(next,narc[s]); |
223 | 223 |
visited[narc[s]]=true; |
224 | 224 |
Node n=g.target(narc[s]); |
225 | 225 |
++narc[s]; |
226 | 226 |
s=n; |
227 | 227 |
} |
228 | 228 |
} |
229 | 229 |
return *this; |
230 | 230 |
} |
231 | 231 |
|
232 | 232 |
///Postfix incrementation |
233 | 233 |
|
234 | 234 |
/// Postfix incrementation. |
235 | 235 |
/// |
236 | 236 |
///\warning This incrementation returns an \c Arc (which converts to |
237 | 237 |
///an \c Edge), not an \ref EulerIt, as one may expect. |
238 | 238 |
Arc operator++(int) |
239 | 239 |
{ |
240 | 240 |
Arc e=*this; |
241 | 241 |
++(*this); |
242 | 242 |
return e; |
243 | 243 |
} |
244 | 244 |
}; |
245 | 245 |
|
246 | 246 |
|
247 | 247 |
///Check if the given graph is Eulerian |
248 | 248 |
|
249 | 249 |
/// \ingroup graph_properties |
250 | 250 |
///This function checks if the given graph is Eulerian. |
251 | 251 |
///It works for both directed and undirected graphs. |
252 | 252 |
/// |
253 | 253 |
///By definition, a digraph is called \e Eulerian if |
254 | 254 |
///and only if it is connected and the number of incoming and outgoing |
255 | 255 |
///arcs are the same for each node. |
256 | 256 |
///Similarly, an undirected graph is called \e Eulerian if |
257 | 257 |
///and only if it is connected and the number of incident edges is even |
258 | 258 |
///for each node. |
259 | 259 |
/// |
260 | 260 |
///\note There are (di)graphs that are not Eulerian, but still have an |
261 | 261 |
/// Euler tour, since they may contain isolated nodes. |
262 | 262 |
/// |
263 | 263 |
///\sa DiEulerIt, EulerIt |
264 | 264 |
template<typename GR> |
265 | 265 |
#ifdef DOXYGEN |
266 | 266 |
bool |
267 | 267 |
#else |
268 | 268 |
typename enable_if<UndirectedTagIndicator<GR>,bool>::type |
269 | 269 |
eulerian(const GR &g) |
270 | 270 |
{ |
271 | 271 |
for(typename GR::NodeIt n(g);n!=INVALID;++n) |
272 | 272 |
if(countIncEdges(g,n)%2) return false; |
273 | 273 |
return connected(g); |
274 | 274 |
} |
275 | 275 |
template<class GR> |
276 | 276 |
typename disable_if<UndirectedTagIndicator<GR>,bool>::type |
277 | 277 |
#endif |
278 | 278 |
eulerian(const GR &g) |
279 | 279 |
{ |
280 | 280 |
for(typename GR::NodeIt n(g);n!=INVALID;++n) |
281 | 281 |
if(countInArcs(g,n)!=countOutArcs(g,n)) return false; |
282 | 282 |
return connected(undirector(g)); |
283 | 283 |
} |
284 | 284 |
|
285 | 285 |
} |
286 | 286 |
|
287 | 287 |
#endif |
1 | 1 |
/* -*- mode: C++; indent-tabs-mode: nil; -*- |
2 | 2 |
* |
3 | 3 |
* This file is a part of LEMON, a generic C++ optimization library. |
4 | 4 |
* |
5 | 5 |
* Copyright (C) 2003-2010 |
6 | 6 |
* Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
7 | 7 |
* (Egervary Research Group on Combinatorial Optimization, EGRES). |
8 | 8 |
* |
9 | 9 |
* Permission to use, modify and distribute this software is granted |
10 | 10 |
* provided that this copyright notice appears in all copies. For |
11 | 11 |
* precise terms see the accompanying LICENSE file. |
12 | 12 |
* |
13 | 13 |
* This software is provided "AS IS" with no warranty of any kind, |
14 | 14 |
* express or implied, and with no claim as to its suitability for any |
15 | 15 |
* purpose. |
16 | 16 |
* |
17 | 17 |
*/ |
18 | 18 |
|
19 | 19 |
#ifndef LEMON_GROSSO_LOCATELLI_PULLAN_MC_H |
20 | 20 |
#define LEMON_GROSSO_LOCATELLI_PULLAN_MC_H |
21 | 21 |
|
22 | 22 |
/// \ingroup approx_algs |
23 | 23 |
/// |
24 | 24 |
/// \file |
25 | 25 |
/// \brief The iterated local search algorithm of Grosso, Locatelli, and Pullan |
26 | 26 |
/// for the maximum clique problem |
27 | 27 |
|
28 | 28 |
#include <vector> |
29 | 29 |
#include <limits> |
30 | 30 |
#include <lemon/core.h> |
31 | 31 |
#include <lemon/random.h> |
32 | 32 |
|
33 | 33 |
namespace lemon { |
34 | 34 |
|
35 | 35 |
/// \addtogroup approx_algs |
36 | 36 |
/// @{ |
37 | 37 |
|
38 | 38 |
/// \brief Implementation of the iterated local search algorithm of Grosso, |
39 | 39 |
/// Locatelli, and Pullan for the maximum clique problem |
40 | 40 |
/// |
41 | 41 |
/// \ref GrossoLocatelliPullanMc implements the iterated local search |
42 | 42 |
/// algorithm of Grosso, Locatelli, and Pullan for solving the \e maximum |
43 | 43 |
/// \e clique \e problem \ref grosso08maxclique. |
44 | 44 |
/// It is to find the largest complete subgraph (\e clique) in an |
45 | 45 |
/// undirected graph, i.e., the largest set of nodes where each |
46 | 46 |
/// pair of nodes is connected. |
47 | 47 |
/// |
48 | 48 |
/// This class provides a simple but highly efficient and robust heuristic |
49 |
/// method that quickly finds a large clique, but not necessarily the |
|
49 |
/// method that quickly finds a quite large clique, but not necessarily the |
|
50 | 50 |
/// largest one. |
51 |
/// The algorithm performs a certain number of iterations to find several |
|
52 |
/// cliques and selects the largest one among them. Various limits can be |
|
53 |
/// specified to control the running time and the effectiveness of the |
|
54 |
/// search process. |
|
51 | 55 |
/// |
52 | 56 |
/// \tparam GR The undirected graph type the algorithm runs on. |
53 | 57 |
/// |
54 | 58 |
/// \note %GrossoLocatelliPullanMc provides three different node selection |
55 | 59 |
/// rules, from which the most powerful one is used by default. |
56 | 60 |
/// For more information, see \ref SelectionRule. |
57 | 61 |
template <typename GR> |
58 | 62 |
class GrossoLocatelliPullanMc |
59 | 63 |
{ |
60 | 64 |
public: |
61 | 65 |
|
62 | 66 |
/// \brief Constants for specifying the node selection rule. |
63 | 67 |
/// |
64 | 68 |
/// Enum type containing constants for specifying the node selection rule |
65 | 69 |
/// for the \ref run() function. |
66 | 70 |
/// |
67 | 71 |
/// During the algorithm, nodes are selected for addition to the current |
68 | 72 |
/// clique according to the applied rule. |
69 | 73 |
/// In general, the PENALTY_BASED rule turned out to be the most powerful |
70 | 74 |
/// and the most robust, thus it is the default option. |
71 | 75 |
/// However, another selection rule can be specified using the \ref run() |
72 | 76 |
/// function with the proper parameter. |
73 | 77 |
enum SelectionRule { |
74 | 78 |
|
75 | 79 |
/// A node is selected randomly without any evaluation at each step. |
76 | 80 |
RANDOM, |
77 | 81 |
|
78 | 82 |
/// A node of maximum degree is selected randomly at each step. |
79 | 83 |
DEGREE_BASED, |
80 | 84 |
|
81 | 85 |
/// A node of minimum penalty is selected randomly at each step. |
82 | 86 |
/// The node penalties are updated adaptively after each stage of the |
83 | 87 |
/// search process. |
84 | 88 |
PENALTY_BASED |
85 | 89 |
}; |
86 | 90 |
|
91 |
/// \brief Constants for the causes of search termination. |
|
92 |
/// |
|
93 |
/// Enum type containing constants for the different causes of search |
|
94 |
/// termination. The \ref run() function returns one of these values. |
|
95 |
enum TerminationCause { |
|
96 |
|
|
97 |
/// The iteration count limit is reached. |
|
98 |
ITERATION_LIMIT, |
|
99 |
|
|
100 |
/// The step count limit is reached. |
|
101 |
STEP_LIMIT, |
|
102 |
|
|
103 |
/// The clique size limit is reached. |
|
104 |
SIZE_LIMIT |
|
105 |
}; |
|
106 |
|
|
87 | 107 |
private: |
88 | 108 |
|
89 | 109 |
TEMPLATE_GRAPH_TYPEDEFS(GR); |
90 | 110 |
|
91 | 111 |
typedef std::vector<int> IntVector; |
92 | 112 |
typedef std::vector<char> BoolVector; |
93 | 113 |
typedef std::vector<BoolVector> BoolMatrix; |
94 | 114 |
// Note: vector<char> is used instead of vector<bool> for efficiency reasons |
95 | 115 |
|
116 |
// The underlying graph |
|
96 | 117 |
const GR &_graph; |
97 | 118 |
IntNodeMap _id; |
98 | 119 |
|
99 | 120 |
// Internal matrix representation of the graph |
100 | 121 |
BoolMatrix _gr; |
101 | 122 |
int _n; |
102 | 123 |
|
124 |
// Search options |
|
125 |
bool _delta_based_restart; |
|
126 |
int _restart_delta_limit; |
|
127 |
|
|
128 |
// Search limits |
|
129 |
int _iteration_limit; |
|
130 |
int _step_limit; |
|
131 |
int _size_limit; |
|
132 |
|
|
103 | 133 |
// The current clique |
104 | 134 |
BoolVector _clique; |
105 | 135 |
int _size; |
106 | 136 |
|
107 | 137 |
// The best clique found so far |
108 | 138 |
BoolVector _best_clique; |
109 | 139 |
int _best_size; |
110 | 140 |
|
111 | 141 |
// The "distances" of the nodes from the current clique. |
112 | 142 |
// _delta[u] is the number of nodes in the clique that are |
113 | 143 |
// not connected with u. |
114 | 144 |
IntVector _delta; |
115 | 145 |
|
116 | 146 |
// The current tabu set |
117 | 147 |
BoolVector _tabu; |
118 | 148 |
|
119 | 149 |
// Random number generator |
120 | 150 |
Random _rnd; |
121 | 151 |
|
122 | 152 |
private: |
123 | 153 |
|
124 | 154 |
// Implementation of the RANDOM node selection rule. |
125 | 155 |
class RandomSelectionRule |
126 | 156 |
{ |
127 | 157 |
private: |
128 | 158 |
|
129 | 159 |
// References to the algorithm instance |
130 | 160 |
const BoolVector &_clique; |
131 | 161 |
const IntVector &_delta; |
132 | 162 |
const BoolVector &_tabu; |
133 | 163 |
Random &_rnd; |
134 | 164 |
|
135 | 165 |
// Pivot rule data |
136 | 166 |
int _n; |
137 | 167 |
|
138 | 168 |
public: |
139 | 169 |
|
140 | 170 |
// Constructor |
141 | 171 |
RandomSelectionRule(GrossoLocatelliPullanMc &mc) : |
142 | 172 |
_clique(mc._clique), _delta(mc._delta), _tabu(mc._tabu), |
143 | 173 |
_rnd(mc._rnd), _n(mc._n) |
144 | 174 |
{} |
145 | 175 |
|
146 | 176 |
// Return a node index for a feasible add move or -1 if no one exists |
147 | 177 |
int nextFeasibleAddNode() const { |
148 | 178 |
int start_node = _rnd[_n]; |
149 | 179 |
for (int i = start_node; i != _n; i++) { |
150 | 180 |
if (_delta[i] == 0 && !_tabu[i]) return i; |
151 | 181 |
} |
152 | 182 |
for (int i = 0; i != start_node; i++) { |
153 | 183 |
if (_delta[i] == 0 && !_tabu[i]) return i; |
154 | 184 |
} |
155 | 185 |
return -1; |
156 | 186 |
} |
157 | 187 |
|
158 | 188 |
// Return a node index for a feasible swap move or -1 if no one exists |
159 | 189 |
int nextFeasibleSwapNode() const { |
160 | 190 |
int start_node = _rnd[_n]; |
161 | 191 |
for (int i = start_node; i != _n; i++) { |
162 | 192 |
if (!_clique[i] && _delta[i] == 1 && !_tabu[i]) return i; |
163 | 193 |
} |
164 | 194 |
for (int i = 0; i != start_node; i++) { |
165 | 195 |
if (!_clique[i] && _delta[i] == 1 && !_tabu[i]) return i; |
166 | 196 |
} |
167 | 197 |
return -1; |
168 | 198 |
} |
169 | 199 |
|
170 | 200 |
// Return a node index for an add move or -1 if no one exists |
171 | 201 |
int nextAddNode() const { |
172 | 202 |
int start_node = _rnd[_n]; |
173 | 203 |
for (int i = start_node; i != _n; i++) { |
174 | 204 |
if (_delta[i] == 0) return i; |
175 | 205 |
} |
176 | 206 |
for (int i = 0; i != start_node; i++) { |
177 | 207 |
if (_delta[i] == 0) return i; |
178 | 208 |
} |
179 | 209 |
return -1; |
180 | 210 |
} |
181 | 211 |
|
182 | 212 |
// Update internal data structures between stages (if necessary) |
183 | 213 |
void update() {} |
184 | 214 |
|
185 | 215 |
}; //class RandomSelectionRule |
186 | 216 |
|
187 | 217 |
|
188 | 218 |
// Implementation of the DEGREE_BASED node selection rule. |
189 | 219 |
class DegreeBasedSelectionRule |
190 | 220 |
{ |
191 | 221 |
private: |
192 | 222 |
|
193 | 223 |
// References to the algorithm instance |
194 | 224 |
const BoolVector &_clique; |
195 | 225 |
const IntVector &_delta; |
196 | 226 |
const BoolVector &_tabu; |
197 | 227 |
Random &_rnd; |
198 | 228 |
|
199 | 229 |
// Pivot rule data |
200 | 230 |
int _n; |
201 | 231 |
IntVector _deg; |
202 | 232 |
|
203 | 233 |
public: |
204 | 234 |
|
205 | 235 |
// Constructor |
206 | 236 |
DegreeBasedSelectionRule(GrossoLocatelliPullanMc &mc) : |
207 | 237 |
_clique(mc._clique), _delta(mc._delta), _tabu(mc._tabu), |
208 | 238 |
_rnd(mc._rnd), _n(mc._n), _deg(_n) |
209 | 239 |
{ |
210 | 240 |
for (int i = 0; i != _n; i++) { |
211 | 241 |
int d = 0; |
212 | 242 |
BoolVector &row = mc._gr[i]; |
213 | 243 |
for (int j = 0; j != _n; j++) { |
214 | 244 |
if (row[j]) d++; |
215 | 245 |
} |
216 | 246 |
_deg[i] = d; |
217 | 247 |
} |
218 | 248 |
} |
219 | 249 |
|
220 | 250 |
// Return a node index for a feasible add move or -1 if no one exists |
221 | 251 |
int nextFeasibleAddNode() const { |
222 | 252 |
int start_node = _rnd[_n]; |
223 | 253 |
int node = -1, max_deg = -1; |
224 | 254 |
for (int i = start_node; i != _n; i++) { |
225 | 255 |
if (_delta[i] == 0 && !_tabu[i] && _deg[i] > max_deg) { |
226 | 256 |
node = i; |
227 | 257 |
max_deg = _deg[i]; |
228 | 258 |
} |
229 | 259 |
} |
230 | 260 |
for (int i = 0; i != start_node; i++) { |
231 | 261 |
if (_delta[i] == 0 && !_tabu[i] && _deg[i] > max_deg) { |
232 | 262 |
node = i; |
233 | 263 |
max_deg = _deg[i]; |
234 | 264 |
} |
235 | 265 |
} |
236 | 266 |
return node; |
237 | 267 |
} |
238 | 268 |
|
239 | 269 |
// Return a node index for a feasible swap move or -1 if no one exists |
240 | 270 |
int nextFeasibleSwapNode() const { |
241 | 271 |
int start_node = _rnd[_n]; |
242 | 272 |
int node = -1, max_deg = -1; |
243 | 273 |
for (int i = start_node; i != _n; i++) { |
244 | 274 |
if (!_clique[i] && _delta[i] == 1 && !_tabu[i] && |
245 | 275 |
_deg[i] > max_deg) { |
246 | 276 |
node = i; |
247 | 277 |
max_deg = _deg[i]; |
248 | 278 |
} |
249 | 279 |
} |
250 | 280 |
for (int i = 0; i != start_node; i++) { |
251 | 281 |
if (!_clique[i] && _delta[i] == 1 && !_tabu[i] && |
252 | 282 |
_deg[i] > max_deg) { |
253 | 283 |
node = i; |
254 | 284 |
max_deg = _deg[i]; |
255 | 285 |
} |
256 | 286 |
} |
257 | 287 |
return node; |
258 | 288 |
} |
259 | 289 |
|
260 | 290 |
// Return a node index for an add move or -1 if no one exists |
261 | 291 |
int nextAddNode() const { |
262 | 292 |
int start_node = _rnd[_n]; |
263 | 293 |
int node = -1, max_deg = -1; |
264 | 294 |
for (int i = start_node; i != _n; i++) { |
265 | 295 |
if (_delta[i] == 0 && _deg[i] > max_deg) { |
266 | 296 |
node = i; |
267 | 297 |
max_deg = _deg[i]; |
268 | 298 |
} |
269 | 299 |
} |
270 | 300 |
for (int i = 0; i != start_node; i++) { |
271 | 301 |
if (_delta[i] == 0 && _deg[i] > max_deg) { |
272 | 302 |
node = i; |
273 | 303 |
max_deg = _deg[i]; |
274 | 304 |
} |
275 | 305 |
} |
276 | 306 |
return node; |
277 | 307 |
} |
278 | 308 |
|
279 | 309 |
// Update internal data structures between stages (if necessary) |
280 | 310 |
void update() {} |
281 | 311 |
|
282 | 312 |
}; //class DegreeBasedSelectionRule |
283 | 313 |
|
284 | 314 |
|
285 | 315 |
// Implementation of the PENALTY_BASED node selection rule. |
286 | 316 |
class PenaltyBasedSelectionRule |
287 | 317 |
{ |
288 | 318 |
private: |
289 | 319 |
|
290 | 320 |
// References to the algorithm instance |
291 | 321 |
const BoolVector &_clique; |
292 | 322 |
const IntVector &_delta; |
293 | 323 |
const BoolVector &_tabu; |
294 | 324 |
Random &_rnd; |
295 | 325 |
|
296 | 326 |
// Pivot rule data |
297 | 327 |
int _n; |
298 | 328 |
IntVector _penalty; |
299 | 329 |
|
300 | 330 |
public: |
301 | 331 |
|
302 | 332 |
// Constructor |
303 | 333 |
PenaltyBasedSelectionRule(GrossoLocatelliPullanMc &mc) : |
304 | 334 |
_clique(mc._clique), _delta(mc._delta), _tabu(mc._tabu), |
305 | 335 |
_rnd(mc._rnd), _n(mc._n), _penalty(_n, 0) |
306 | 336 |
{} |
307 | 337 |
|
308 | 338 |
// Return a node index for a feasible add move or -1 if no one exists |
309 | 339 |
int nextFeasibleAddNode() const { |
310 | 340 |
int start_node = _rnd[_n]; |
311 | 341 |
int node = -1, min_p = std::numeric_limits<int>::max(); |
312 | 342 |
for (int i = start_node; i != _n; i++) { |
313 | 343 |
if (_delta[i] == 0 && !_tabu[i] && _penalty[i] < min_p) { |
314 | 344 |
node = i; |
315 | 345 |
min_p = _penalty[i]; |
316 | 346 |
} |
317 | 347 |
} |
318 | 348 |
for (int i = 0; i != start_node; i++) { |
319 | 349 |
if (_delta[i] == 0 && !_tabu[i] && _penalty[i] < min_p) { |
320 | 350 |
node = i; |
321 | 351 |
min_p = _penalty[i]; |
322 | 352 |
} |
323 | 353 |
} |
324 | 354 |
return node; |
325 | 355 |
} |
326 | 356 |
|
327 | 357 |
// Return a node index for a feasible swap move or -1 if no one exists |
328 | 358 |
int nextFeasibleSwapNode() const { |
329 | 359 |
int start_node = _rnd[_n]; |
330 | 360 |
int node = -1, min_p = std::numeric_limits<int>::max(); |
331 | 361 |
for (int i = start_node; i != _n; i++) { |
332 | 362 |
if (!_clique[i] && _delta[i] == 1 && !_tabu[i] && |
333 | 363 |
_penalty[i] < min_p) { |
334 | 364 |
node = i; |
335 | 365 |
min_p = _penalty[i]; |
336 | 366 |
} |
337 | 367 |
} |
338 | 368 |
for (int i = 0; i != start_node; i++) { |
339 | 369 |
if (!_clique[i] && _delta[i] == 1 && !_tabu[i] && |
340 | 370 |
_penalty[i] < min_p) { |
341 | 371 |
node = i; |
342 | 372 |
min_p = _penalty[i]; |
343 | 373 |
} |
344 | 374 |
} |
345 | 375 |
return node; |
346 | 376 |
} |
347 | 377 |
|
348 | 378 |
// Return a node index for an add move or -1 if no one exists |
349 | 379 |
int nextAddNode() const { |
350 | 380 |
int start_node = _rnd[_n]; |
351 | 381 |
int node = -1, min_p = std::numeric_limits<int>::max(); |
352 | 382 |
for (int i = start_node; i != _n; i++) { |
353 | 383 |
if (_delta[i] == 0 && _penalty[i] < min_p) { |
354 | 384 |
node = i; |
355 | 385 |
min_p = _penalty[i]; |
356 | 386 |
} |
357 | 387 |
} |
358 | 388 |
for (int i = 0; i != start_node; i++) { |
359 | 389 |
if (_delta[i] == 0 && _penalty[i] < min_p) { |
360 | 390 |
node = i; |
361 | 391 |
min_p = _penalty[i]; |
362 | 392 |
} |
363 | 393 |
} |
364 | 394 |
return node; |
365 | 395 |
} |
366 | 396 |
|
367 | 397 |
// Update internal data structures between stages (if necessary) |
368 | 398 |
void update() {} |
369 | 399 |
|
370 | 400 |
}; //class PenaltyBasedSelectionRule |
371 | 401 |
|
372 | 402 |
public: |
373 | 403 |
|
374 | 404 |
/// \brief Constructor. |
375 | 405 |
/// |
376 | 406 |
/// Constructor. |
377 | 407 |
/// The global \ref rnd "random number generator instance" is used |
378 | 408 |
/// during the algorithm. |
379 | 409 |
/// |
380 | 410 |
/// \param graph The undirected graph the algorithm runs on. |
381 | 411 |
GrossoLocatelliPullanMc(const GR& graph) : |
382 | 412 |
_graph(graph), _id(_graph), _rnd(rnd) |
383 |
{ |
|
413 |
{ |
|
414 |
initOptions(); |
|
415 |
} |
|
384 | 416 |
|
385 | 417 |
/// \brief Constructor with random seed. |
386 | 418 |
/// |
387 | 419 |
/// Constructor with random seed. |
388 | 420 |
/// |
389 | 421 |
/// \param graph The undirected graph the algorithm runs on. |
390 | 422 |
/// \param seed Seed value for the internal random number generator |
391 | 423 |
/// that is used during the algorithm. |
392 | 424 |
GrossoLocatelliPullanMc(const GR& graph, int seed) : |
393 | 425 |
_graph(graph), _id(_graph), _rnd(seed) |
394 |
{ |
|
426 |
{ |
|
427 |
initOptions(); |
|
428 |
} |
|
395 | 429 |
|
396 | 430 |
/// \brief Constructor with random number generator. |
397 | 431 |
/// |
398 | 432 |
/// Constructor with random number generator. |
399 | 433 |
/// |
400 | 434 |
/// \param graph The undirected graph the algorithm runs on. |
401 | 435 |
/// \param random A random number generator that is used during the |
402 | 436 |
/// algorithm. |
403 | 437 |
GrossoLocatelliPullanMc(const GR& graph, const Random& random) : |
404 | 438 |
_graph(graph), _id(_graph), _rnd(random) |
405 |
{ |
|
439 |
{ |
|
440 |
initOptions(); |
|
441 |
} |
|
406 | 442 |
|
407 | 443 |
/// \name Execution Control |
444 |
/// The \ref run() function can be used to execute the algorithm.\n |
|
445 |
/// The functions \ref iterationLimit(int), \ref stepLimit(int), and |
|
446 |
/// \ref sizeLimit(int) can be used to specify various limits for the |
|
447 |
/// search process. |
|
448 |
|
|
408 | 449 |
/// @{ |
409 | 450 |
|
451 |
/// \brief Sets the maximum number of iterations. |
|
452 |
/// |
|
453 |
/// This function sets the maximum number of iterations. |
|
454 |
/// Each iteration of the algorithm finds a maximal clique (but not |
|
455 |
/// necessarily the largest one) by performing several search steps |
|
456 |
/// (node selections). |
|
457 |
/// |
|
458 |
/// This limit controls the running time and the success of the |
|
459 |
/// algorithm. For larger values, the algorithm runs slower, but it more |
|
460 |
/// likely finds larger cliques. For smaller values, the algorithm is |
|
461 |
/// faster but probably gives worse results. |
|
462 |
/// |
|
463 |
/// The default value is \c 1000. |
|
464 |
/// \c -1 means that number of iterations is not limited. |
|
465 |
/// |
|
466 |
/// \warning You should specify a reasonable limit for the number of |
|
467 |
/// iterations and/or the number of search steps. |
|
468 |
/// |
|
469 |
/// \return <tt>(*this)</tt> |
|
470 |
/// |
|
471 |
/// \sa stepLimit(int) |
|
472 |
/// \sa sizeLimit(int) |
|
473 |
GrossoLocatelliPullanMc& iterationLimit(int limit) { |
|
474 |
_iteration_limit = limit; |
|
475 |
return *this; |
|
476 |
} |
|
477 |
|
|
478 |
/// \brief Sets the maximum number of search steps. |
|
479 |
/// |
|
480 |
/// This function sets the maximum number of elementary search steps. |
|
481 |
/// Each iteration of the algorithm finds a maximal clique (but not |
|
482 |
/// necessarily the largest one) by performing several search steps |
|
483 |
/// (node selections). |
|
484 |
/// |
|
485 |
/// This limit controls the running time and the success of the |
|
486 |
/// algorithm. For larger values, the algorithm runs slower, but it more |
|
487 |
/// likely finds larger cliques. For smaller values, the algorithm is |
|
488 |
/// faster but probably gives worse results. |
|
489 |
/// |
|
490 |
/// The default value is \c -1, which means that number of steps |
|
491 |
/// is not limited explicitly. However, the number of iterations is |
|
492 |
/// limited and each iteration performs a finite number of search steps. |
|
493 |
/// |
|
494 |
/// \warning You should specify a reasonable limit for the number of |
|
495 |
/// iterations and/or the number of search steps. |
|
496 |
/// |
|
497 |
/// \return <tt>(*this)</tt> |
|
498 |
/// |
|
499 |
/// \sa iterationLimit(int) |
|
500 |
/// \sa sizeLimit(int) |
|
501 |
GrossoLocatelliPullanMc& stepLimit(int limit) { |
|
502 |
_step_limit = limit; |
|
503 |
return *this; |
|
504 |
} |
|
505 |
|
|
506 |
/// \brief Sets the desired clique size. |
|
507 |
/// |
|
508 |
/// This function sets the desired clique size that serves as a search |
|
509 |
/// limit. If a clique of this size (or a larger one) is found, then the |
|
510 |
/// algorithm terminates. |
|
511 |
/// |
|
512 |
/// This function is especially useful if you know an exact upper bound |
|
513 |
/// for the size of the cliques in the graph or if any clique above |
|
514 |
/// a certain size limit is sufficient for your application. |
|
515 |
/// |
|
516 |
/// The default value is \c -1, which means that the size limit is set to |
|
517 |
/// the number of nodes in the graph. |
|
518 |
/// |
|
519 |
/// \return <tt>(*this)</tt> |
|
520 |
/// |
|
521 |
/// \sa iterationLimit(int) |
|
522 |
/// \sa stepLimit(int) |
|
523 |
GrossoLocatelliPullanMc& sizeLimit(int limit) { |
|
524 |
_size_limit = limit; |
|
525 |
return *this; |
|
526 |
} |
|
527 |
|
|
528 |
/// \brief The maximum number of iterations. |
|
529 |
/// |
|
530 |
/// This function gives back the maximum number of iterations. |
|
531 |
/// \c -1 means that no limit is specified. |
|
532 |
/// |
|
533 |
/// \sa iterationLimit(int) |
|
534 |
int iterationLimit() const { |
|
535 |
return _iteration_limit; |
|
536 |
} |
|
537 |
|
|
538 |
/// \brief The maximum number of search steps. |
|
539 |
/// |
|
540 |
/// This function gives back the maximum number of search steps. |
|
541 |
/// \c -1 means that no limit is specified. |
|
542 |
/// |
|
543 |
/// \sa stepLimit(int) |
|
544 |
int stepLimit() const { |
|
545 |
return _step_limit; |
|
546 |
} |
|
547 |
|
|
548 |
/// \brief The desired clique size. |
|
549 |
/// |
|
550 |
/// This function gives back the desired clique size that serves as a |
|
551 |
/// search limit. \c -1 means that this limit is set to the number of |
|
552 |
/// nodes in the graph. |
|
553 |
/// |
|
554 |
/// \sa sizeLimit(int) |
|
555 |
int sizeLimit() const { |
|
556 |
return _size_limit; |
|
557 |
} |
|
558 |
|
|
410 | 559 |
/// \brief Runs the algorithm. |
411 | 560 |
/// |
412 |
/// This function runs the algorithm. |
|
561 |
/// This function runs the algorithm. If one of the specified limits |
|
562 |
/// is reached, the search process terminates. |
|
413 | 563 |
/// |
414 |
/// \param step_num The maximum number of node selections (steps) |
|
415 |
/// during the search process. |
|
416 |
/// This parameter controls the running time and the success of the |
|
417 |
/// algorithm. For larger values, the algorithm runs slower but it more |
|
418 |
/// likely finds larger cliques. For smaller values, the algorithm is |
|
419 |
/// faster but probably gives worse results. |
|
420 | 564 |
/// \param rule The node selection rule. For more information, see |
421 | 565 |
/// \ref SelectionRule. |
422 | 566 |
/// |
423 |
/// \return The size of the found clique. |
|
424 |
int run(int step_num = 100000, |
|
425 |
|
|
567 |
/// \return The termination cause of the search. For more information, |
|
568 |
/// see \ref TerminationCause. |
|
569 |
TerminationCause run(SelectionRule rule = PENALTY_BASED) |
|
426 | 570 |
{ |
427 | 571 |
init(); |
428 | 572 |
switch (rule) { |
429 | 573 |
case RANDOM: |
430 |
return start<RandomSelectionRule>( |
|
574 |
return start<RandomSelectionRule>(); |
|
431 | 575 |
case DEGREE_BASED: |
432 |
return start<DegreeBasedSelectionRule>(step_num); |
|
433 |
case PENALTY_BASED: |
|
434 |
return start< |
|
576 |
return start<DegreeBasedSelectionRule>(); |
|
577 |
default: |
|
578 |
return start<PenaltyBasedSelectionRule>(); |
|
435 | 579 |
} |
436 |
return 0; // avoid warning |
|
437 | 580 |
} |
438 | 581 |
|
439 | 582 |
/// @} |
440 | 583 |
|
441 | 584 |
/// \name Query Functions |
585 |
/// The results of the algorithm can be obtained using these functions.\n |
|
586 |
/// The run() function must be called before using them. |
|
587 |
|
|
442 | 588 |
/// @{ |
443 | 589 |
|
444 | 590 |
/// \brief The size of the found clique |
445 | 591 |
/// |
446 | 592 |
/// This function returns the size of the found clique. |
447 | 593 |
/// |
448 | 594 |
/// \pre run() must be called before using this function. |
449 | 595 |
int cliqueSize() const { |
450 | 596 |
return _best_size; |
451 | 597 |
} |
452 | 598 |
|
453 | 599 |
/// \brief Gives back the found clique in a \c bool node map |
454 | 600 |
/// |
455 | 601 |
/// This function gives back the characteristic vector of the found |
456 | 602 |
/// clique in the given node map. |
457 | 603 |
/// It must be a \ref concepts::WriteMap "writable" node map with |
458 | 604 |
/// \c bool (or convertible) value type. |
459 | 605 |
/// |
460 | 606 |
/// \pre run() must be called before using this function. |
461 | 607 |
template <typename CliqueMap> |
462 | 608 |
void cliqueMap(CliqueMap &map) const { |
463 | 609 |
for (NodeIt n(_graph); n != INVALID; ++n) { |
464 | 610 |
map[n] = static_cast<bool>(_best_clique[_id[n]]); |
465 | 611 |
} |
466 | 612 |
} |
467 | 613 |
|
468 | 614 |
/// \brief Iterator to list the nodes of the found clique |
469 | 615 |
/// |
470 | 616 |
/// This iterator class lists the nodes of the found clique. |
471 | 617 |
/// Before using it, you must allocate a GrossoLocatelliPullanMc instance |
472 | 618 |
/// and call its \ref GrossoLocatelliPullanMc::run() "run()" method. |
473 | 619 |
/// |
474 | 620 |
/// The following example prints out the IDs of the nodes in the found |
475 | 621 |
/// clique. |
476 | 622 |
/// \code |
477 | 623 |
/// GrossoLocatelliPullanMc<Graph> mc(g); |
478 | 624 |
/// mc.run(); |
479 | 625 |
/// for (GrossoLocatelliPullanMc<Graph>::CliqueNodeIt n(mc); |
480 | 626 |
/// n != INVALID; ++n) |
481 | 627 |
/// { |
482 | 628 |
/// std::cout << g.id(n) << std::endl; |
483 | 629 |
/// } |
484 | 630 |
/// \endcode |
485 | 631 |
class CliqueNodeIt |
486 | 632 |
{ |
487 | 633 |
private: |
488 | 634 |
NodeIt _it; |
489 | 635 |
BoolNodeMap _map; |
490 | 636 |
|
491 | 637 |
public: |
492 | 638 |
|
493 | 639 |
/// Constructor |
494 | 640 |
|
495 | 641 |
/// Constructor. |
496 | 642 |
/// \param mc The algorithm instance. |
497 | 643 |
CliqueNodeIt(const GrossoLocatelliPullanMc &mc) |
498 | 644 |
: _map(mc._graph) |
499 | 645 |
{ |
500 | 646 |
mc.cliqueMap(_map); |
501 | 647 |
for (_it = NodeIt(mc._graph); _it != INVALID && !_map[_it]; ++_it) ; |
502 | 648 |
} |
503 | 649 |
|
504 | 650 |
/// Conversion to \c Node |
505 | 651 |
operator Node() const { return _it; } |
506 | 652 |
|
507 | 653 |
bool operator==(Invalid) const { return _it == INVALID; } |
508 | 654 |
bool operator!=(Invalid) const { return _it != INVALID; } |
509 | 655 |
|
510 | 656 |
/// Next node |
511 | 657 |
CliqueNodeIt &operator++() { |
512 | 658 |
for (++_it; _it != INVALID && !_map[_it]; ++_it) ; |
513 | 659 |
return *this; |
514 | 660 |
} |
515 | 661 |
|
516 | 662 |
/// Postfix incrementation |
517 | 663 |
|
518 | 664 |
/// Postfix incrementation. |
519 | 665 |
/// |
520 | 666 |
/// \warning This incrementation returns a \c Node, not a |
521 | 667 |
/// \c CliqueNodeIt as one may expect. |
522 | 668 |
typename GR::Node operator++(int) { |
523 | 669 |
Node n=*this; |
524 | 670 |
++(*this); |
525 | 671 |
return n; |
526 | 672 |
} |
527 | 673 |
|
528 | 674 |
}; |
529 | 675 |
|
530 | 676 |
/// @} |
531 | 677 |
|
532 | 678 |
private: |
533 | 679 |
|
680 |
// Initialize search options and limits |
|
681 |
void initOptions() { |
|
682 |
// Search options |
|
683 |
_delta_based_restart = true; |
|
684 |
_restart_delta_limit = 4; |
|
685 |
|
|
686 |
// Search limits |
|
687 |
_iteration_limit = 1000; |
|
688 |
_step_limit = -1; // this is disabled by default |
|
689 |
_size_limit = -1; // this is disabled by default |
|
690 |
} |
|
691 |
|
|
534 | 692 |
// Adds a node to the current clique |
535 | 693 |
void addCliqueNode(int u) { |
536 | 694 |
if (_clique[u]) return; |
537 | 695 |
_clique[u] = true; |
538 | 696 |
_size++; |
539 | 697 |
BoolVector &row = _gr[u]; |
540 | 698 |
for (int i = 0; i != _n; i++) { |
541 | 699 |
if (!row[i]) _delta[i]++; |
542 | 700 |
} |
543 | 701 |
} |
544 | 702 |
|
545 | 703 |
// Removes a node from the current clique |
546 | 704 |
void delCliqueNode(int u) { |
547 | 705 |
if (!_clique[u]) return; |
548 | 706 |
_clique[u] = false; |
549 | 707 |
_size--; |
550 | 708 |
BoolVector &row = _gr[u]; |
551 | 709 |
for (int i = 0; i != _n; i++) { |
552 | 710 |
if (!row[i]) _delta[i]--; |
553 | 711 |
} |
554 | 712 |
} |
555 | 713 |
|
556 | 714 |
// Initialize data structures |
557 | 715 |
void init() { |
558 | 716 |
_n = countNodes(_graph); |
559 | 717 |
int ui = 0; |
560 | 718 |
for (NodeIt u(_graph); u != INVALID; ++u) { |
561 | 719 |
_id[u] = ui++; |
562 | 720 |
} |
563 | 721 |
_gr.clear(); |
564 | 722 |
_gr.resize(_n, BoolVector(_n, false)); |
565 | 723 |
ui = 0; |
566 | 724 |
for (NodeIt u(_graph); u != INVALID; ++u) { |
567 | 725 |
for (IncEdgeIt e(_graph, u); e != INVALID; ++e) { |
568 | 726 |
int vi = _id[_graph.runningNode(e)]; |
569 | 727 |
_gr[ui][vi] = true; |
570 | 728 |
_gr[vi][ui] = true; |
571 | 729 |
} |
572 | 730 |
++ui; |
573 | 731 |
} |
574 | 732 |
|
575 | 733 |
_clique.clear(); |
576 | 734 |
_clique.resize(_n, false); |
577 | 735 |
_size = 0; |
578 | 736 |
_best_clique.clear(); |
579 | 737 |
_best_clique.resize(_n, false); |
580 | 738 |
_best_size = 0; |
581 | 739 |
_delta.clear(); |
582 | 740 |
_delta.resize(_n, 0); |
583 | 741 |
_tabu.clear(); |
584 | 742 |
_tabu.resize(_n, false); |
585 | 743 |
} |
586 | 744 |
|
587 | 745 |
// Executes the algorithm |
588 | 746 |
template <typename SelectionRuleImpl> |
589 |
int start(int max_select) { |
|
590 |
// Options for the restart rule |
|
591 |
const bool delta_based_restart = true; |
|
592 |
const int restart_delta_limit = 4; |
|
593 |
|
|
594 |
if (_n == 0) return 0; |
|
747 |
TerminationCause start() { |
|
748 |
if (_n == 0) return SIZE_LIMIT; |
|
595 | 749 |
if (_n == 1) { |
596 | 750 |
_best_clique[0] = true; |
597 | 751 |
_best_size = 1; |
598 |
return |
|
752 |
return SIZE_LIMIT; |
|
599 | 753 |
} |
600 | 754 |
|
601 |
// Iterated local search |
|
755 |
// Iterated local search algorithm |
|
756 |
const int max_size = _size_limit >= 0 ? _size_limit : _n; |
|
757 |
const int max_restart = _iteration_limit >= 0 ? |
|
758 |
_iteration_limit : std::numeric_limits<int>::max(); |
|
759 |
const int max_select = _step_limit >= 0 ? |
|
760 |
_step_limit : std::numeric_limits<int>::max(); |
|
761 |
|
|
602 | 762 |
SelectionRuleImpl sel_method(*this); |
603 |
int select = 0; |
|
763 |
int select = 0, restart = 0; |
|
604 | 764 |
IntVector restart_nodes; |
605 |
|
|
606 |
while (select < max_select) { |
|
765 |
while (select < max_select && restart < max_restart) { |
|
607 | 766 |
|
608 | 767 |
// Perturbation/restart |
609 |
|
|
768 |
restart++; |
|
769 |
if (_delta_based_restart) { |
|
610 | 770 |
restart_nodes.clear(); |
611 | 771 |
for (int i = 0; i != _n; i++) { |
612 |
if (_delta[i] >= |
|
772 |
if (_delta[i] >= _restart_delta_limit) |
|
613 | 773 |
restart_nodes.push_back(i); |
614 | 774 |
} |
615 | 775 |
} |
616 | 776 |
int rs_node = -1; |
617 | 777 |
if (restart_nodes.size() > 0) { |
618 | 778 |
rs_node = restart_nodes[_rnd[restart_nodes.size()]]; |
619 | 779 |
} else { |
620 | 780 |
rs_node = _rnd[_n]; |
621 | 781 |
} |
622 | 782 |
BoolVector &row = _gr[rs_node]; |
623 | 783 |
for (int i = 0; i != _n; i++) { |
624 | 784 |
if (_clique[i] && !row[i]) delCliqueNode(i); |
625 | 785 |
} |
626 | 786 |
addCliqueNode(rs_node); |
627 | 787 |
|
628 | 788 |
// Local search |
629 | 789 |
_tabu.clear(); |
630 | 790 |
_tabu.resize(_n, false); |
631 | 791 |
bool tabu_empty = true; |
632 | 792 |
int max_swap = _size; |
633 | 793 |
while (select < max_select) { |
634 | 794 |
select++; |
635 | 795 |
int u; |
636 | 796 |
if ((u = sel_method.nextFeasibleAddNode()) != -1) { |
637 | 797 |
// Feasible add move |
638 | 798 |
addCliqueNode(u); |
639 | 799 |
if (tabu_empty) max_swap = _size; |
640 | 800 |
} |
641 | 801 |
else if ((u = sel_method.nextFeasibleSwapNode()) != -1) { |
642 | 802 |
// Feasible swap move |
643 | 803 |
int v = -1; |
644 | 804 |
BoolVector &row = _gr[u]; |
645 | 805 |
for (int i = 0; i != _n; i++) { |
646 | 806 |
if (_clique[i] && !row[i]) { |
647 | 807 |
v = i; |
648 | 808 |
break; |
649 | 809 |
} |
650 | 810 |
} |
651 | 811 |
addCliqueNode(u); |
652 | 812 |
delCliqueNode(v); |
653 | 813 |
_tabu[v] = true; |
654 | 814 |
tabu_empty = false; |
655 | 815 |
if (--max_swap <= 0) break; |
656 | 816 |
} |
657 | 817 |
else if ((u = sel_method.nextAddNode()) != -1) { |
658 | 818 |
// Non-feasible add move |
659 | 819 |
addCliqueNode(u); |
660 | 820 |
} |
661 | 821 |
else break; |
662 | 822 |
} |
663 | 823 |
if (_size > _best_size) { |
664 | 824 |
_best_clique = _clique; |
665 | 825 |
_best_size = _size; |
666 |
if (_best_size |
|
826 |
if (_best_size >= max_size) return SIZE_LIMIT; |
|
667 | 827 |
} |
668 | 828 |
sel_method.update(); |
669 | 829 |
} |
670 | 830 |
|
671 |
return |
|
831 |
return (restart >= max_restart ? ITERATION_LIMIT : STEP_LIMIT); |
|
672 | 832 |
} |
673 | 833 |
|
674 | 834 |
}; //class GrossoLocatelliPullanMc |
675 | 835 |
|
676 | 836 |
///@} |
677 | 837 |
|
678 | 838 |
} //namespace lemon |
679 | 839 |
|
680 | 840 |
#endif //LEMON_GROSSO_LOCATELLI_PULLAN_MC_H |
Changeset was too big and was cut off... Show full diff
0 comments (0 inline)