0
15
0
2
7
2
7
1
11
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-2008 |
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_BFS_H |
20 | 20 |
#define LEMON_BFS_H |
21 | 21 |
|
22 | 22 |
///\ingroup search |
23 | 23 |
///\file |
24 | 24 |
///\brief BFS algorithm. |
25 | 25 |
|
26 | 26 |
#include <lemon/list_graph.h> |
27 | 27 |
#include <lemon/bits/path_dump.h> |
28 | 28 |
#include <lemon/core.h> |
29 | 29 |
#include <lemon/error.h> |
30 | 30 |
#include <lemon/maps.h> |
31 | 31 |
#include <lemon/path.h> |
32 | 32 |
|
33 | 33 |
namespace lemon { |
34 | 34 |
|
35 | 35 |
///Default traits class of Bfs class. |
36 | 36 |
|
37 | 37 |
///Default traits class of Bfs class. |
38 | 38 |
///\tparam GR Digraph type. |
39 | 39 |
template<class GR> |
40 | 40 |
struct BfsDefaultTraits |
41 | 41 |
{ |
42 | 42 |
///The type of the digraph the algorithm runs on. |
43 | 43 |
typedef GR Digraph; |
44 | 44 |
|
45 | 45 |
///\brief The type of the map that stores the predecessor |
46 | 46 |
///arcs of the shortest paths. |
47 | 47 |
/// |
48 | 48 |
///The type of the map that stores the predecessor |
49 | 49 |
///arcs of the shortest paths. |
50 | 50 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
51 | 51 |
typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap; |
52 | 52 |
///Instantiates a \ref PredMap. |
53 | 53 |
|
54 | 54 |
///This function instantiates a \ref PredMap. |
55 | 55 |
///\param g is the digraph, to which we would like to define the |
56 | 56 |
///\ref PredMap. |
57 |
///\todo The digraph alone may be insufficient to initialize |
|
58 | 57 |
static PredMap *createPredMap(const Digraph &g) |
59 | 58 |
{ |
60 | 59 |
return new PredMap(g); |
61 | 60 |
} |
62 | 61 |
|
63 | 62 |
///The type of the map that indicates which nodes are processed. |
64 | 63 |
|
65 | 64 |
///The type of the map that indicates which nodes are processed. |
66 | 65 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
67 |
///By default it is a NullMap. |
|
68 | 66 |
typedef NullMap<typename Digraph::Node,bool> ProcessedMap; |
69 | 67 |
///Instantiates a \ref ProcessedMap. |
70 | 68 |
|
71 | 69 |
///This function instantiates a \ref ProcessedMap. |
72 | 70 |
///\param g is the digraph, to which |
73 | 71 |
///we would like to define the \ref ProcessedMap |
74 | 72 |
#ifdef DOXYGEN |
75 | 73 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
76 | 74 |
#else |
77 | 75 |
static ProcessedMap *createProcessedMap(const Digraph &) |
78 | 76 |
#endif |
79 | 77 |
{ |
80 | 78 |
return new ProcessedMap(); |
81 | 79 |
} |
82 | 80 |
|
83 | 81 |
///The type of the map that indicates which nodes are reached. |
84 | 82 |
|
85 | 83 |
///The type of the map that indicates which nodes are reached. |
86 | 84 |
///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept. |
87 | 85 |
typedef typename Digraph::template NodeMap<bool> ReachedMap; |
88 | 86 |
///Instantiates a \ref ReachedMap. |
89 | 87 |
|
90 | 88 |
///This function instantiates a \ref ReachedMap. |
91 | 89 |
///\param g is the digraph, to which |
92 | 90 |
///we would like to define the \ref ReachedMap. |
93 | 91 |
static ReachedMap *createReachedMap(const Digraph &g) |
94 | 92 |
{ |
95 | 93 |
return new ReachedMap(g); |
96 | 94 |
} |
97 | 95 |
|
98 | 96 |
///The type of the map that stores the distances of the nodes. |
99 | 97 |
|
100 | 98 |
///The type of the map that stores the distances of the nodes. |
101 | 99 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
102 | 100 |
typedef typename Digraph::template NodeMap<int> DistMap; |
103 | 101 |
///Instantiates a \ref DistMap. |
104 | 102 |
|
105 | 103 |
///This function instantiates a \ref DistMap. |
106 | 104 |
///\param g is the digraph, to which we would like to define the |
107 | 105 |
///\ref DistMap. |
108 | 106 |
static DistMap *createDistMap(const Digraph &g) |
109 | 107 |
{ |
110 | 108 |
return new DistMap(g); |
111 | 109 |
} |
112 | 110 |
}; |
113 | 111 |
|
114 | 112 |
///%BFS algorithm class. |
115 | 113 |
|
116 | 114 |
///\ingroup search |
117 | 115 |
///This class provides an efficient implementation of the %BFS algorithm. |
118 | 116 |
/// |
119 | 117 |
///There is also a \ref bfs() "function-type interface" for the BFS |
120 | 118 |
///algorithm, which is convenient in the simplier cases and it can be |
121 | 119 |
///used easier. |
122 | 120 |
/// |
123 | 121 |
///\tparam GR The type of the digraph the algorithm runs on. |
124 | 122 |
///The default value is \ref ListDigraph. The value of GR is not used |
125 | 123 |
///directly by \ref Bfs, it is only passed to \ref BfsDefaultTraits. |
126 | 124 |
///\tparam TR Traits class to set various data types used by the algorithm. |
127 | 125 |
///The default traits class is |
128 | 126 |
///\ref BfsDefaultTraits "BfsDefaultTraits<GR>". |
129 | 127 |
///See \ref BfsDefaultTraits for the documentation of |
130 | 128 |
///a Bfs traits class. |
131 | 129 |
#ifdef DOXYGEN |
132 | 130 |
template <typename GR, |
133 | 131 |
typename TR> |
134 | 132 |
#else |
135 | 133 |
template <typename GR=ListDigraph, |
136 | 134 |
typename TR=BfsDefaultTraits<GR> > |
137 | 135 |
#endif |
138 | 136 |
class Bfs { |
139 | 137 |
public: |
140 | 138 |
///\ref Exception for uninitialized parameters. |
141 | 139 |
|
142 | 140 |
///This error represents problems in the initialization of the |
143 | 141 |
///parameters of the algorithm. |
144 | 142 |
class UninitializedParameter : public lemon::UninitializedParameter { |
145 | 143 |
public: |
146 | 144 |
virtual const char* what() const throw() { |
147 | 145 |
return "lemon::Bfs::UninitializedParameter"; |
148 | 146 |
} |
149 | 147 |
}; |
150 | 148 |
|
151 | 149 |
///The type of the digraph the algorithm runs on. |
152 | 150 |
typedef typename TR::Digraph Digraph; |
153 | 151 |
|
154 | 152 |
///\brief The type of the map that stores the predecessor arcs of the |
155 | 153 |
///shortest paths. |
156 | 154 |
typedef typename TR::PredMap PredMap; |
157 | 155 |
///The type of the map that stores the distances of the nodes. |
158 | 156 |
typedef typename TR::DistMap DistMap; |
159 | 157 |
///The type of the map that indicates which nodes are reached. |
160 | 158 |
typedef typename TR::ReachedMap ReachedMap; |
161 | 159 |
///The type of the map that indicates which nodes are processed. |
162 | 160 |
typedef typename TR::ProcessedMap ProcessedMap; |
163 | 161 |
///The type of the paths. |
164 | 162 |
typedef PredMapPath<Digraph, PredMap> Path; |
165 | 163 |
|
166 | 164 |
///The traits class. |
167 | 165 |
typedef TR Traits; |
168 | 166 |
|
169 | 167 |
private: |
170 | 168 |
|
171 | 169 |
typedef typename Digraph::Node Node; |
172 | 170 |
typedef typename Digraph::NodeIt NodeIt; |
173 | 171 |
typedef typename Digraph::Arc Arc; |
174 | 172 |
typedef typename Digraph::OutArcIt OutArcIt; |
175 | 173 |
|
176 | 174 |
//Pointer to the underlying digraph. |
177 | 175 |
const Digraph *G; |
178 | 176 |
//Pointer to the map of predecessor arcs. |
179 | 177 |
PredMap *_pred; |
180 | 178 |
//Indicates if _pred is locally allocated (true) or not. |
181 | 179 |
bool local_pred; |
182 | 180 |
//Pointer to the map of distances. |
183 | 181 |
DistMap *_dist; |
184 | 182 |
//Indicates if _dist is locally allocated (true) or not. |
185 | 183 |
bool local_dist; |
186 | 184 |
//Pointer to the map of reached status of the nodes. |
187 | 185 |
ReachedMap *_reached; |
188 | 186 |
//Indicates if _reached is locally allocated (true) or not. |
189 | 187 |
bool local_reached; |
190 | 188 |
//Pointer to the map of processed status of the nodes. |
191 | 189 |
ProcessedMap *_processed; |
192 | 190 |
//Indicates if _processed is locally allocated (true) or not. |
193 | 191 |
bool local_processed; |
194 | 192 |
|
195 | 193 |
std::vector<typename Digraph::Node> _queue; |
196 | 194 |
int _queue_head,_queue_tail,_queue_next_dist; |
197 | 195 |
int _curr_dist; |
198 | 196 |
|
199 |
///Creates the maps if necessary. |
|
200 |
///\todo Better memory allocation (instead of new). |
|
197 |
//Creates the maps if necessary. |
|
201 | 198 |
void create_maps() |
202 | 199 |
{ |
203 | 200 |
if(!_pred) { |
204 | 201 |
local_pred = true; |
205 | 202 |
_pred = Traits::createPredMap(*G); |
206 | 203 |
} |
207 | 204 |
if(!_dist) { |
208 | 205 |
local_dist = true; |
209 | 206 |
_dist = Traits::createDistMap(*G); |
210 | 207 |
} |
211 | 208 |
if(!_reached) { |
212 | 209 |
local_reached = true; |
213 | 210 |
_reached = Traits::createReachedMap(*G); |
214 | 211 |
} |
215 | 212 |
if(!_processed) { |
216 | 213 |
local_processed = true; |
217 | 214 |
_processed = Traits::createProcessedMap(*G); |
218 | 215 |
} |
219 | 216 |
} |
220 | 217 |
|
221 | 218 |
protected: |
222 | 219 |
|
223 | 220 |
Bfs() {} |
224 | 221 |
|
225 | 222 |
public: |
226 | 223 |
|
227 | 224 |
typedef Bfs Create; |
228 | 225 |
|
229 | 226 |
///\name Named template parameters |
230 | 227 |
|
231 | 228 |
///@{ |
232 | 229 |
|
233 | 230 |
template <class T> |
234 | 231 |
struct SetPredMapTraits : public Traits { |
235 | 232 |
typedef T PredMap; |
236 | 233 |
static PredMap *createPredMap(const Digraph &) |
237 | 234 |
{ |
238 | 235 |
throw UninitializedParameter(); |
239 | 236 |
} |
240 | 237 |
}; |
241 | 238 |
///\brief \ref named-templ-param "Named parameter" for setting |
242 | 239 |
///\ref PredMap type. |
243 | 240 |
/// |
244 | 241 |
///\ref named-templ-param "Named parameter" for setting |
245 | 242 |
///\ref PredMap type. |
246 | 243 |
template <class T> |
247 | 244 |
struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > { |
248 | 245 |
typedef Bfs< Digraph, SetPredMapTraits<T> > Create; |
249 | 246 |
}; |
250 | 247 |
|
251 | 248 |
template <class T> |
252 | 249 |
struct SetDistMapTraits : public Traits { |
253 | 250 |
typedef T DistMap; |
254 | 251 |
static DistMap *createDistMap(const Digraph &) |
255 | 252 |
{ |
256 | 253 |
throw UninitializedParameter(); |
257 | 254 |
} |
258 | 255 |
}; |
259 | 256 |
///\brief \ref named-templ-param "Named parameter" for setting |
260 | 257 |
///\ref DistMap type. |
261 | 258 |
/// |
262 | 259 |
///\ref named-templ-param "Named parameter" for setting |
263 | 260 |
///\ref DistMap type. |
264 | 261 |
template <class T> |
265 | 262 |
struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > { |
266 | 263 |
typedef Bfs< Digraph, SetDistMapTraits<T> > Create; |
267 | 264 |
}; |
268 | 265 |
|
269 | 266 |
template <class T> |
270 | 267 |
struct SetReachedMapTraits : public Traits { |
271 | 268 |
typedef T ReachedMap; |
272 | 269 |
static ReachedMap *createReachedMap(const Digraph &) |
273 | 270 |
{ |
274 | 271 |
throw UninitializedParameter(); |
275 | 272 |
} |
276 | 273 |
}; |
277 | 274 |
///\brief \ref named-templ-param "Named parameter" for setting |
278 | 275 |
///\ref ReachedMap type. |
279 | 276 |
/// |
280 | 277 |
///\ref named-templ-param "Named parameter" for setting |
281 | 278 |
///\ref ReachedMap type. |
282 | 279 |
template <class T> |
283 | 280 |
struct SetReachedMap : public Bfs< Digraph, SetReachedMapTraits<T> > { |
284 | 281 |
typedef Bfs< Digraph, SetReachedMapTraits<T> > Create; |
285 | 282 |
}; |
286 | 283 |
|
287 | 284 |
template <class T> |
288 | 285 |
struct SetProcessedMapTraits : public Traits { |
289 | 286 |
typedef T ProcessedMap; |
290 | 287 |
static ProcessedMap *createProcessedMap(const Digraph &) |
291 | 288 |
{ |
292 | 289 |
throw UninitializedParameter(); |
293 | 290 |
} |
294 | 291 |
}; |
295 | 292 |
///\brief \ref named-templ-param "Named parameter" for setting |
296 | 293 |
///\ref ProcessedMap type. |
297 | 294 |
/// |
298 | 295 |
///\ref named-templ-param "Named parameter" for setting |
299 | 296 |
///\ref ProcessedMap type. |
300 | 297 |
template <class T> |
301 | 298 |
struct SetProcessedMap : public Bfs< Digraph, SetProcessedMapTraits<T> > { |
302 | 299 |
typedef Bfs< Digraph, SetProcessedMapTraits<T> > Create; |
303 | 300 |
}; |
304 | 301 |
|
305 | 302 |
struct SetStandardProcessedMapTraits : public Traits { |
306 | 303 |
typedef typename Digraph::template NodeMap<bool> ProcessedMap; |
307 | 304 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
308 | 305 |
{ |
309 | 306 |
return new ProcessedMap(g); |
310 | 307 |
} |
311 | 308 |
}; |
312 | 309 |
///\brief \ref named-templ-param "Named parameter" for setting |
313 | 310 |
///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>. |
314 | 311 |
/// |
315 | 312 |
///\ref named-templ-param "Named parameter" for setting |
316 | 313 |
///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>. |
317 | 314 |
///If you don't set it explicitly, it will be automatically allocated. |
318 | 315 |
struct SetStandardProcessedMap : |
319 | 316 |
public Bfs< Digraph, SetStandardProcessedMapTraits > { |
320 | 317 |
typedef Bfs< Digraph, SetStandardProcessedMapTraits > Create; |
321 | 318 |
}; |
322 | 319 |
|
323 | 320 |
///@} |
324 | 321 |
|
325 | 322 |
public: |
326 | 323 |
|
327 | 324 |
///Constructor. |
328 | 325 |
|
329 | 326 |
///Constructor. |
330 | 327 |
///\param g The digraph the algorithm runs on. |
331 | 328 |
Bfs(const Digraph &g) : |
332 | 329 |
G(&g), |
333 | 330 |
_pred(NULL), local_pred(false), |
334 | 331 |
_dist(NULL), local_dist(false), |
335 | 332 |
_reached(NULL), local_reached(false), |
336 | 333 |
_processed(NULL), local_processed(false) |
337 | 334 |
{ } |
338 | 335 |
|
339 | 336 |
///Destructor. |
340 | 337 |
~Bfs() |
341 | 338 |
{ |
342 | 339 |
if(local_pred) delete _pred; |
343 | 340 |
if(local_dist) delete _dist; |
344 | 341 |
if(local_reached) delete _reached; |
345 | 342 |
if(local_processed) delete _processed; |
346 | 343 |
} |
347 | 344 |
|
348 | 345 |
///Sets the map that stores the predecessor arcs. |
349 | 346 |
|
350 | 347 |
///Sets the map that stores the predecessor arcs. |
351 | 348 |
///If you don't use this function before calling \ref run(), |
352 | 349 |
///it will allocate one. The destructor deallocates this |
353 | 350 |
///automatically allocated map, of course. |
354 | 351 |
///\return <tt> (*this) </tt> |
355 | 352 |
Bfs &predMap(PredMap &m) |
356 | 353 |
{ |
357 | 354 |
if(local_pred) { |
358 | 355 |
delete _pred; |
359 | 356 |
local_pred=false; |
360 | 357 |
} |
361 | 358 |
_pred = &m; |
362 | 359 |
return *this; |
363 | 360 |
} |
364 | 361 |
|
365 | 362 |
///Sets the map that indicates which nodes are reached. |
366 | 363 |
|
367 | 364 |
///Sets the map that indicates which nodes are reached. |
368 | 365 |
///If you don't use this function before calling \ref run(), |
369 | 366 |
///it will allocate one. The destructor deallocates this |
370 | 367 |
///automatically allocated map, of course. |
371 | 368 |
///\return <tt> (*this) </tt> |
372 | 369 |
Bfs &reachedMap(ReachedMap &m) |
373 | 370 |
{ |
374 | 371 |
if(local_reached) { |
375 | 372 |
delete _reached; |
376 | 373 |
local_reached=false; |
377 | 374 |
} |
378 | 375 |
_reached = &m; |
379 | 376 |
return *this; |
380 | 377 |
} |
381 | 378 |
|
382 | 379 |
///Sets the map that indicates which nodes are processed. |
383 | 380 |
|
384 | 381 |
///Sets the map that indicates which nodes are processed. |
385 | 382 |
///If you don't use this function before calling \ref run(), |
386 | 383 |
///it will allocate one. The destructor deallocates this |
387 | 384 |
///automatically allocated map, of course. |
388 | 385 |
///\return <tt> (*this) </tt> |
389 | 386 |
Bfs &processedMap(ProcessedMap &m) |
390 | 387 |
{ |
391 | 388 |
if(local_processed) { |
392 | 389 |
delete _processed; |
393 | 390 |
local_processed=false; |
394 | 391 |
} |
395 | 392 |
_processed = &m; |
396 | 393 |
return *this; |
397 | 394 |
} |
398 | 395 |
|
399 | 396 |
///Sets the map that stores the distances of the nodes. |
400 | 397 |
|
401 | 398 |
///Sets the map that stores the distances of the nodes calculated by |
402 | 399 |
///the algorithm. |
403 | 400 |
///If you don't use this function before calling \ref run(), |
404 | 401 |
///it will allocate one. The destructor deallocates this |
405 | 402 |
///automatically allocated map, of course. |
406 | 403 |
///\return <tt> (*this) </tt> |
407 | 404 |
Bfs &distMap(DistMap &m) |
408 | 405 |
{ |
409 | 406 |
if(local_dist) { |
410 | 407 |
delete _dist; |
411 | 408 |
local_dist=false; |
412 | 409 |
} |
413 | 410 |
_dist = &m; |
414 | 411 |
return *this; |
415 | 412 |
} |
416 | 413 |
|
417 | 414 |
public: |
418 | 415 |
|
419 | 416 |
///\name Execution control |
420 | 417 |
///The simplest way to execute the algorithm is to use |
421 | 418 |
///one of the member functions called \ref lemon::Bfs::run() "run()". |
422 | 419 |
///\n |
423 | 420 |
///If you need more control on the execution, first you must call |
424 | 421 |
///\ref lemon::Bfs::init() "init()", then you can add several source |
425 | 422 |
///nodes with \ref lemon::Bfs::addSource() "addSource()". |
426 | 423 |
///Finally \ref lemon::Bfs::start() "start()" will perform the |
427 | 424 |
///actual path computation. |
428 | 425 |
|
429 | 426 |
///@{ |
430 | 427 |
|
431 | 428 |
///Initializes the internal data structures. |
432 | 429 |
|
433 | 430 |
///Initializes the internal data structures. |
434 | 431 |
/// |
435 | 432 |
void init() |
436 | 433 |
{ |
437 | 434 |
create_maps(); |
438 | 435 |
_queue.resize(countNodes(*G)); |
439 | 436 |
_queue_head=_queue_tail=0; |
440 | 437 |
_curr_dist=1; |
441 | 438 |
for ( NodeIt u(*G) ; u!=INVALID ; ++u ) { |
442 | 439 |
_pred->set(u,INVALID); |
443 | 440 |
_reached->set(u,false); |
444 | 441 |
_processed->set(u,false); |
445 | 442 |
} |
446 | 443 |
} |
447 | 444 |
|
448 | 445 |
///Adds a new source node. |
449 | 446 |
|
450 | 447 |
///Adds a new source node to the set of nodes to be processed. |
451 | 448 |
/// |
452 | 449 |
void addSource(Node s) |
453 | 450 |
{ |
454 | 451 |
if(!(*_reached)[s]) |
455 | 452 |
{ |
456 | 453 |
_reached->set(s,true); |
457 | 454 |
_pred->set(s,INVALID); |
458 | 455 |
_dist->set(s,0); |
459 | 456 |
_queue[_queue_head++]=s; |
460 | 457 |
_queue_next_dist=_queue_head; |
461 | 458 |
} |
462 | 459 |
} |
463 | 460 |
|
464 | 461 |
///Processes the next node. |
465 | 462 |
|
466 | 463 |
///Processes the next node. |
467 | 464 |
/// |
468 | 465 |
///\return The processed node. |
469 | 466 |
/// |
470 | 467 |
///\pre The queue must not be empty. |
471 | 468 |
Node processNextNode() |
472 | 469 |
{ |
473 | 470 |
if(_queue_tail==_queue_next_dist) { |
474 | 471 |
_curr_dist++; |
475 | 472 |
_queue_next_dist=_queue_head; |
476 | 473 |
} |
477 | 474 |
Node n=_queue[_queue_tail++]; |
478 | 475 |
_processed->set(n,true); |
479 | 476 |
Node m; |
480 | 477 |
for(OutArcIt e(*G,n);e!=INVALID;++e) |
481 | 478 |
if(!(*_reached)[m=G->target(e)]) { |
482 | 479 |
_queue[_queue_head++]=m; |
483 | 480 |
_reached->set(m,true); |
484 | 481 |
_pred->set(m,e); |
485 | 482 |
_dist->set(m,_curr_dist); |
486 | 483 |
} |
487 | 484 |
return n; |
488 | 485 |
} |
489 | 486 |
|
490 | 487 |
///Processes the next node. |
491 | 488 |
|
492 | 489 |
///Processes the next node and checks if the given target node |
493 | 490 |
///is reached. If the target node is reachable from the processed |
494 | 491 |
///node, then the \c reach parameter will be set to \c true. |
495 | 492 |
/// |
496 | 493 |
///\param target The target node. |
497 | 494 |
///\retval reach Indicates if the target node is reached. |
498 | 495 |
///It should be initially \c false. |
499 | 496 |
/// |
500 | 497 |
///\return The processed node. |
501 | 498 |
/// |
502 | 499 |
///\pre The queue must not be empty. |
503 | 500 |
Node processNextNode(Node target, bool& reach) |
504 | 501 |
{ |
505 | 502 |
if(_queue_tail==_queue_next_dist) { |
506 | 503 |
_curr_dist++; |
507 | 504 |
_queue_next_dist=_queue_head; |
508 | 505 |
} |
509 | 506 |
Node n=_queue[_queue_tail++]; |
510 | 507 |
_processed->set(n,true); |
511 | 508 |
Node m; |
512 | 509 |
for(OutArcIt e(*G,n);e!=INVALID;++e) |
513 | 510 |
if(!(*_reached)[m=G->target(e)]) { |
514 | 511 |
_queue[_queue_head++]=m; |
515 | 512 |
_reached->set(m,true); |
516 | 513 |
_pred->set(m,e); |
517 | 514 |
_dist->set(m,_curr_dist); |
518 | 515 |
reach = reach || (target == m); |
519 | 516 |
} |
520 | 517 |
return n; |
521 | 518 |
} |
522 | 519 |
|
523 | 520 |
///Processes the next node. |
524 | 521 |
|
525 | 522 |
///Processes the next node and checks if at least one of reached |
526 | 523 |
///nodes has \c true value in the \c nm node map. If one node |
527 | 524 |
///with \c true value is reachable from the processed node, then the |
528 | 525 |
///\c rnode parameter will be set to the first of such nodes. |
529 | 526 |
/// |
530 | 527 |
///\param nm A \c bool (or convertible) node map that indicates the |
531 | 528 |
///possible targets. |
532 | 529 |
///\retval rnode The reached target node. |
533 | 530 |
///It should be initially \c INVALID. |
534 | 531 |
/// |
535 | 532 |
///\return The processed node. |
536 | 533 |
/// |
537 | 534 |
///\pre The queue must not be empty. |
538 | 535 |
template<class NM> |
539 | 536 |
Node processNextNode(const NM& nm, Node& rnode) |
540 | 537 |
{ |
541 | 538 |
if(_queue_tail==_queue_next_dist) { |
542 | 539 |
_curr_dist++; |
543 | 540 |
_queue_next_dist=_queue_head; |
544 | 541 |
} |
545 | 542 |
Node n=_queue[_queue_tail++]; |
546 | 543 |
_processed->set(n,true); |
547 | 544 |
Node m; |
548 | 545 |
for(OutArcIt e(*G,n);e!=INVALID;++e) |
549 | 546 |
if(!(*_reached)[m=G->target(e)]) { |
550 | 547 |
_queue[_queue_head++]=m; |
551 | 548 |
_reached->set(m,true); |
552 | 549 |
_pred->set(m,e); |
553 | 550 |
_dist->set(m,_curr_dist); |
554 | 551 |
if (nm[m] && rnode == INVALID) rnode = m; |
555 | 552 |
} |
556 | 553 |
return n; |
557 | 554 |
} |
558 | 555 |
|
559 | 556 |
///The next node to be processed. |
560 | 557 |
|
561 | 558 |
///Returns the next node to be processed or \c INVALID if the queue |
562 | 559 |
///is empty. |
563 | 560 |
Node nextNode() const |
564 | 561 |
{ |
565 | 562 |
return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID; |
566 | 563 |
} |
567 | 564 |
|
568 | 565 |
///\brief Returns \c false if there are nodes |
569 | 566 |
///to be processed. |
570 | 567 |
/// |
571 | 568 |
///Returns \c false if there are nodes |
572 | 569 |
///to be processed in the queue. |
573 | 570 |
bool emptyQueue() const { return _queue_tail==_queue_head; } |
574 | 571 |
|
575 | 572 |
///Returns the number of the nodes to be processed. |
576 | 573 |
|
577 | 574 |
///Returns the number of the nodes to be processed in the queue. |
578 | 575 |
int queueSize() const { return _queue_head-_queue_tail; } |
579 | 576 |
|
580 | 577 |
///Executes the algorithm. |
581 | 578 |
|
582 | 579 |
///Executes the algorithm. |
583 | 580 |
/// |
584 | 581 |
///This method runs the %BFS algorithm from the root node(s) |
585 | 582 |
///in order to compute the shortest path to each node. |
586 | 583 |
/// |
587 | 584 |
///The algorithm computes |
588 | 585 |
///- the shortest path tree (forest), |
589 | 586 |
///- the distance of each node from the root(s). |
590 | 587 |
/// |
591 | 588 |
///\pre init() must be called and at least one root node should be |
592 | 589 |
///added with addSource() before using this function. |
593 | 590 |
/// |
594 | 591 |
///\note <tt>b.start()</tt> is just a shortcut of the following code. |
595 | 592 |
///\code |
596 | 593 |
/// while ( !b.emptyQueue() ) { |
597 | 594 |
/// b.processNextNode(); |
598 | 595 |
/// } |
599 | 596 |
///\endcode |
600 | 597 |
void start() |
601 | 598 |
{ |
602 | 599 |
while ( !emptyQueue() ) processNextNode(); |
603 | 600 |
} |
604 | 601 |
|
605 | 602 |
///Executes the algorithm until the given target node is reached. |
606 | 603 |
|
607 | 604 |
///Executes the algorithm until the given target node is reached. |
608 | 605 |
/// |
609 | 606 |
///This method runs the %BFS algorithm from the root node(s) |
610 | 607 |
///in order to compute the shortest path to \c dest. |
611 | 608 |
/// |
612 | 609 |
///The algorithm computes |
613 | 610 |
///- the shortest path to \c dest, |
614 | 611 |
///- the distance of \c dest from the root(s). |
615 | 612 |
/// |
616 | 613 |
///\pre init() must be called and at least one root node should be |
617 | 614 |
///added with addSource() before using this function. |
618 | 615 |
/// |
619 | 616 |
///\note <tt>b.start(t)</tt> is just a shortcut of the following code. |
620 | 617 |
///\code |
621 | 618 |
/// bool reach = false; |
622 | 619 |
/// while ( !b.emptyQueue() && !reach ) { |
623 | 620 |
/// b.processNextNode(t, reach); |
624 | 621 |
/// } |
625 | 622 |
///\endcode |
626 | 623 |
void start(Node dest) |
627 | 624 |
{ |
628 | 625 |
bool reach = false; |
629 | 626 |
while ( !emptyQueue() && !reach ) processNextNode(dest, reach); |
630 | 627 |
} |
631 | 628 |
|
632 | 629 |
///Executes the algorithm until a condition is met. |
633 | 630 |
|
634 | 631 |
///Executes the algorithm until a condition is met. |
635 | 632 |
/// |
636 | 633 |
///This method runs the %BFS algorithm from the root node(s) in |
637 | 634 |
///order to compute the shortest path to a node \c v with |
638 | 635 |
/// <tt>nm[v]</tt> true, if such a node can be found. |
639 | 636 |
/// |
640 | 637 |
///\param nm A \c bool (or convertible) node map. The algorithm |
641 | 638 |
///will stop when it reaches a node \c v with <tt>nm[v]</tt> true. |
642 | 639 |
/// |
643 | 640 |
///\return The reached node \c v with <tt>nm[v]</tt> true or |
644 | 641 |
///\c INVALID if no such node was found. |
645 | 642 |
/// |
646 | 643 |
///\pre init() must be called and at least one root node should be |
647 | 644 |
///added with addSource() before using this function. |
648 | 645 |
/// |
649 | 646 |
///\note <tt>b.start(nm)</tt> is just a shortcut of the following code. |
650 | 647 |
///\code |
651 | 648 |
/// Node rnode = INVALID; |
652 | 649 |
/// while ( !b.emptyQueue() && rnode == INVALID ) { |
653 | 650 |
/// b.processNextNode(nm, rnode); |
654 | 651 |
/// } |
655 | 652 |
/// return rnode; |
656 | 653 |
///\endcode |
657 | 654 |
template<class NodeBoolMap> |
658 | 655 |
Node start(const NodeBoolMap &nm) |
659 | 656 |
{ |
660 | 657 |
Node rnode = INVALID; |
661 | 658 |
while ( !emptyQueue() && rnode == INVALID ) { |
662 | 659 |
processNextNode(nm, rnode); |
663 | 660 |
} |
664 | 661 |
return rnode; |
665 | 662 |
} |
666 | 663 |
|
667 | 664 |
///Runs the algorithm from the given node. |
668 | 665 |
|
669 | 666 |
///This method runs the %BFS algorithm from node \c s |
670 | 667 |
///in order to compute the shortest path to each node. |
671 | 668 |
/// |
672 | 669 |
///The algorithm computes |
673 | 670 |
///- the shortest path tree, |
674 | 671 |
///- the distance of each node from the root. |
675 | 672 |
/// |
676 | 673 |
///\note <tt>b.run(s)</tt> is just a shortcut of the following code. |
677 | 674 |
///\code |
678 | 675 |
/// b.init(); |
679 | 676 |
/// b.addSource(s); |
680 | 677 |
/// b.start(); |
681 | 678 |
///\endcode |
682 | 679 |
void run(Node s) { |
683 | 680 |
init(); |
684 | 681 |
addSource(s); |
685 | 682 |
start(); |
686 | 683 |
} |
687 | 684 |
|
688 | 685 |
///Finds the shortest path between \c s and \c t. |
689 | 686 |
|
690 | 687 |
///This method runs the %BFS algorithm from node \c s |
691 | 688 |
///in order to compute the shortest path to \c t. |
692 | 689 |
/// |
693 | 690 |
///\return The length of the shortest <tt>s</tt>--<tt>t</tt> path, |
694 | 691 |
///if \c t is reachable form \c s, \c 0 otherwise. |
695 | 692 |
/// |
696 | 693 |
///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a |
697 | 694 |
///shortcut of the following code. |
698 | 695 |
///\code |
699 | 696 |
/// b.init(); |
700 | 697 |
/// b.addSource(s); |
701 | 698 |
/// b.start(t); |
702 | 699 |
///\endcode |
703 | 700 |
int run(Node s,Node t) { |
704 | 701 |
init(); |
705 | 702 |
addSource(s); |
706 | 703 |
start(t); |
707 | 704 |
return reached(t) ? _curr_dist : 0; |
708 | 705 |
} |
709 | 706 |
|
710 | 707 |
///Runs the algorithm to visit all nodes in the digraph. |
711 | 708 |
|
712 | 709 |
///This method runs the %BFS algorithm in order to |
713 | 710 |
///compute the shortest path to each node. |
714 | 711 |
/// |
715 | 712 |
///The algorithm computes |
716 | 713 |
///- the shortest path tree (forest), |
717 | 714 |
///- the distance of each node from the root(s). |
718 | 715 |
/// |
719 | 716 |
///\note <tt>b.run(s)</tt> is just a shortcut of the following code. |
720 | 717 |
///\code |
721 | 718 |
/// b.init(); |
722 | 719 |
/// for (NodeIt n(gr); n != INVALID; ++n) { |
723 | 720 |
/// if (!b.reached(n)) { |
724 | 721 |
/// b.addSource(n); |
725 | 722 |
/// b.start(); |
726 | 723 |
/// } |
727 | 724 |
/// } |
728 | 725 |
///\endcode |
729 | 726 |
void run() { |
730 | 727 |
init(); |
731 | 728 |
for (NodeIt n(*G); n != INVALID; ++n) { |
732 | 729 |
if (!reached(n)) { |
733 | 730 |
addSource(n); |
734 | 731 |
start(); |
735 | 732 |
} |
736 | 733 |
} |
737 | 734 |
} |
738 | 735 |
|
739 | 736 |
///@} |
740 | 737 |
|
741 | 738 |
///\name Query Functions |
742 | 739 |
///The result of the %BFS algorithm can be obtained using these |
743 | 740 |
///functions.\n |
744 | 741 |
///Either \ref lemon::Bfs::run() "run()" or \ref lemon::Bfs::start() |
745 | 742 |
///"start()" must be called before using them. |
746 | 743 |
|
747 | 744 |
///@{ |
748 | 745 |
|
749 | 746 |
///The shortest path to a node. |
750 | 747 |
|
751 | 748 |
///Returns the shortest path to a node. |
752 | 749 |
/// |
753 | 750 |
///\warning \c t should be reachable from the root(s). |
754 | 751 |
/// |
755 | 752 |
///\pre Either \ref run() or \ref start() must be called before |
756 | 753 |
///using this function. |
757 | 754 |
Path path(Node t) const { return Path(*G, *_pred, t); } |
758 | 755 |
|
759 | 756 |
///The distance of a node from the root(s). |
760 | 757 |
|
761 | 758 |
///Returns the distance of a node from the root(s). |
762 | 759 |
/// |
763 | 760 |
///\warning If node \c v is not reachable from the root(s), then |
764 | 761 |
///the return value of this function is undefined. |
765 | 762 |
/// |
766 | 763 |
///\pre Either \ref run() or \ref start() must be called before |
767 | 764 |
///using this function. |
768 | 765 |
int dist(Node v) const { return (*_dist)[v]; } |
769 | 766 |
|
770 | 767 |
///Returns the 'previous arc' of the shortest path tree for a node. |
771 | 768 |
|
772 | 769 |
///This function returns the 'previous arc' of the shortest path |
773 | 770 |
///tree for the node \c v, i.e. it returns the last arc of a |
774 | 771 |
///shortest path from the root(s) to \c v. It is \c INVALID if \c v |
775 | 772 |
///is not reachable from the root(s) or if \c v is a root. |
776 | 773 |
/// |
777 | 774 |
///The shortest path tree used here is equal to the shortest path |
778 | 775 |
///tree used in \ref predNode(). |
779 | 776 |
/// |
780 | 777 |
///\pre Either \ref run() or \ref start() must be called before |
781 | 778 |
///using this function. |
782 | 779 |
Arc predArc(Node v) const { return (*_pred)[v];} |
783 | 780 |
|
784 | 781 |
///Returns the 'previous node' of the shortest path tree for a node. |
785 | 782 |
|
786 | 783 |
///This function returns the 'previous node' of the shortest path |
787 | 784 |
///tree for the node \c v, i.e. it returns the last but one node |
788 | 785 |
///from a shortest path from the root(s) to \c v. It is \c INVALID |
789 | 786 |
///if \c v is not reachable from the root(s) or if \c v is a root. |
790 | 787 |
/// |
791 | 788 |
///The shortest path tree used here is equal to the shortest path |
792 | 789 |
///tree used in \ref predArc(). |
793 | 790 |
/// |
794 | 791 |
///\pre Either \ref run() or \ref start() must be called before |
795 | 792 |
///using this function. |
796 | 793 |
Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID: |
797 | 794 |
G->source((*_pred)[v]); } |
798 | 795 |
|
799 | 796 |
///\brief Returns a const reference to the node map that stores the |
800 | 797 |
/// distances of the nodes. |
801 | 798 |
/// |
802 | 799 |
///Returns a const reference to the node map that stores the distances |
803 | 800 |
///of the nodes calculated by the algorithm. |
804 | 801 |
/// |
805 | 802 |
///\pre Either \ref run() or \ref init() |
806 | 803 |
///must be called before using this function. |
807 | 804 |
const DistMap &distMap() const { return *_dist;} |
808 | 805 |
|
809 | 806 |
///\brief Returns a const reference to the node map that stores the |
810 | 807 |
///predecessor arcs. |
811 | 808 |
/// |
812 | 809 |
///Returns a const reference to the node map that stores the predecessor |
813 | 810 |
///arcs, which form the shortest path tree. |
814 | 811 |
/// |
815 | 812 |
///\pre Either \ref run() or \ref init() |
816 | 813 |
///must be called before using this function. |
817 | 814 |
const PredMap &predMap() const { return *_pred;} |
818 | 815 |
|
819 | 816 |
///Checks if a node is reachable from the root(s). |
820 | 817 |
|
821 | 818 |
///Returns \c true if \c v is reachable from the root(s). |
822 | 819 |
///\pre Either \ref run() or \ref start() |
823 | 820 |
///must be called before using this function. |
824 | 821 |
bool reached(Node v) const { return (*_reached)[v]; } |
825 | 822 |
|
826 | 823 |
///@} |
827 | 824 |
}; |
828 | 825 |
|
829 | 826 |
///Default traits class of bfs() function. |
830 | 827 |
|
831 | 828 |
///Default traits class of bfs() function. |
832 | 829 |
///\tparam GR Digraph type. |
833 | 830 |
template<class GR> |
834 | 831 |
struct BfsWizardDefaultTraits |
835 | 832 |
{ |
836 | 833 |
///The type of the digraph the algorithm runs on. |
837 | 834 |
typedef GR Digraph; |
838 | 835 |
|
839 | 836 |
///\brief The type of the map that stores the predecessor |
840 | 837 |
///arcs of the shortest paths. |
841 | 838 |
/// |
842 | 839 |
///The type of the map that stores the predecessor |
843 | 840 |
///arcs of the shortest paths. |
844 | 841 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
845 | 842 |
typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap; |
846 | 843 |
///Instantiates a \ref PredMap. |
847 | 844 |
|
848 | 845 |
///This function instantiates a \ref PredMap. |
849 | 846 |
///\param g is the digraph, to which we would like to define the |
850 | 847 |
///\ref PredMap. |
851 |
///\todo The digraph alone may be insufficient to initialize |
|
852 | 848 |
static PredMap *createPredMap(const Digraph &g) |
853 | 849 |
{ |
854 | 850 |
return new PredMap(g); |
855 | 851 |
} |
856 | 852 |
|
857 | 853 |
///The type of the map that indicates which nodes are processed. |
858 | 854 |
|
859 | 855 |
///The type of the map that indicates which nodes are processed. |
860 | 856 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
861 | 857 |
///By default it is a NullMap. |
862 | 858 |
typedef NullMap<typename Digraph::Node,bool> ProcessedMap; |
863 | 859 |
///Instantiates a \ref ProcessedMap. |
864 | 860 |
|
865 | 861 |
///This function instantiates a \ref ProcessedMap. |
866 | 862 |
///\param g is the digraph, to which |
867 | 863 |
///we would like to define the \ref ProcessedMap. |
868 | 864 |
#ifdef DOXYGEN |
869 | 865 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
870 | 866 |
#else |
871 | 867 |
static ProcessedMap *createProcessedMap(const Digraph &) |
872 | 868 |
#endif |
873 | 869 |
{ |
874 | 870 |
return new ProcessedMap(); |
875 | 871 |
} |
876 | 872 |
|
877 | 873 |
///The type of the map that indicates which nodes are reached. |
878 | 874 |
|
879 | 875 |
///The type of the map that indicates which nodes are reached. |
880 | 876 |
///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept. |
881 | 877 |
typedef typename Digraph::template NodeMap<bool> ReachedMap; |
882 | 878 |
///Instantiates a \ref ReachedMap. |
883 | 879 |
|
884 | 880 |
///This function instantiates a \ref ReachedMap. |
885 | 881 |
///\param g is the digraph, to which |
886 | 882 |
///we would like to define the \ref ReachedMap. |
887 | 883 |
static ReachedMap *createReachedMap(const Digraph &g) |
888 | 884 |
{ |
889 | 885 |
return new ReachedMap(g); |
890 | 886 |
} |
891 | 887 |
|
892 | 888 |
///The type of the map that stores the distances of the nodes. |
893 | 889 |
|
894 | 890 |
///The type of the map that stores the distances of the nodes. |
895 | 891 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
896 | 892 |
typedef typename Digraph::template NodeMap<int> DistMap; |
897 | 893 |
///Instantiates a \ref DistMap. |
898 | 894 |
|
899 | 895 |
///This function instantiates a \ref DistMap. |
900 | 896 |
///\param g is the digraph, to which we would like to define |
901 | 897 |
///the \ref DistMap |
902 | 898 |
static DistMap *createDistMap(const Digraph &g) |
903 | 899 |
{ |
904 | 900 |
return new DistMap(g); |
905 | 901 |
} |
906 | 902 |
|
907 | 903 |
///The type of the shortest paths. |
908 | 904 |
|
909 | 905 |
///The type of the shortest paths. |
910 | 906 |
///It must meet the \ref concepts::Path "Path" concept. |
911 | 907 |
typedef lemon::Path<Digraph> Path; |
912 | 908 |
}; |
913 | 909 |
|
914 | 910 |
/// Default traits class used by \ref BfsWizard |
915 | 911 |
|
916 | 912 |
/// To make it easier to use Bfs algorithm |
917 | 913 |
/// we have created a wizard class. |
918 | 914 |
/// This \ref BfsWizard class needs default traits, |
919 | 915 |
/// as well as the \ref Bfs class. |
920 | 916 |
/// The \ref BfsWizardBase is a class to be the default traits of the |
921 | 917 |
/// \ref BfsWizard class. |
922 | 918 |
template<class GR> |
923 | 919 |
class BfsWizardBase : public BfsWizardDefaultTraits<GR> |
924 | 920 |
{ |
925 | 921 |
|
926 | 922 |
typedef BfsWizardDefaultTraits<GR> Base; |
927 | 923 |
protected: |
928 | 924 |
//The type of the nodes in the digraph. |
929 | 925 |
typedef typename Base::Digraph::Node Node; |
930 | 926 |
|
931 | 927 |
//Pointer to the digraph the algorithm runs on. |
932 | 928 |
void *_g; |
933 | 929 |
//Pointer to the map of reached nodes. |
934 | 930 |
void *_reached; |
935 | 931 |
//Pointer to the map of processed nodes. |
936 | 932 |
void *_processed; |
937 | 933 |
//Pointer to the map of predecessors arcs. |
938 | 934 |
void *_pred; |
939 | 935 |
//Pointer to the map of distances. |
940 | 936 |
void *_dist; |
941 | 937 |
//Pointer to the shortest path to the target node. |
942 | 938 |
void *_path; |
943 | 939 |
//Pointer to the distance of the target node. |
944 | 940 |
int *_di; |
945 | 941 |
|
946 | 942 |
public: |
947 | 943 |
/// Constructor. |
948 | 944 |
|
949 | 945 |
/// This constructor does not require parameters, therefore it initiates |
950 | 946 |
/// all of the attributes to \c 0. |
951 | 947 |
BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0), |
952 | 948 |
_dist(0), _path(0), _di(0) {} |
953 | 949 |
|
954 | 950 |
/// Constructor. |
955 | 951 |
|
956 | 952 |
/// This constructor requires one parameter, |
957 | 953 |
/// others are initiated to \c 0. |
958 | 954 |
/// \param g The digraph the algorithm runs on. |
959 | 955 |
BfsWizardBase(const GR &g) : |
960 | 956 |
_g(reinterpret_cast<void*>(const_cast<GR*>(&g))), |
961 | 957 |
_reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {} |
962 | 958 |
|
963 | 959 |
}; |
964 | 960 |
|
965 | 961 |
/// Auxiliary class for the function-type interface of BFS algorithm. |
966 | 962 |
|
967 | 963 |
/// This auxiliary class is created to implement the |
968 | 964 |
/// \ref bfs() "function-type interface" of \ref Bfs algorithm. |
969 | 965 |
/// It does not have own \ref run() method, it uses the functions |
970 | 966 |
/// and features of the plain \ref Bfs. |
971 | 967 |
/// |
972 | 968 |
/// This class should only be used through the \ref bfs() function, |
973 | 969 |
/// which makes it easier to use the algorithm. |
974 | 970 |
template<class TR> |
975 | 971 |
class BfsWizard : public TR |
976 | 972 |
{ |
977 | 973 |
typedef TR Base; |
978 | 974 |
|
979 | 975 |
///The type of the digraph the algorithm runs on. |
980 | 976 |
typedef typename TR::Digraph Digraph; |
981 | 977 |
|
982 | 978 |
typedef typename Digraph::Node Node; |
983 | 979 |
typedef typename Digraph::NodeIt NodeIt; |
984 | 980 |
typedef typename Digraph::Arc Arc; |
985 | 981 |
typedef typename Digraph::OutArcIt OutArcIt; |
986 | 982 |
|
987 | 983 |
///\brief The type of the map that stores the predecessor |
988 | 984 |
///arcs of the shortest paths. |
989 | 985 |
typedef typename TR::PredMap PredMap; |
990 | 986 |
///\brief The type of the map that stores the distances of the nodes. |
991 | 987 |
typedef typename TR::DistMap DistMap; |
992 | 988 |
///\brief The type of the map that indicates which nodes are reached. |
993 | 989 |
typedef typename TR::ReachedMap ReachedMap; |
994 | 990 |
///\brief The type of the map that indicates which nodes are processed. |
995 | 991 |
typedef typename TR::ProcessedMap ProcessedMap; |
996 | 992 |
///The type of the shortest paths |
997 | 993 |
typedef typename TR::Path Path; |
998 | 994 |
|
999 | 995 |
public: |
1000 | 996 |
|
1001 | 997 |
/// Constructor. |
1002 | 998 |
BfsWizard() : TR() {} |
1003 | 999 |
|
1004 | 1000 |
/// Constructor that requires parameters. |
1005 | 1001 |
|
1006 | 1002 |
/// Constructor that requires parameters. |
1007 | 1003 |
/// These parameters will be the default values for the traits class. |
1008 | 1004 |
/// \param g The digraph the algorithm runs on. |
1009 | 1005 |
BfsWizard(const Digraph &g) : |
1010 | 1006 |
TR(g) {} |
1011 | 1007 |
|
1012 | 1008 |
///Copy constructor |
1013 | 1009 |
BfsWizard(const TR &b) : TR(b) {} |
1014 | 1010 |
|
1015 | 1011 |
~BfsWizard() {} |
1016 | 1012 |
|
1017 | 1013 |
///Runs BFS algorithm from the given source node. |
1018 | 1014 |
|
1019 | 1015 |
///This method runs BFS algorithm from node \c s |
1020 | 1016 |
///in order to compute the shortest path to each node. |
1021 | 1017 |
void run(Node s) |
1022 | 1018 |
{ |
1023 | 1019 |
Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g)); |
1024 | 1020 |
if (Base::_pred) |
1025 | 1021 |
alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); |
1026 | 1022 |
if (Base::_dist) |
1027 | 1023 |
alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); |
1028 | 1024 |
if (Base::_reached) |
1029 | 1025 |
alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached)); |
1030 | 1026 |
if (Base::_processed) |
1031 | 1027 |
alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed)); |
1032 | 1028 |
if (s!=INVALID) |
1033 | 1029 |
alg.run(s); |
1034 | 1030 |
else |
1035 | 1031 |
alg.run(); |
1036 | 1032 |
} |
1037 | 1033 |
|
1038 | 1034 |
///Finds the shortest path between \c s and \c t. |
1039 | 1035 |
|
1040 | 1036 |
///This method runs BFS algorithm from node \c s |
1041 | 1037 |
///in order to compute the shortest path to node \c t |
1042 | 1038 |
///(it stops searching when \c t is processed). |
1043 | 1039 |
/// |
1044 | 1040 |
///\return \c true if \c t is reachable form \c s. |
1045 | 1041 |
bool run(Node s, Node t) |
1046 | 1042 |
{ |
1047 | 1043 |
if (s==INVALID || t==INVALID) throw UninitializedParameter(); |
1048 | 1044 |
Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g)); |
1049 | 1045 |
if (Base::_pred) |
1050 | 1046 |
alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); |
1051 | 1047 |
if (Base::_dist) |
1052 | 1048 |
alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); |
1053 | 1049 |
if (Base::_reached) |
1054 | 1050 |
alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached)); |
1055 | 1051 |
if (Base::_processed) |
1056 | 1052 |
alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed)); |
1057 | 1053 |
alg.run(s,t); |
1058 | 1054 |
if (Base::_path) |
1059 | 1055 |
*reinterpret_cast<Path*>(Base::_path) = alg.path(t); |
1060 | 1056 |
if (Base::_di) |
1061 | 1057 |
*Base::_di = alg.dist(t); |
1062 | 1058 |
return alg.reached(t); |
1063 | 1059 |
} |
1064 | 1060 |
|
1065 | 1061 |
///Runs BFS algorithm to visit all nodes in the digraph. |
1066 | 1062 |
|
1067 | 1063 |
///This method runs BFS algorithm in order to compute |
1068 | 1064 |
///the shortest path to each node. |
1069 | 1065 |
void run() |
1070 | 1066 |
{ |
1071 | 1067 |
run(INVALID); |
1072 | 1068 |
} |
1073 | 1069 |
|
1074 | 1070 |
template<class T> |
1075 | 1071 |
struct SetPredMapBase : public Base { |
1076 | 1072 |
typedef T PredMap; |
1077 | 1073 |
static PredMap *createPredMap(const Digraph &) { return 0; }; |
1078 | 1074 |
SetPredMapBase(const TR &b) : TR(b) {} |
1079 | 1075 |
}; |
1080 | 1076 |
///\brief \ref named-func-param "Named parameter" |
1081 | 1077 |
///for setting \ref PredMap object. |
1082 | 1078 |
/// |
1083 | 1079 |
///\ref named-func-param "Named parameter" |
1084 | 1080 |
///for setting \ref PredMap object. |
1085 | 1081 |
template<class T> |
1086 | 1082 |
BfsWizard<SetPredMapBase<T> > predMap(const T &t) |
1087 | 1083 |
{ |
1088 | 1084 |
Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1089 | 1085 |
return BfsWizard<SetPredMapBase<T> >(*this); |
1090 | 1086 |
} |
1091 | 1087 |
|
1092 | 1088 |
template<class T> |
1093 | 1089 |
struct SetReachedMapBase : public Base { |
1094 | 1090 |
typedef T ReachedMap; |
1095 | 1091 |
static ReachedMap *createReachedMap(const Digraph &) { return 0; }; |
1096 | 1092 |
SetReachedMapBase(const TR &b) : TR(b) {} |
1097 | 1093 |
}; |
1098 | 1094 |
///\brief \ref named-func-param "Named parameter" |
1099 | 1095 |
///for setting \ref ReachedMap object. |
1100 | 1096 |
/// |
1101 | 1097 |
/// \ref named-func-param "Named parameter" |
1102 | 1098 |
///for setting \ref ReachedMap object. |
1103 | 1099 |
template<class T> |
1104 | 1100 |
BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t) |
1105 | 1101 |
{ |
1106 | 1102 |
Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1107 | 1103 |
return BfsWizard<SetReachedMapBase<T> >(*this); |
1108 | 1104 |
} |
1109 | 1105 |
|
1110 | 1106 |
template<class T> |
1111 | 1107 |
struct SetDistMapBase : public Base { |
1112 | 1108 |
typedef T DistMap; |
1113 | 1109 |
static DistMap *createDistMap(const Digraph &) { return 0; }; |
1114 | 1110 |
SetDistMapBase(const TR &b) : TR(b) {} |
1115 | 1111 |
}; |
1116 | 1112 |
///\brief \ref named-func-param "Named parameter" |
1117 | 1113 |
///for setting \ref DistMap object. |
1118 | 1114 |
/// |
1119 | 1115 |
/// \ref named-func-param "Named parameter" |
1120 | 1116 |
///for setting \ref DistMap object. |
1121 | 1117 |
template<class T> |
1122 | 1118 |
BfsWizard<SetDistMapBase<T> > distMap(const T &t) |
1123 | 1119 |
{ |
1124 | 1120 |
Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1125 | 1121 |
return BfsWizard<SetDistMapBase<T> >(*this); |
1126 | 1122 |
} |
1127 | 1123 |
|
1128 | 1124 |
template<class T> |
1129 | 1125 |
struct SetProcessedMapBase : public Base { |
1130 | 1126 |
typedef T ProcessedMap; |
1131 | 1127 |
static ProcessedMap *createProcessedMap(const Digraph &) { return 0; }; |
1132 | 1128 |
SetProcessedMapBase(const TR &b) : TR(b) {} |
1133 | 1129 |
}; |
1134 | 1130 |
///\brief \ref named-func-param "Named parameter" |
1135 | 1131 |
///for setting \ref ProcessedMap object. |
1136 | 1132 |
/// |
1137 | 1133 |
/// \ref named-func-param "Named parameter" |
1138 | 1134 |
///for setting \ref ProcessedMap object. |
1139 | 1135 |
template<class T> |
1140 | 1136 |
BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t) |
1141 | 1137 |
{ |
1142 | 1138 |
Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1143 | 1139 |
return BfsWizard<SetProcessedMapBase<T> >(*this); |
1144 | 1140 |
} |
1145 | 1141 |
|
1146 | 1142 |
template<class T> |
1147 | 1143 |
struct SetPathBase : public Base { |
1148 | 1144 |
typedef T Path; |
1149 | 1145 |
SetPathBase(const TR &b) : TR(b) {} |
1150 | 1146 |
}; |
1151 | 1147 |
///\brief \ref named-func-param "Named parameter" |
1152 | 1148 |
///for getting the shortest path to the target node. |
1153 | 1149 |
/// |
1154 | 1150 |
///\ref named-func-param "Named parameter" |
1155 | 1151 |
///for getting the shortest path to the target node. |
1156 | 1152 |
template<class T> |
1157 | 1153 |
BfsWizard<SetPathBase<T> > path(const T &t) |
1158 | 1154 |
{ |
1159 | 1155 |
Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1160 | 1156 |
return BfsWizard<SetPathBase<T> >(*this); |
1161 | 1157 |
} |
1162 | 1158 |
|
1163 | 1159 |
///\brief \ref named-func-param "Named parameter" |
1164 | 1160 |
///for getting the distance of the target node. |
1165 | 1161 |
/// |
1166 | 1162 |
///\ref named-func-param "Named parameter" |
1167 | 1163 |
///for getting the distance of the target node. |
1168 | 1164 |
BfsWizard dist(const int &d) |
1169 | 1165 |
{ |
1170 | 1166 |
Base::_di=const_cast<int*>(&d); |
1171 | 1167 |
return *this; |
1172 | 1168 |
} |
1173 | 1169 |
|
1174 | 1170 |
}; |
1175 | 1171 |
|
1176 | 1172 |
///Function-type interface for BFS algorithm. |
1177 | 1173 |
|
1178 | 1174 |
/// \ingroup search |
1179 | 1175 |
///Function-type interface for BFS algorithm. |
1180 | 1176 |
/// |
1181 | 1177 |
///This function also has several \ref named-func-param "named parameters", |
1182 | 1178 |
///they are declared as the members of class \ref BfsWizard. |
1183 | 1179 |
///The following examples show how to use these parameters. |
1184 | 1180 |
///\code |
1185 | 1181 |
/// // Compute shortest path from node s to each node |
1186 | 1182 |
/// bfs(g).predMap(preds).distMap(dists).run(s); |
1187 | 1183 |
/// |
1188 | 1184 |
/// // Compute shortest path from s to t |
1189 | 1185 |
/// bool reached = bfs(g).path(p).dist(d).run(s,t); |
1190 | 1186 |
///\endcode |
1191 | 1187 |
///\warning Don't forget to put the \ref BfsWizard::run() "run()" |
1192 | 1188 |
///to the end of the parameter list. |
1193 | 1189 |
///\sa BfsWizard |
1194 | 1190 |
///\sa Bfs |
1195 | 1191 |
template<class GR> |
1196 | 1192 |
BfsWizard<BfsWizardBase<GR> > |
1197 | 1193 |
bfs(const GR &digraph) |
1198 | 1194 |
{ |
1199 | 1195 |
return BfsWizard<BfsWizardBase<GR> >(digraph); |
1200 | 1196 |
} |
1201 | 1197 |
|
1202 | 1198 |
#ifdef DOXYGEN |
1203 | 1199 |
/// \brief Visitor class for BFS. |
1204 | 1200 |
/// |
1205 | 1201 |
/// This class defines the interface of the BfsVisit events, and |
1206 | 1202 |
/// it could be the base of a real visitor class. |
1207 | 1203 |
template <typename _Digraph> |
1208 | 1204 |
struct BfsVisitor { |
1209 | 1205 |
typedef _Digraph Digraph; |
1210 | 1206 |
typedef typename Digraph::Arc Arc; |
1211 | 1207 |
typedef typename Digraph::Node Node; |
1212 | 1208 |
/// \brief Called for the source node(s) of the BFS. |
1213 | 1209 |
/// |
1214 | 1210 |
/// This function is called for the source node(s) of the BFS. |
1215 | 1211 |
void start(const Node& node) {} |
1216 | 1212 |
/// \brief Called when a node is reached first time. |
1217 | 1213 |
/// |
1218 | 1214 |
/// This function is called when a node is reached first time. |
1219 | 1215 |
void reach(const Node& node) {} |
1220 | 1216 |
/// \brief Called when a node is processed. |
1221 | 1217 |
/// |
1222 | 1218 |
/// This function is called when a node is processed. |
1223 | 1219 |
void process(const Node& node) {} |
1224 | 1220 |
/// \brief Called when an arc reaches a new node. |
1225 | 1221 |
/// |
1226 | 1222 |
/// This function is called when the BFS finds an arc whose target node |
1227 | 1223 |
/// is not reached yet. |
1228 | 1224 |
void discover(const Arc& arc) {} |
1229 | 1225 |
/// \brief Called when an arc is examined but its target node is |
1230 | 1226 |
/// already discovered. |
1231 | 1227 |
/// |
1232 | 1228 |
/// This function is called when an arc is examined but its target node is |
1233 | 1229 |
/// already discovered. |
1234 | 1230 |
void examine(const Arc& arc) {} |
1235 | 1231 |
}; |
1236 | 1232 |
#else |
1237 | 1233 |
template <typename _Digraph> |
1238 | 1234 |
struct BfsVisitor { |
1239 | 1235 |
typedef _Digraph Digraph; |
1240 | 1236 |
typedef typename Digraph::Arc Arc; |
1241 | 1237 |
typedef typename Digraph::Node Node; |
1242 | 1238 |
void start(const Node&) {} |
1243 | 1239 |
void reach(const Node&) {} |
1244 | 1240 |
void process(const Node&) {} |
1245 | 1241 |
void discover(const Arc&) {} |
1246 | 1242 |
void examine(const Arc&) {} |
1247 | 1243 |
|
1248 | 1244 |
template <typename _Visitor> |
1249 | 1245 |
struct Constraints { |
1250 | 1246 |
void constraints() { |
1251 | 1247 |
Arc arc; |
1252 | 1248 |
Node node; |
1253 | 1249 |
visitor.start(node); |
1254 | 1250 |
visitor.reach(node); |
1255 | 1251 |
visitor.process(node); |
1256 | 1252 |
visitor.discover(arc); |
1257 | 1253 |
visitor.examine(arc); |
1258 | 1254 |
} |
1259 | 1255 |
_Visitor& visitor; |
1260 | 1256 |
}; |
1261 | 1257 |
}; |
1262 | 1258 |
#endif |
1263 | 1259 |
|
1264 | 1260 |
/// \brief Default traits class of BfsVisit class. |
1265 | 1261 |
/// |
1266 | 1262 |
/// Default traits class of BfsVisit class. |
1267 | 1263 |
/// \tparam _Digraph The type of the digraph the algorithm runs on. |
1268 | 1264 |
template<class _Digraph> |
1269 | 1265 |
struct BfsVisitDefaultTraits { |
1270 | 1266 |
|
1271 | 1267 |
/// \brief The type of the digraph the algorithm runs on. |
1272 | 1268 |
typedef _Digraph Digraph; |
1273 | 1269 |
|
1274 | 1270 |
/// \brief The type of the map that indicates which nodes are reached. |
1275 | 1271 |
/// |
1276 | 1272 |
/// The type of the map that indicates which nodes are reached. |
1277 | 1273 |
/// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept. |
1278 | 1274 |
typedef typename Digraph::template NodeMap<bool> ReachedMap; |
1279 | 1275 |
|
1280 | 1276 |
/// \brief Instantiates a \ref ReachedMap. |
1281 | 1277 |
/// |
1282 | 1278 |
/// This function instantiates a \ref ReachedMap. |
1283 | 1279 |
/// \param digraph is the digraph, to which |
1284 | 1280 |
/// we would like to define the \ref ReachedMap. |
1285 | 1281 |
static ReachedMap *createReachedMap(const Digraph &digraph) { |
1286 | 1282 |
return new ReachedMap(digraph); |
1287 | 1283 |
} |
1288 | 1284 |
|
1289 | 1285 |
}; |
1290 | 1286 |
|
1291 | 1287 |
/// \ingroup search |
1292 | 1288 |
/// |
1293 | 1289 |
/// \brief %BFS algorithm class with visitor interface. |
1294 | 1290 |
/// |
1295 | 1291 |
/// This class provides an efficient implementation of the %BFS algorithm |
1296 | 1292 |
/// with visitor interface. |
1297 | 1293 |
/// |
1298 | 1294 |
/// The %BfsVisit class provides an alternative interface to the Bfs |
1299 | 1295 |
/// class. It works with callback mechanism, the BfsVisit object calls |
1300 | 1296 |
/// the member functions of the \c Visitor class on every BFS event. |
1301 | 1297 |
/// |
1302 | 1298 |
/// This interface of the BFS algorithm should be used in special cases |
1303 | 1299 |
/// when extra actions have to be performed in connection with certain |
1304 | 1300 |
/// events of the BFS algorithm. Otherwise consider to use Bfs or bfs() |
1305 | 1301 |
/// instead. |
1306 | 1302 |
/// |
1307 | 1303 |
/// \tparam _Digraph The type of the digraph the algorithm runs on. |
1308 | 1304 |
/// The default value is |
1309 | 1305 |
/// \ref ListDigraph. The value of _Digraph is not used directly by |
1310 | 1306 |
/// \ref BfsVisit, it is only passed to \ref BfsVisitDefaultTraits. |
1311 | 1307 |
/// \tparam _Visitor The Visitor type that is used by the algorithm. |
1312 | 1308 |
/// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty visitor, which |
1313 | 1309 |
/// does not observe the BFS events. If you want to observe the BFS |
1314 | 1310 |
/// events, you should implement your own visitor class. |
1315 | 1311 |
/// \tparam _Traits Traits class to set various data types used by the |
1316 | 1312 |
/// algorithm. The default traits class is |
1317 | 1313 |
/// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>". |
1318 | 1314 |
/// See \ref BfsVisitDefaultTraits for the documentation of |
1319 | 1315 |
/// a BFS visit traits class. |
1320 | 1316 |
#ifdef DOXYGEN |
1321 | 1317 |
template <typename _Digraph, typename _Visitor, typename _Traits> |
1322 | 1318 |
#else |
1323 | 1319 |
template <typename _Digraph = ListDigraph, |
1324 | 1320 |
typename _Visitor = BfsVisitor<_Digraph>, |
1325 | 1321 |
typename _Traits = BfsDefaultTraits<_Digraph> > |
1326 | 1322 |
#endif |
1327 | 1323 |
class BfsVisit { |
1328 | 1324 |
public: |
1329 | 1325 |
|
1330 | 1326 |
/// \brief \ref Exception for uninitialized parameters. |
1331 | 1327 |
/// |
1332 | 1328 |
/// This error represents problems in the initialization |
1333 | 1329 |
/// of the parameters of the algorithm. |
1334 | 1330 |
class UninitializedParameter : public lemon::UninitializedParameter { |
1335 | 1331 |
public: |
1336 | 1332 |
virtual const char* what() const throw() |
1337 | 1333 |
{ |
1338 | 1334 |
return "lemon::BfsVisit::UninitializedParameter"; |
1339 | 1335 |
} |
1340 | 1336 |
}; |
1341 | 1337 |
|
1342 | 1338 |
///The traits class. |
1343 | 1339 |
typedef _Traits Traits; |
1344 | 1340 |
|
1345 | 1341 |
///The type of the digraph the algorithm runs on. |
1346 | 1342 |
typedef typename Traits::Digraph Digraph; |
1347 | 1343 |
|
1348 | 1344 |
///The visitor type used by the algorithm. |
1349 | 1345 |
typedef _Visitor Visitor; |
1350 | 1346 |
|
1351 | 1347 |
///The type of the map that indicates which nodes are reached. |
1352 | 1348 |
typedef typename Traits::ReachedMap ReachedMap; |
1353 | 1349 |
|
1354 | 1350 |
private: |
1355 | 1351 |
|
1356 | 1352 |
typedef typename Digraph::Node Node; |
1357 | 1353 |
typedef typename Digraph::NodeIt NodeIt; |
1358 | 1354 |
typedef typename Digraph::Arc Arc; |
1359 | 1355 |
typedef typename Digraph::OutArcIt OutArcIt; |
1360 | 1356 |
|
1361 | 1357 |
//Pointer to the underlying digraph. |
1362 | 1358 |
const Digraph *_digraph; |
1363 | 1359 |
//Pointer to the visitor object. |
1364 | 1360 |
Visitor *_visitor; |
1365 | 1361 |
//Pointer to the map of reached status of the nodes. |
1366 | 1362 |
ReachedMap *_reached; |
1367 | 1363 |
//Indicates if _reached is locally allocated (true) or not. |
1368 | 1364 |
bool local_reached; |
1369 | 1365 |
|
1370 | 1366 |
std::vector<typename Digraph::Node> _list; |
1371 | 1367 |
int _list_front, _list_back; |
1372 | 1368 |
|
1373 |
///Creates the maps if necessary. |
|
1374 |
///\todo Better memory allocation (instead of new). |
|
1369 |
//Creates the maps if necessary. |
|
1375 | 1370 |
void create_maps() { |
1376 | 1371 |
if(!_reached) { |
1377 | 1372 |
local_reached = true; |
1378 | 1373 |
_reached = Traits::createReachedMap(*_digraph); |
1379 | 1374 |
} |
1380 | 1375 |
} |
1381 | 1376 |
|
1382 | 1377 |
protected: |
1383 | 1378 |
|
1384 | 1379 |
BfsVisit() {} |
1385 | 1380 |
|
1386 | 1381 |
public: |
1387 | 1382 |
|
1388 | 1383 |
typedef BfsVisit Create; |
1389 | 1384 |
|
1390 | 1385 |
/// \name Named template parameters |
1391 | 1386 |
|
1392 | 1387 |
///@{ |
1393 | 1388 |
template <class T> |
1394 | 1389 |
struct SetReachedMapTraits : public Traits { |
1395 | 1390 |
typedef T ReachedMap; |
1396 | 1391 |
static ReachedMap *createReachedMap(const Digraph &digraph) { |
1397 | 1392 |
throw UninitializedParameter(); |
1398 | 1393 |
} |
1399 | 1394 |
}; |
1400 | 1395 |
/// \brief \ref named-templ-param "Named parameter" for setting |
1401 | 1396 |
/// ReachedMap type. |
1402 | 1397 |
/// |
1403 | 1398 |
/// \ref named-templ-param "Named parameter" for setting ReachedMap type. |
1404 | 1399 |
template <class T> |
1405 | 1400 |
struct SetReachedMap : public BfsVisit< Digraph, Visitor, |
1406 | 1401 |
SetReachedMapTraits<T> > { |
1407 | 1402 |
typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create; |
1408 | 1403 |
}; |
1409 | 1404 |
///@} |
1410 | 1405 |
|
1411 | 1406 |
public: |
1412 | 1407 |
|
1413 | 1408 |
/// \brief Constructor. |
1414 | 1409 |
/// |
1415 | 1410 |
/// Constructor. |
1416 | 1411 |
/// |
1417 | 1412 |
/// \param digraph The digraph the algorithm runs on. |
1418 | 1413 |
/// \param visitor The visitor object of the algorithm. |
1419 | 1414 |
BfsVisit(const Digraph& digraph, Visitor& visitor) |
1420 | 1415 |
: _digraph(&digraph), _visitor(&visitor), |
1421 | 1416 |
_reached(0), local_reached(false) {} |
1422 | 1417 |
|
1423 | 1418 |
/// \brief Destructor. |
1424 | 1419 |
~BfsVisit() { |
1425 | 1420 |
if(local_reached) delete _reached; |
1426 | 1421 |
} |
1427 | 1422 |
|
1428 | 1423 |
/// \brief Sets the map that indicates which nodes are reached. |
1429 | 1424 |
/// |
1430 | 1425 |
/// Sets the map that indicates which nodes are reached. |
1431 | 1426 |
/// If you don't use this function before calling \ref run(), |
1432 | 1427 |
/// it will allocate one. The destructor deallocates this |
1433 | 1428 |
/// automatically allocated map, of course. |
1434 | 1429 |
/// \return <tt> (*this) </tt> |
1435 | 1430 |
BfsVisit &reachedMap(ReachedMap &m) { |
1436 | 1431 |
if(local_reached) { |
1437 | 1432 |
delete _reached; |
1438 | 1433 |
local_reached = false; |
1439 | 1434 |
} |
1440 | 1435 |
_reached = &m; |
1441 | 1436 |
return *this; |
1442 | 1437 |
} |
1443 | 1438 |
|
1444 | 1439 |
public: |
1445 | 1440 |
|
1446 | 1441 |
/// \name Execution control |
1447 | 1442 |
/// The simplest way to execute the algorithm is to use |
1448 | 1443 |
/// one of the member functions called \ref lemon::BfsVisit::run() |
1449 | 1444 |
/// "run()". |
1450 | 1445 |
/// \n |
1451 | 1446 |
/// If you need more control on the execution, first you must call |
1452 | 1447 |
/// \ref lemon::BfsVisit::init() "init()", then you can add several |
1453 | 1448 |
/// source nodes with \ref lemon::BfsVisit::addSource() "addSource()". |
1454 | 1449 |
/// Finally \ref lemon::BfsVisit::start() "start()" will perform the |
1455 | 1450 |
/// actual path computation. |
1456 | 1451 |
|
1457 | 1452 |
/// @{ |
1458 | 1453 |
|
1459 | 1454 |
/// \brief Initializes the internal data structures. |
1460 | 1455 |
/// |
1461 | 1456 |
/// Initializes the internal data structures. |
1462 | 1457 |
void init() { |
1463 | 1458 |
create_maps(); |
1464 | 1459 |
_list.resize(countNodes(*_digraph)); |
1465 | 1460 |
_list_front = _list_back = -1; |
1466 | 1461 |
for (NodeIt u(*_digraph) ; u != INVALID ; ++u) { |
1467 | 1462 |
_reached->set(u, false); |
1468 | 1463 |
} |
1469 | 1464 |
} |
1470 | 1465 |
|
1471 | 1466 |
/// \brief Adds a new source node. |
1472 | 1467 |
/// |
1473 | 1468 |
/// Adds a new source node to the set of nodes to be processed. |
1474 | 1469 |
void addSource(Node s) { |
1475 | 1470 |
if(!(*_reached)[s]) { |
1476 | 1471 |
_reached->set(s,true); |
1477 | 1472 |
_visitor->start(s); |
1478 | 1473 |
_visitor->reach(s); |
1479 | 1474 |
_list[++_list_back] = s; |
1480 | 1475 |
} |
1481 | 1476 |
} |
1482 | 1477 |
|
1483 | 1478 |
/// \brief Processes the next node. |
1484 | 1479 |
/// |
1485 | 1480 |
/// Processes the next node. |
1486 | 1481 |
/// |
1487 | 1482 |
/// \return The processed node. |
1488 | 1483 |
/// |
1489 | 1484 |
/// \pre The queue must not be empty. |
1490 | 1485 |
Node processNextNode() { |
1491 | 1486 |
Node n = _list[++_list_front]; |
1492 | 1487 |
_visitor->process(n); |
1493 | 1488 |
Arc e; |
1494 | 1489 |
for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) { |
1495 | 1490 |
Node m = _digraph->target(e); |
1496 | 1491 |
if (!(*_reached)[m]) { |
1497 | 1492 |
_visitor->discover(e); |
1498 | 1493 |
_visitor->reach(m); |
1499 | 1494 |
_reached->set(m, true); |
1500 | 1495 |
_list[++_list_back] = m; |
1501 | 1496 |
} else { |
1502 | 1497 |
_visitor->examine(e); |
1503 | 1498 |
} |
1504 | 1499 |
} |
1505 | 1500 |
return n; |
1506 | 1501 |
} |
1507 | 1502 |
|
1508 | 1503 |
/// \brief Processes the next node. |
1509 | 1504 |
/// |
1510 | 1505 |
/// Processes the next node and checks if the given target node |
1511 | 1506 |
/// is reached. If the target node is reachable from the processed |
1512 | 1507 |
/// node, then the \c reach parameter will be set to \c true. |
1513 | 1508 |
/// |
1514 | 1509 |
/// \param target The target node. |
1515 | 1510 |
/// \retval reach Indicates if the target node is reached. |
1516 | 1511 |
/// It should be initially \c false. |
1517 | 1512 |
/// |
1518 | 1513 |
/// \return The processed node. |
1519 | 1514 |
/// |
1520 | 1515 |
/// \pre The queue must not be empty. |
1521 | 1516 |
Node processNextNode(Node target, bool& reach) { |
1522 | 1517 |
Node n = _list[++_list_front]; |
1523 | 1518 |
_visitor->process(n); |
1524 | 1519 |
Arc e; |
1525 | 1520 |
for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) { |
1526 | 1521 |
Node m = _digraph->target(e); |
1527 | 1522 |
if (!(*_reached)[m]) { |
1528 | 1523 |
_visitor->discover(e); |
1529 | 1524 |
_visitor->reach(m); |
1530 | 1525 |
_reached->set(m, true); |
1531 | 1526 |
_list[++_list_back] = m; |
1532 | 1527 |
reach = reach || (target == m); |
1533 | 1528 |
} else { |
1534 | 1529 |
_visitor->examine(e); |
1535 | 1530 |
} |
1536 | 1531 |
} |
1537 | 1532 |
return n; |
1538 | 1533 |
} |
1539 | 1534 |
|
1540 | 1535 |
/// \brief Processes the next node. |
1541 | 1536 |
/// |
1542 | 1537 |
/// Processes the next node and checks if at least one of reached |
1543 | 1538 |
/// nodes has \c true value in the \c nm node map. If one node |
1544 | 1539 |
/// with \c true value is reachable from the processed node, then the |
1545 | 1540 |
/// \c rnode parameter will be set to the first of such nodes. |
1546 | 1541 |
/// |
1547 | 1542 |
/// \param nm A \c bool (or convertible) node map that indicates the |
1548 | 1543 |
/// possible targets. |
1549 | 1544 |
/// \retval rnode The reached target node. |
1550 | 1545 |
/// It should be initially \c INVALID. |
1551 | 1546 |
/// |
1552 | 1547 |
/// \return The processed node. |
1553 | 1548 |
/// |
1554 | 1549 |
/// \pre The queue must not be empty. |
1555 | 1550 |
template <typename NM> |
1556 | 1551 |
Node processNextNode(const NM& nm, Node& rnode) { |
1557 | 1552 |
Node n = _list[++_list_front]; |
1558 | 1553 |
_visitor->process(n); |
1559 | 1554 |
Arc e; |
1560 | 1555 |
for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) { |
1561 | 1556 |
Node m = _digraph->target(e); |
1562 | 1557 |
if (!(*_reached)[m]) { |
1563 | 1558 |
_visitor->discover(e); |
1564 | 1559 |
_visitor->reach(m); |
1565 | 1560 |
_reached->set(m, true); |
1566 | 1561 |
_list[++_list_back] = m; |
1567 | 1562 |
if (nm[m] && rnode == INVALID) rnode = m; |
1568 | 1563 |
} else { |
1569 | 1564 |
_visitor->examine(e); |
1570 | 1565 |
} |
1571 | 1566 |
} |
1572 | 1567 |
return n; |
1573 | 1568 |
} |
1574 | 1569 |
|
1575 | 1570 |
/// \brief The next node to be processed. |
1576 | 1571 |
/// |
1577 | 1572 |
/// Returns the next node to be processed or \c INVALID if the queue |
1578 | 1573 |
/// is empty. |
1579 | 1574 |
Node nextNode() const { |
1580 | 1575 |
return _list_front != _list_back ? _list[_list_front + 1] : INVALID; |
1581 | 1576 |
} |
1582 | 1577 |
|
1583 | 1578 |
/// \brief Returns \c false if there are nodes |
1584 | 1579 |
/// to be processed. |
1585 | 1580 |
/// |
1586 | 1581 |
/// Returns \c false if there are nodes |
1587 | 1582 |
/// to be processed in the queue. |
1588 | 1583 |
bool emptyQueue() const { return _list_front == _list_back; } |
1589 | 1584 |
|
1590 | 1585 |
/// \brief Returns the number of the nodes to be processed. |
1591 | 1586 |
/// |
1592 | 1587 |
/// Returns the number of the nodes to be processed in the queue. |
1593 | 1588 |
int queueSize() const { return _list_back - _list_front; } |
1594 | 1589 |
|
1595 | 1590 |
/// \brief Executes the algorithm. |
1596 | 1591 |
/// |
1597 | 1592 |
/// Executes the algorithm. |
1598 | 1593 |
/// |
1599 | 1594 |
/// This method runs the %BFS algorithm from the root node(s) |
1600 | 1595 |
/// in order to compute the shortest path to each node. |
1601 | 1596 |
/// |
1602 | 1597 |
/// The algorithm computes |
1603 | 1598 |
/// - the shortest path tree (forest), |
1604 | 1599 |
/// - the distance of each node from the root(s). |
1605 | 1600 |
/// |
1606 | 1601 |
/// \pre init() must be called and at least one root node should be added |
1607 | 1602 |
/// with addSource() before using this function. |
1608 | 1603 |
/// |
1609 | 1604 |
/// \note <tt>b.start()</tt> is just a shortcut of the following code. |
1610 | 1605 |
/// \code |
1611 | 1606 |
/// while ( !b.emptyQueue() ) { |
1612 | 1607 |
/// b.processNextNode(); |
1613 | 1608 |
/// } |
1614 | 1609 |
/// \endcode |
1615 | 1610 |
void start() { |
1616 | 1611 |
while ( !emptyQueue() ) processNextNode(); |
1617 | 1612 |
} |
1618 | 1613 |
|
1619 | 1614 |
/// \brief Executes the algorithm until the given target node is reached. |
1620 | 1615 |
/// |
1621 | 1616 |
/// Executes the algorithm until the given target node is reached. |
1622 | 1617 |
/// |
1623 | 1618 |
/// This method runs the %BFS algorithm from the root node(s) |
1624 | 1619 |
/// in order to compute the shortest path to \c dest. |
1625 | 1620 |
/// |
1626 | 1621 |
/// The algorithm computes |
1627 | 1622 |
/// - the shortest path to \c dest, |
1628 | 1623 |
/// - the distance of \c dest from the root(s). |
1629 | 1624 |
/// |
1630 | 1625 |
/// \pre init() must be called and at least one root node should be |
1631 | 1626 |
/// added with addSource() before using this function. |
1632 | 1627 |
/// |
1633 | 1628 |
/// \note <tt>b.start(t)</tt> is just a shortcut of the following code. |
1634 | 1629 |
/// \code |
1635 | 1630 |
/// bool reach = false; |
1636 | 1631 |
/// while ( !b.emptyQueue() && !reach ) { |
1637 | 1632 |
/// b.processNextNode(t, reach); |
1638 | 1633 |
/// } |
1639 | 1634 |
/// \endcode |
1640 | 1635 |
void start(Node dest) { |
1641 | 1636 |
bool reach = false; |
1642 | 1637 |
while ( !emptyQueue() && !reach ) processNextNode(dest, reach); |
1643 | 1638 |
} |
1644 | 1639 |
|
1645 | 1640 |
/// \brief Executes the algorithm until a condition is met. |
1646 | 1641 |
/// |
1647 | 1642 |
/// Executes the algorithm until a condition is met. |
1648 | 1643 |
/// |
1649 | 1644 |
/// This method runs the %BFS algorithm from the root node(s) in |
1650 | 1645 |
/// order to compute the shortest path to a node \c v with |
1651 | 1646 |
/// <tt>nm[v]</tt> true, if such a node can be found. |
1652 | 1647 |
/// |
1653 | 1648 |
/// \param nm must be a bool (or convertible) node map. The |
1654 | 1649 |
/// algorithm will stop when it reaches a node \c v with |
1655 | 1650 |
/// <tt>nm[v]</tt> true. |
1656 | 1651 |
/// |
1657 | 1652 |
/// \return The reached node \c v with <tt>nm[v]</tt> true or |
1658 | 1653 |
/// \c INVALID if no such node was found. |
1659 | 1654 |
/// |
1660 | 1655 |
/// \pre init() must be called and at least one root node should be |
1661 | 1656 |
/// added with addSource() before using this function. |
1662 | 1657 |
/// |
1663 | 1658 |
/// \note <tt>b.start(nm)</tt> is just a shortcut of the following code. |
1664 | 1659 |
/// \code |
1665 | 1660 |
/// Node rnode = INVALID; |
1666 | 1661 |
/// while ( !b.emptyQueue() && rnode == INVALID ) { |
1667 | 1662 |
/// b.processNextNode(nm, rnode); |
1668 | 1663 |
/// } |
1669 | 1664 |
/// return rnode; |
1670 | 1665 |
/// \endcode |
1671 | 1666 |
template <typename NM> |
1672 | 1667 |
Node start(const NM &nm) { |
1673 | 1668 |
Node rnode = INVALID; |
1674 | 1669 |
while ( !emptyQueue() && rnode == INVALID ) { |
1675 | 1670 |
processNextNode(nm, rnode); |
1676 | 1671 |
} |
1677 | 1672 |
return rnode; |
1678 | 1673 |
} |
1679 | 1674 |
|
1680 | 1675 |
/// \brief Runs the algorithm from the given node. |
1681 | 1676 |
/// |
1682 | 1677 |
/// This method runs the %BFS algorithm from node \c s |
1683 | 1678 |
/// in order to compute the shortest path to each node. |
1684 | 1679 |
/// |
1685 | 1680 |
/// The algorithm computes |
1686 | 1681 |
/// - the shortest path tree, |
1687 | 1682 |
/// - the distance of each node from the root. |
1688 | 1683 |
/// |
1689 | 1684 |
/// \note <tt>b.run(s)</tt> is just a shortcut of the following code. |
1690 | 1685 |
///\code |
1691 | 1686 |
/// b.init(); |
1692 | 1687 |
/// b.addSource(s); |
1693 | 1688 |
/// b.start(); |
1694 | 1689 |
///\endcode |
1695 | 1690 |
void run(Node s) { |
1696 | 1691 |
init(); |
1697 | 1692 |
addSource(s); |
1698 | 1693 |
start(); |
1699 | 1694 |
} |
1700 | 1695 |
|
1701 | 1696 |
/// \brief Runs the algorithm to visit all nodes in the digraph. |
1702 | 1697 |
/// |
1703 | 1698 |
/// This method runs the %BFS algorithm in order to |
1704 | 1699 |
/// compute the shortest path to each node. |
1705 | 1700 |
/// |
1706 | 1701 |
/// The algorithm computes |
1707 | 1702 |
/// - the shortest path tree (forest), |
1708 | 1703 |
/// - the distance of each node from the root(s). |
1709 | 1704 |
/// |
1710 | 1705 |
/// \note <tt>b.run(s)</tt> is just a shortcut of the following code. |
1711 | 1706 |
///\code |
1712 | 1707 |
/// b.init(); |
1713 | 1708 |
/// for (NodeIt n(gr); n != INVALID; ++n) { |
1714 | 1709 |
/// if (!b.reached(n)) { |
1715 | 1710 |
/// b.addSource(n); |
1716 | 1711 |
/// b.start(); |
1717 | 1712 |
/// } |
1718 | 1713 |
/// } |
1719 | 1714 |
///\endcode |
1720 | 1715 |
void run() { |
1721 | 1716 |
init(); |
1722 | 1717 |
for (NodeIt it(*_digraph); it != INVALID; ++it) { |
1723 | 1718 |
if (!reached(it)) { |
1724 | 1719 |
addSource(it); |
1725 | 1720 |
start(); |
1726 | 1721 |
} |
1727 | 1722 |
} |
1728 | 1723 |
} |
1729 | 1724 |
|
1730 | 1725 |
///@} |
1731 | 1726 |
|
1732 | 1727 |
/// \name Query Functions |
1733 | 1728 |
/// The result of the %BFS algorithm can be obtained using these |
1734 | 1729 |
/// functions.\n |
1735 | 1730 |
/// Either \ref lemon::BfsVisit::run() "run()" or |
1736 | 1731 |
/// \ref lemon::BfsVisit::start() "start()" must be called before |
1737 | 1732 |
/// using them. |
1738 | 1733 |
///@{ |
1739 | 1734 |
|
1740 | 1735 |
/// \brief Checks if a node is reachable from the root(s). |
1741 | 1736 |
/// |
1742 | 1737 |
/// Returns \c true if \c v is reachable from the root(s). |
1743 | 1738 |
/// \pre Either \ref run() or \ref start() |
1744 | 1739 |
/// must be called before using this function. |
1745 | 1740 |
bool reached(Node v) { return (*_reached)[v]; } |
1746 | 1741 |
|
1747 | 1742 |
///@} |
1748 | 1743 |
|
1749 | 1744 |
}; |
1750 | 1745 |
|
1751 | 1746 |
} //END OF NAMESPACE LEMON |
1752 | 1747 |
|
1753 | 1748 |
#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-2008 |
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_BITS_BASE_EXTENDER_H |
20 | 20 |
#define LEMON_BITS_BASE_EXTENDER_H |
21 | 21 |
|
22 | 22 |
#include <lemon/core.h> |
23 | 23 |
#include <lemon/error.h> |
24 | 24 |
|
25 | 25 |
#include <lemon/bits/map_extender.h> |
26 | 26 |
#include <lemon/bits/default_map.h> |
27 | 27 |
|
28 | 28 |
#include <lemon/concept_check.h> |
29 | 29 |
#include <lemon/concepts/maps.h> |
30 | 30 |
|
31 | 31 |
///\ingroup digraphbits |
32 | 32 |
///\file |
33 | 33 |
///\brief Extenders for the digraph types |
34 | 34 |
namespace lemon { |
35 | 35 |
|
36 | 36 |
/// \ingroup digraphbits |
37 | 37 |
/// |
38 | 38 |
/// \brief BaseDigraph to BaseGraph extender |
39 | 39 |
template <typename Base> |
40 | 40 |
class UndirDigraphExtender : public Base { |
41 | 41 |
|
42 | 42 |
public: |
43 | 43 |
|
44 | 44 |
typedef Base Parent; |
45 | 45 |
typedef typename Parent::Arc Edge; |
46 | 46 |
typedef typename Parent::Node Node; |
47 | 47 |
|
48 | 48 |
typedef True UndirectedTag; |
49 | 49 |
|
50 | 50 |
class Arc : public Edge { |
51 | 51 |
friend class UndirDigraphExtender; |
52 | 52 |
|
53 | 53 |
protected: |
54 | 54 |
bool forward; |
55 | 55 |
|
56 | 56 |
Arc(const Edge &ue, bool _forward) : |
57 | 57 |
Edge(ue), forward(_forward) {} |
58 | 58 |
|
59 | 59 |
public: |
60 | 60 |
Arc() {} |
61 | 61 |
|
62 | 62 |
// Invalid arc constructor |
63 | 63 |
Arc(Invalid i) : Edge(i), forward(true) {} |
64 | 64 |
|
65 | 65 |
bool operator==(const Arc &that) const { |
66 | 66 |
return forward==that.forward && Edge(*this)==Edge(that); |
67 | 67 |
} |
68 | 68 |
bool operator!=(const Arc &that) const { |
69 | 69 |
return forward!=that.forward || Edge(*this)!=Edge(that); |
70 | 70 |
} |
71 | 71 |
bool operator<(const Arc &that) const { |
72 | 72 |
return forward<that.forward || |
73 | 73 |
(!(that.forward<forward) && Edge(*this)<Edge(that)); |
74 | 74 |
} |
75 | 75 |
}; |
76 | 76 |
|
77 | 77 |
/// First node of the edge |
78 | 78 |
Node u(const Edge &e) const { |
79 | 79 |
return Parent::source(e); |
80 | 80 |
} |
81 | 81 |
|
82 | 82 |
/// Source of the given arc |
83 | 83 |
Node source(const Arc &e) const { |
84 | 84 |
return e.forward ? Parent::source(e) : Parent::target(e); |
85 | 85 |
} |
86 | 86 |
|
87 | 87 |
/// Second node of the edge |
88 | 88 |
Node v(const Edge &e) const { |
89 | 89 |
return Parent::target(e); |
90 | 90 |
} |
91 | 91 |
|
92 | 92 |
/// Target of the given arc |
93 | 93 |
Node target(const Arc &e) const { |
94 | 94 |
return e.forward ? Parent::target(e) : Parent::source(e); |
95 | 95 |
} |
96 | 96 |
|
97 | 97 |
/// \brief Directed arc from an edge. |
98 | 98 |
/// |
99 | 99 |
/// Returns a directed arc corresponding to the specified edge. |
100 | 100 |
/// If the given bool is true, the first node of the given edge and |
101 | 101 |
/// the source node of the returned arc are the same. |
102 | 102 |
static Arc direct(const Edge &e, bool d) { |
103 | 103 |
return Arc(e, d); |
104 | 104 |
} |
105 | 105 |
|
106 | 106 |
/// Returns whether the given directed arc has the same orientation |
107 | 107 |
/// as the corresponding edge. |
108 |
/// |
|
109 |
/// \todo reference to the corresponding point of the undirected digraph |
|
110 |
/// concept. "What does the direction of an edge mean?" |
|
111 | 108 |
static bool direction(const Arc &a) { return a.forward; } |
112 | 109 |
|
113 | 110 |
using Parent::first; |
114 | 111 |
using Parent::next; |
115 | 112 |
|
116 | 113 |
void first(Arc &e) const { |
117 | 114 |
Parent::first(e); |
118 | 115 |
e.forward=true; |
119 | 116 |
} |
120 | 117 |
|
121 | 118 |
void next(Arc &e) const { |
122 | 119 |
if( e.forward ) { |
123 | 120 |
e.forward = false; |
124 | 121 |
} |
125 | 122 |
else { |
126 | 123 |
Parent::next(e); |
127 | 124 |
e.forward = true; |
128 | 125 |
} |
129 | 126 |
} |
130 | 127 |
|
131 | 128 |
void firstOut(Arc &e, const Node &n) const { |
132 | 129 |
Parent::firstIn(e,n); |
133 | 130 |
if( Edge(e) != INVALID ) { |
134 | 131 |
e.forward = false; |
135 | 132 |
} |
136 | 133 |
else { |
137 | 134 |
Parent::firstOut(e,n); |
138 | 135 |
e.forward = true; |
139 | 136 |
} |
140 | 137 |
} |
141 | 138 |
void nextOut(Arc &e) const { |
142 | 139 |
if( ! e.forward ) { |
143 | 140 |
Node n = Parent::target(e); |
144 | 141 |
Parent::nextIn(e); |
145 | 142 |
if( Edge(e) == INVALID ) { |
146 | 143 |
Parent::firstOut(e, n); |
147 | 144 |
e.forward = true; |
148 | 145 |
} |
149 | 146 |
} |
150 | 147 |
else { |
151 | 148 |
Parent::nextOut(e); |
152 | 149 |
} |
153 | 150 |
} |
154 | 151 |
|
155 | 152 |
void firstIn(Arc &e, const Node &n) const { |
156 | 153 |
Parent::firstOut(e,n); |
157 | 154 |
if( Edge(e) != INVALID ) { |
158 | 155 |
e.forward = false; |
159 | 156 |
} |
160 | 157 |
else { |
161 | 158 |
Parent::firstIn(e,n); |
162 | 159 |
e.forward = true; |
163 | 160 |
} |
164 | 161 |
} |
165 | 162 |
void nextIn(Arc &e) const { |
166 | 163 |
if( ! e.forward ) { |
167 | 164 |
Node n = Parent::source(e); |
168 | 165 |
Parent::nextOut(e); |
169 | 166 |
if( Edge(e) == INVALID ) { |
170 | 167 |
Parent::firstIn(e, n); |
171 | 168 |
e.forward = true; |
172 | 169 |
} |
173 | 170 |
} |
174 | 171 |
else { |
175 | 172 |
Parent::nextIn(e); |
176 | 173 |
} |
177 | 174 |
} |
178 | 175 |
|
179 | 176 |
void firstInc(Edge &e, bool &d, const Node &n) const { |
180 | 177 |
d = true; |
181 | 178 |
Parent::firstOut(e, n); |
182 | 179 |
if (e != INVALID) return; |
183 | 180 |
d = false; |
184 | 181 |
Parent::firstIn(e, n); |
185 | 182 |
} |
186 | 183 |
|
187 | 184 |
void nextInc(Edge &e, bool &d) const { |
188 | 185 |
if (d) { |
189 | 186 |
Node s = Parent::source(e); |
190 | 187 |
Parent::nextOut(e); |
191 | 188 |
if (e != INVALID) return; |
192 | 189 |
d = false; |
193 | 190 |
Parent::firstIn(e, s); |
194 | 191 |
} else { |
195 | 192 |
Parent::nextIn(e); |
196 | 193 |
} |
197 | 194 |
} |
198 | 195 |
|
199 | 196 |
Node nodeFromId(int ix) const { |
200 | 197 |
return Parent::nodeFromId(ix); |
201 | 198 |
} |
202 | 199 |
|
203 | 200 |
Arc arcFromId(int ix) const { |
204 | 201 |
return direct(Parent::arcFromId(ix >> 1), bool(ix & 1)); |
205 | 202 |
} |
206 | 203 |
|
207 | 204 |
Edge edgeFromId(int ix) const { |
208 | 205 |
return Parent::arcFromId(ix); |
209 | 206 |
} |
210 | 207 |
|
211 | 208 |
int id(const Node &n) const { |
212 | 209 |
return Parent::id(n); |
213 | 210 |
} |
214 | 211 |
|
215 | 212 |
int id(const Edge &e) const { |
216 | 213 |
return Parent::id(e); |
217 | 214 |
} |
218 | 215 |
|
219 | 216 |
int id(const Arc &e) const { |
220 | 217 |
return 2 * Parent::id(e) + int(e.forward); |
221 | 218 |
} |
222 | 219 |
|
223 | 220 |
int maxNodeId() const { |
224 | 221 |
return Parent::maxNodeId(); |
225 | 222 |
} |
226 | 223 |
|
227 | 224 |
int maxArcId() const { |
228 | 225 |
return 2 * Parent::maxArcId() + 1; |
229 | 226 |
} |
230 | 227 |
|
231 | 228 |
int maxEdgeId() const { |
232 | 229 |
return Parent::maxArcId(); |
233 | 230 |
} |
234 | 231 |
|
235 | 232 |
int arcNum() const { |
236 | 233 |
return 2 * Parent::arcNum(); |
237 | 234 |
} |
238 | 235 |
|
239 | 236 |
int edgeNum() const { |
240 | 237 |
return Parent::arcNum(); |
241 | 238 |
} |
242 | 239 |
|
243 | 240 |
Arc findArc(Node s, Node t, Arc p = INVALID) const { |
244 | 241 |
if (p == INVALID) { |
245 | 242 |
Edge arc = Parent::findArc(s, t); |
246 | 243 |
if (arc != INVALID) return direct(arc, true); |
247 | 244 |
arc = Parent::findArc(t, s); |
248 | 245 |
if (arc != INVALID) return direct(arc, false); |
249 | 246 |
} else if (direction(p)) { |
250 | 247 |
Edge arc = Parent::findArc(s, t, p); |
251 | 248 |
if (arc != INVALID) return direct(arc, true); |
252 | 249 |
arc = Parent::findArc(t, s); |
253 | 250 |
if (arc != INVALID) return direct(arc, false); |
254 | 251 |
} else { |
255 | 252 |
Edge arc = Parent::findArc(t, s, p); |
256 | 253 |
if (arc != INVALID) return direct(arc, false); |
257 | 254 |
} |
258 | 255 |
return INVALID; |
259 | 256 |
} |
260 | 257 |
|
261 | 258 |
Edge findEdge(Node s, Node t, Edge p = INVALID) const { |
262 | 259 |
if (s != t) { |
263 | 260 |
if (p == INVALID) { |
264 | 261 |
Edge arc = Parent::findArc(s, t); |
265 | 262 |
if (arc != INVALID) return arc; |
266 | 263 |
arc = Parent::findArc(t, s); |
267 | 264 |
if (arc != INVALID) return arc; |
268 | 265 |
} else if (Parent::s(p) == s) { |
269 | 266 |
Edge arc = Parent::findArc(s, t, p); |
270 | 267 |
if (arc != INVALID) return arc; |
271 | 268 |
arc = Parent::findArc(t, s); |
272 | 269 |
if (arc != INVALID) return arc; |
273 | 270 |
} else { |
274 | 271 |
Edge arc = Parent::findArc(t, s, p); |
275 | 272 |
if (arc != INVALID) return arc; |
276 | 273 |
} |
277 | 274 |
} else { |
278 | 275 |
return Parent::findArc(s, t, p); |
279 | 276 |
} |
280 | 277 |
return INVALID; |
281 | 278 |
} |
282 | 279 |
}; |
283 | 280 |
|
284 | 281 |
template <typename Base> |
285 | 282 |
class BidirBpGraphExtender : public Base { |
286 | 283 |
public: |
287 | 284 |
typedef Base Parent; |
288 | 285 |
typedef BidirBpGraphExtender Digraph; |
289 | 286 |
|
290 | 287 |
typedef typename Parent::Node Node; |
291 | 288 |
typedef typename Parent::Edge Edge; |
292 | 289 |
|
293 | 290 |
|
294 | 291 |
using Parent::first; |
295 | 292 |
using Parent::next; |
296 | 293 |
|
297 | 294 |
using Parent::id; |
298 | 295 |
|
299 | 296 |
class Red : public Node { |
300 | 297 |
friend class BidirBpGraphExtender; |
301 | 298 |
public: |
302 | 299 |
Red() {} |
303 | 300 |
Red(const Node& node) : Node(node) { |
304 | 301 |
LEMON_ASSERT(Parent::red(node) || node == INVALID, |
305 | 302 |
typename Parent::NodeSetError()); |
306 | 303 |
} |
307 | 304 |
Red& operator=(const Node& node) { |
308 | 305 |
LEMON_ASSERT(Parent::red(node) || node == INVALID, |
309 | 306 |
typename Parent::NodeSetError()); |
310 | 307 |
Node::operator=(node); |
311 | 308 |
return *this; |
312 | 309 |
} |
313 | 310 |
Red(Invalid) : Node(INVALID) {} |
314 | 311 |
Red& operator=(Invalid) { |
315 | 312 |
Node::operator=(INVALID); |
316 | 313 |
return *this; |
317 | 314 |
} |
318 | 315 |
}; |
319 | 316 |
|
320 | 317 |
void first(Red& node) const { |
321 | 318 |
Parent::firstRed(static_cast<Node&>(node)); |
322 | 319 |
} |
323 | 320 |
void next(Red& node) const { |
324 | 321 |
Parent::nextRed(static_cast<Node&>(node)); |
325 | 322 |
} |
326 | 323 |
|
327 | 324 |
int id(const Red& node) const { |
328 | 325 |
return Parent::redId(node); |
329 | 326 |
} |
330 | 327 |
|
331 | 328 |
class Blue : public Node { |
332 | 329 |
friend class BidirBpGraphExtender; |
333 | 330 |
public: |
334 | 331 |
Blue() {} |
335 | 332 |
Blue(const Node& node) : Node(node) { |
336 | 333 |
LEMON_ASSERT(Parent::blue(node) || node == INVALID, |
337 | 334 |
typename Parent::NodeSetError()); |
338 | 335 |
} |
339 | 336 |
Blue& operator=(const Node& node) { |
340 | 337 |
LEMON_ASSERT(Parent::blue(node) || node == INVALID, |
341 | 338 |
typename Parent::NodeSetError()); |
342 | 339 |
Node::operator=(node); |
343 | 340 |
return *this; |
344 | 341 |
} |
345 | 342 |
Blue(Invalid) : Node(INVALID) {} |
346 | 343 |
Blue& operator=(Invalid) { |
347 | 344 |
Node::operator=(INVALID); |
348 | 345 |
return *this; |
349 | 346 |
} |
350 | 347 |
}; |
351 | 348 |
|
352 | 349 |
void first(Blue& node) const { |
353 | 350 |
Parent::firstBlue(static_cast<Node&>(node)); |
354 | 351 |
} |
355 | 352 |
void next(Blue& node) const { |
356 | 353 |
Parent::nextBlue(static_cast<Node&>(node)); |
357 | 354 |
} |
358 | 355 |
|
359 | 356 |
int id(const Blue& node) const { |
360 | 357 |
return Parent::redId(node); |
361 | 358 |
} |
362 | 359 |
|
363 | 360 |
Node source(const Edge& arc) const { |
364 | 361 |
return red(arc); |
365 | 362 |
} |
366 | 363 |
Node target(const Edge& arc) const { |
367 | 364 |
return blue(arc); |
368 | 365 |
} |
369 | 366 |
|
370 | 367 |
void firstInc(Edge& arc, bool& dir, const Node& node) const { |
371 | 368 |
if (Parent::red(node)) { |
372 | 369 |
Parent::firstFromRed(arc, node); |
373 | 370 |
dir = true; |
374 | 371 |
} else { |
375 | 372 |
Parent::firstFromBlue(arc, node); |
376 | 373 |
dir = static_cast<Edge&>(arc) == INVALID; |
377 | 374 |
} |
378 | 375 |
} |
379 | 376 |
void nextInc(Edge& arc, bool& dir) const { |
380 | 377 |
if (dir) { |
381 | 378 |
Parent::nextFromRed(arc); |
382 | 379 |
} else { |
383 | 380 |
Parent::nextFromBlue(arc); |
384 | 381 |
if (arc == INVALID) dir = true; |
385 | 382 |
} |
386 | 383 |
} |
387 | 384 |
|
388 | 385 |
class Arc : public Edge { |
389 | 386 |
friend class BidirBpGraphExtender; |
390 | 387 |
protected: |
391 | 388 |
bool forward; |
392 | 389 |
|
393 | 390 |
Arc(const Edge& arc, bool _forward) |
394 | 391 |
: Edge(arc), forward(_forward) {} |
395 | 392 |
|
396 | 393 |
public: |
397 | 394 |
Arc() {} |
398 | 395 |
Arc (Invalid) : Edge(INVALID), forward(true) {} |
399 | 396 |
bool operator==(const Arc& i) const { |
400 | 397 |
return Edge::operator==(i) && forward == i.forward; |
401 | 398 |
} |
402 | 399 |
bool operator!=(const Arc& i) const { |
403 | 400 |
return Edge::operator!=(i) || forward != i.forward; |
404 | 401 |
} |
405 | 402 |
bool operator<(const Arc& i) const { |
406 | 403 |
return Edge::operator<(i) || |
407 | 404 |
(!(i.forward<forward) && Edge(*this)<Edge(i)); |
408 | 405 |
} |
409 | 406 |
}; |
410 | 407 |
|
411 | 408 |
void first(Arc& arc) const { |
412 | 409 |
Parent::first(static_cast<Edge&>(arc)); |
413 | 410 |
arc.forward = true; |
414 | 411 |
} |
415 | 412 |
|
416 | 413 |
void next(Arc& arc) const { |
417 | 414 |
if (!arc.forward) { |
418 | 415 |
Parent::next(static_cast<Edge&>(arc)); |
419 | 416 |
} |
420 | 417 |
arc.forward = !arc.forward; |
421 | 418 |
} |
422 | 419 |
|
423 | 420 |
void firstOut(Arc& arc, const Node& node) const { |
424 | 421 |
if (Parent::red(node)) { |
425 | 422 |
Parent::firstFromRed(arc, node); |
426 | 423 |
arc.forward = true; |
427 | 424 |
} else { |
428 | 425 |
Parent::firstFromBlue(arc, node); |
429 | 426 |
arc.forward = static_cast<Edge&>(arc) == INVALID; |
430 | 427 |
} |
431 | 428 |
} |
432 | 429 |
void nextOut(Arc& arc) const { |
433 | 430 |
if (arc.forward) { |
434 | 431 |
Parent::nextFromRed(arc); |
435 | 432 |
} else { |
436 | 433 |
Parent::nextFromBlue(arc); |
437 | 434 |
arc.forward = static_cast<Edge&>(arc) == INVALID; |
438 | 435 |
} |
439 | 436 |
} |
440 | 437 |
|
441 | 438 |
void firstIn(Arc& arc, const Node& node) const { |
442 | 439 |
if (Parent::blue(node)) { |
443 | 440 |
Parent::firstFromBlue(arc, node); |
444 | 441 |
arc.forward = true; |
445 | 442 |
} else { |
446 | 443 |
Parent::firstFromRed(arc, node); |
447 | 444 |
arc.forward = static_cast<Edge&>(arc) == INVALID; |
448 | 445 |
} |
449 | 446 |
} |
450 | 447 |
void nextIn(Arc& arc) const { |
451 | 448 |
if (arc.forward) { |
452 | 449 |
Parent::nextFromBlue(arc); |
453 | 450 |
} else { |
454 | 451 |
Parent::nextFromRed(arc); |
455 | 452 |
arc.forward = static_cast<Edge&>(arc) == INVALID; |
456 | 453 |
} |
457 | 454 |
} |
458 | 455 |
|
459 | 456 |
Node source(const Arc& arc) const { |
460 | 457 |
return arc.forward ? Parent::red(arc) : Parent::blue(arc); |
461 | 458 |
} |
462 | 459 |
Node target(const Arc& arc) const { |
463 | 460 |
return arc.forward ? Parent::blue(arc) : Parent::red(arc); |
464 | 461 |
} |
465 | 462 |
|
466 | 463 |
int id(const Arc& arc) const { |
467 | 464 |
return (Parent::id(static_cast<const Edge&>(arc)) << 1) + |
468 | 465 |
(arc.forward ? 0 : 1); |
469 | 466 |
} |
470 | 467 |
Arc arcFromId(int ix) const { |
471 | 468 |
return Arc(Parent::fromEdgeId(ix >> 1), (ix & 1) == 0); |
472 | 469 |
} |
473 | 470 |
int maxArcId() const { |
474 | 471 |
return (Parent::maxEdgeId() << 1) + 1; |
475 | 472 |
} |
476 | 473 |
|
477 | 474 |
bool direction(const Arc& arc) const { |
478 | 475 |
return arc.forward; |
479 | 476 |
} |
480 | 477 |
|
481 | 478 |
Arc direct(const Edge& arc, bool dir) const { |
482 | 479 |
return Arc(arc, dir); |
483 | 480 |
} |
484 | 481 |
|
485 | 482 |
int arcNum() const { |
486 | 483 |
return 2 * Parent::edgeNum(); |
487 | 484 |
} |
488 | 485 |
|
489 | 486 |
int edgeNum() const { |
490 | 487 |
return Parent::edgeNum(); |
491 | 488 |
} |
492 | 489 |
|
493 | 490 |
|
494 | 491 |
}; |
495 | 492 |
} |
496 | 493 |
|
497 | 494 |
#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-2008 |
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_BITS_VECTOR_MAP_H |
20 | 20 |
#define LEMON_BITS_VECTOR_MAP_H |
21 | 21 |
|
22 | 22 |
#include <vector> |
23 | 23 |
#include <algorithm> |
24 | 24 |
|
25 | 25 |
#include <lemon/core.h> |
26 | 26 |
#include <lemon/bits/alteration_notifier.h> |
27 | 27 |
|
28 | 28 |
#include <lemon/concept_check.h> |
29 | 29 |
#include <lemon/concepts/maps.h> |
30 | 30 |
|
31 | 31 |
///\ingroup graphbits |
32 | 32 |
/// |
33 | 33 |
///\file |
34 | 34 |
///\brief Vector based graph maps. |
35 | 35 |
namespace lemon { |
36 | 36 |
|
37 | 37 |
/// \ingroup graphbits |
38 | 38 |
/// |
39 | 39 |
/// \brief Graph map based on the std::vector storage. |
40 | 40 |
/// |
41 | 41 |
/// The VectorMap template class is graph map structure what |
42 | 42 |
/// automatically updates the map when a key is added to or erased from |
43 | 43 |
/// the map. This map type uses the std::vector to store the values. |
44 | 44 |
/// |
45 |
/// \tparam |
|
45 |
/// \tparam _Graph The graph this map is attached to. |
|
46 | 46 |
/// \tparam _Item The item type of the graph items. |
47 | 47 |
/// \tparam _Value The value type of the map. |
48 |
/// \todo Fix the doc: there is _Graph parameter instead of _Notifier. |
|
49 | 48 |
template <typename _Graph, typename _Item, typename _Value> |
50 | 49 |
class VectorMap |
51 | 50 |
: public ItemSetTraits<_Graph, _Item>::ItemNotifier::ObserverBase { |
52 | 51 |
private: |
53 | 52 |
|
54 | 53 |
/// The container type of the map. |
55 | 54 |
typedef std::vector<_Value> Container; |
56 | 55 |
|
57 | 56 |
public: |
58 | 57 |
|
59 | 58 |
/// The graph type of the map. |
60 | 59 |
typedef _Graph Graph; |
61 | 60 |
/// The item type of the map. |
62 | 61 |
typedef _Item Item; |
63 | 62 |
/// The reference map tag. |
64 | 63 |
typedef True ReferenceMapTag; |
65 | 64 |
|
66 | 65 |
/// The key type of the map. |
67 | 66 |
typedef _Item Key; |
68 | 67 |
/// The value type of the map. |
69 | 68 |
typedef _Value Value; |
70 | 69 |
|
71 | 70 |
/// The notifier type. |
72 | 71 |
typedef typename ItemSetTraits<_Graph, _Item>::ItemNotifier Notifier; |
73 | 72 |
|
74 | 73 |
/// The map type. |
75 | 74 |
typedef VectorMap Map; |
76 | 75 |
/// The base class of the map. |
77 | 76 |
typedef typename Notifier::ObserverBase Parent; |
78 | 77 |
|
79 | 78 |
/// The reference type of the map; |
80 | 79 |
typedef typename Container::reference Reference; |
81 | 80 |
/// The const reference type of the map; |
82 | 81 |
typedef typename Container::const_reference ConstReference; |
83 | 82 |
|
84 | 83 |
|
85 | 84 |
/// \brief Constructor to attach the new map into the notifier. |
86 | 85 |
/// |
87 | 86 |
/// It constructs a map and attachs it into the notifier. |
88 | 87 |
/// It adds all the items of the graph to the map. |
89 | 88 |
VectorMap(const Graph& graph) { |
90 | 89 |
Parent::attach(graph.notifier(Item())); |
91 | 90 |
container.resize(Parent::notifier()->maxId() + 1); |
92 | 91 |
} |
93 | 92 |
|
94 | 93 |
/// \brief Constructor uses given value to initialize the map. |
95 | 94 |
/// |
96 | 95 |
/// It constructs a map uses a given value to initialize the map. |
97 | 96 |
/// It adds all the items of the graph to the map. |
98 | 97 |
VectorMap(const Graph& graph, const Value& value) { |
99 | 98 |
Parent::attach(graph.notifier(Item())); |
100 | 99 |
container.resize(Parent::notifier()->maxId() + 1, value); |
101 | 100 |
} |
102 | 101 |
|
103 | 102 |
private: |
104 | 103 |
/// \brief Copy constructor |
105 | 104 |
/// |
106 | 105 |
/// Copy constructor. |
107 | 106 |
VectorMap(const VectorMap& _copy) : Parent() { |
108 | 107 |
if (_copy.attached()) { |
109 | 108 |
Parent::attach(*_copy.notifier()); |
110 | 109 |
container = _copy.container; |
111 | 110 |
} |
112 | 111 |
} |
113 | 112 |
|
114 | 113 |
/// \brief Assign operator. |
115 | 114 |
/// |
116 | 115 |
/// This operator assigns for each item in the map the |
117 | 116 |
/// value mapped to the same item in the copied map. |
118 | 117 |
/// The parameter map should be indiced with the same |
119 | 118 |
/// itemset because this assign operator does not change |
120 | 119 |
/// the container of the map. |
121 | 120 |
VectorMap& operator=(const VectorMap& cmap) { |
122 | 121 |
return operator=<VectorMap>(cmap); |
123 | 122 |
} |
124 | 123 |
|
125 | 124 |
|
126 | 125 |
/// \brief Template assign operator. |
127 | 126 |
/// |
128 | 127 |
/// The given parameter should be conform to the ReadMap |
129 | 128 |
/// concecpt and could be indiced by the current item set of |
130 | 129 |
/// the NodeMap. In this case the value for each item |
131 | 130 |
/// is assigned by the value of the given ReadMap. |
132 | 131 |
template <typename CMap> |
133 | 132 |
VectorMap& operator=(const CMap& cmap) { |
134 | 133 |
checkConcept<concepts::ReadMap<Key, _Value>, CMap>(); |
135 | 134 |
const typename Parent::Notifier* nf = Parent::notifier(); |
136 | 135 |
Item it; |
137 | 136 |
for (nf->first(it); it != INVALID; nf->next(it)) { |
138 | 137 |
set(it, cmap[it]); |
139 | 138 |
} |
140 | 139 |
return *this; |
141 | 140 |
} |
142 | 141 |
|
143 | 142 |
public: |
144 | 143 |
|
145 | 144 |
/// \brief The subcript operator. |
146 | 145 |
/// |
147 | 146 |
/// The subscript operator. The map can be subscripted by the |
148 | 147 |
/// actual items of the graph. |
149 | 148 |
Reference operator[](const Key& key) { |
150 | 149 |
return container[Parent::notifier()->id(key)]; |
151 | 150 |
} |
152 | 151 |
|
153 | 152 |
/// \brief The const subcript operator. |
154 | 153 |
/// |
155 | 154 |
/// The const subscript operator. The map can be subscripted by the |
156 | 155 |
/// actual items of the graph. |
157 | 156 |
ConstReference operator[](const Key& key) const { |
158 | 157 |
return container[Parent::notifier()->id(key)]; |
159 | 158 |
} |
160 | 159 |
|
161 | 160 |
|
162 | 161 |
/// \brief The setter function of the map. |
163 | 162 |
/// |
164 | 163 |
/// It the same as operator[](key) = value expression. |
165 | 164 |
void set(const Key& key, const Value& value) { |
166 | 165 |
(*this)[key] = value; |
167 | 166 |
} |
168 | 167 |
|
169 | 168 |
protected: |
170 | 169 |
|
171 | 170 |
/// \brief Adds a new key to the map. |
172 | 171 |
/// |
173 | 172 |
/// It adds a new key to the map. It called by the observer notifier |
174 | 173 |
/// and it overrides the add() member function of the observer base. |
175 | 174 |
virtual void add(const Key& key) { |
176 | 175 |
int id = Parent::notifier()->id(key); |
177 | 176 |
if (id >= int(container.size())) { |
178 | 177 |
container.resize(id + 1); |
179 | 178 |
} |
180 | 179 |
} |
181 | 180 |
|
182 | 181 |
/// \brief Adds more new keys to the map. |
183 | 182 |
/// |
184 | 183 |
/// It adds more new keys to the map. It called by the observer notifier |
185 | 184 |
/// and it overrides the add() member function of the observer base. |
186 | 185 |
virtual void add(const std::vector<Key>& keys) { |
187 | 186 |
int max = container.size() - 1; |
188 | 187 |
for (int i = 0; i < int(keys.size()); ++i) { |
189 | 188 |
int id = Parent::notifier()->id(keys[i]); |
190 | 189 |
if (id >= max) { |
191 | 190 |
max = id; |
192 | 191 |
} |
193 | 192 |
} |
194 | 193 |
container.resize(max + 1); |
195 | 194 |
} |
196 | 195 |
|
197 | 196 |
/// \brief Erase a key from the map. |
198 | 197 |
/// |
199 | 198 |
/// Erase a key from the map. It called by the observer notifier |
200 | 199 |
/// and it overrides the erase() member function of the observer base. |
201 | 200 |
virtual void erase(const Key& key) { |
202 | 201 |
container[Parent::notifier()->id(key)] = Value(); |
203 | 202 |
} |
204 | 203 |
|
205 | 204 |
/// \brief Erase more keys from the map. |
206 | 205 |
/// |
207 | 206 |
/// Erase more keys from the map. It called by the observer notifier |
208 | 207 |
/// and it overrides the erase() member function of the observer base. |
209 | 208 |
virtual void erase(const std::vector<Key>& keys) { |
210 | 209 |
for (int i = 0; i < int(keys.size()); ++i) { |
211 | 210 |
container[Parent::notifier()->id(keys[i])] = Value(); |
212 | 211 |
} |
213 | 212 |
} |
214 | 213 |
|
215 | 214 |
/// \brief Buildes the map. |
216 | 215 |
/// |
217 | 216 |
/// It buildes the map. It called by the observer notifier |
218 | 217 |
/// and it overrides the build() member function of the observer base. |
219 | 218 |
virtual void build() { |
220 | 219 |
int size = Parent::notifier()->maxId() + 1; |
221 | 220 |
container.reserve(size); |
222 | 221 |
container.resize(size); |
223 | 222 |
} |
224 | 223 |
|
225 | 224 |
/// \brief Clear the map. |
226 | 225 |
/// |
227 | 226 |
/// It erase all items from the map. It called by the observer notifier |
228 | 227 |
/// and it overrides the clear() member function of the observer base. |
229 | 228 |
virtual void clear() { |
230 | 229 |
container.clear(); |
231 | 230 |
} |
232 | 231 |
|
233 | 232 |
private: |
234 | 233 |
|
235 | 234 |
Container container; |
236 | 235 |
|
237 | 236 |
}; |
238 | 237 |
|
239 | 238 |
} |
240 | 239 |
|
241 | 240 |
#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-2008 |
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 |
// This file contains a modified version of the concept checking |
20 | 20 |
// utility from BOOST. |
21 | 21 |
// See the appropriate copyright notice below. |
22 | 22 |
|
23 | 23 |
// (C) Copyright Jeremy Siek 2000. |
24 | 24 |
// Distributed under the Boost Software License, Version 1.0. (See |
25 | 25 |
// accompanying file LICENSE_1_0.txt or copy at |
26 | 26 |
// http://www.boost.org/LICENSE_1_0.txt) |
27 | 27 |
// |
28 | 28 |
// Revision History: |
29 | 29 |
// 05 May 2001: Workarounds for HP aCC from Thomas Matelich. (Jeremy Siek) |
30 | 30 |
// 02 April 2001: Removed limits header altogether. (Jeremy Siek) |
31 | 31 |
// 01 April 2001: Modified to use new <boost/limits.hpp> header. (JMaddock) |
32 | 32 |
// |
33 | 33 |
|
34 | 34 |
// See http://www.boost.org/libs/concept_check for documentation. |
35 | 35 |
|
36 | 36 |
///\file |
37 | 37 |
///\brief Basic utilities for concept checking. |
38 | 38 |
/// |
39 |
///\todo Are we still using BOOST concept checking utility? |
|
40 |
///Is the BOOST copyright notice necessary? |
|
41 | 39 |
|
42 | 40 |
#ifndef LEMON_CONCEPT_CHECK_H |
43 | 41 |
#define LEMON_CONCEPT_CHECK_H |
44 | 42 |
|
45 | 43 |
namespace lemon { |
46 | 44 |
|
47 | 45 |
/* |
48 | 46 |
"inline" is used for ignore_unused_variable_warning() |
49 | 47 |
and function_requires() to make sure there is no |
50 | 48 |
overtarget with g++. |
51 | 49 |
*/ |
52 | 50 |
|
53 | 51 |
template <class T> inline void ignore_unused_variable_warning(const T&) { } |
54 | 52 |
|
55 | 53 |
///\e |
56 | 54 |
template <class Concept> |
57 | 55 |
inline void function_requires() |
58 | 56 |
{ |
59 | 57 |
#if !defined(NDEBUG) |
60 | 58 |
void (Concept::*x)() = & Concept::constraints; |
61 | 59 |
ignore_unused_variable_warning(x); |
62 | 60 |
#endif |
63 | 61 |
} |
64 | 62 |
|
65 | 63 |
///\e |
66 | 64 |
template <typename Concept, typename Type> |
67 | 65 |
inline void checkConcept() { |
68 | 66 |
#if !defined(NDEBUG) |
69 | 67 |
typedef typename Concept::template Constraints<Type> ConceptCheck; |
70 | 68 |
void (ConceptCheck::*x)() = & ConceptCheck::constraints; |
71 | 69 |
ignore_unused_variable_warning(x); |
72 | 70 |
#endif |
73 | 71 |
} |
74 | 72 |
|
75 | 73 |
} // namespace lemon |
76 | 74 |
|
77 | 75 |
#endif // LEMON_CONCEPT_CHECK_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-2008 |
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 |
///\ingroup concept |
20 | 20 |
///\file |
21 | 21 |
///\brief Classes for representing paths in digraphs. |
22 | 22 |
/// |
23 |
///\todo Iterators have obsolete style |
|
24 | 23 |
|
25 | 24 |
#ifndef LEMON_CONCEPT_PATH_H |
26 | 25 |
#define LEMON_CONCEPT_PATH_H |
27 | 26 |
|
28 | 27 |
#include <lemon/core.h> |
29 | 28 |
#include <lemon/concept_check.h> |
30 | 29 |
|
31 | 30 |
namespace lemon { |
32 | 31 |
namespace concepts { |
33 | 32 |
|
34 | 33 |
/// \addtogroup concept |
35 | 34 |
/// @{ |
36 | 35 |
|
37 | 36 |
/// \brief A skeleton structure for representing directed paths in |
38 | 37 |
/// a digraph. |
39 | 38 |
/// |
40 | 39 |
/// A skeleton structure for representing directed paths in a |
41 | 40 |
/// digraph. |
42 | 41 |
/// \tparam _Digraph The digraph type in which the path is. |
43 | 42 |
/// |
44 | 43 |
/// In a sense, the path can be treated as a list of arcs. The |
45 | 44 |
/// lemon path type stores just this list. As a consequence it |
46 | 45 |
/// cannot enumerate the nodes in the path and the zero length |
47 | 46 |
/// paths cannot store the source. |
48 | 47 |
/// |
49 | 48 |
template <typename _Digraph> |
50 | 49 |
class Path { |
51 | 50 |
public: |
52 | 51 |
|
53 | 52 |
/// Type of the underlying digraph. |
54 | 53 |
typedef _Digraph Digraph; |
55 | 54 |
/// Arc type of the underlying digraph. |
56 | 55 |
typedef typename Digraph::Arc Arc; |
57 | 56 |
|
58 | 57 |
class ArcIt; |
59 | 58 |
|
60 | 59 |
/// \brief Default constructor |
61 | 60 |
Path() {} |
62 | 61 |
|
63 | 62 |
/// \brief Template constructor |
64 | 63 |
template <typename CPath> |
65 | 64 |
Path(const CPath& cpath) {} |
66 | 65 |
|
67 | 66 |
/// \brief Template assigment |
68 | 67 |
template <typename CPath> |
69 | 68 |
Path& operator=(const CPath& cpath) { |
70 | 69 |
ignore_unused_variable_warning(cpath); |
71 | 70 |
return *this; |
72 | 71 |
} |
73 | 72 |
|
74 | 73 |
/// Length of the path ie. the number of arcs in the path. |
75 | 74 |
int length() const { return 0;} |
76 | 75 |
|
77 | 76 |
/// Returns whether the path is empty. |
78 | 77 |
bool empty() const { return true;} |
79 | 78 |
|
80 | 79 |
/// Resets the path to an empty path. |
81 | 80 |
void clear() {} |
82 | 81 |
|
83 | 82 |
/// \brief LEMON style iterator for path arcs |
84 | 83 |
/// |
85 | 84 |
/// This class is used to iterate on the arcs of the paths. |
86 | 85 |
class ArcIt { |
87 | 86 |
public: |
88 | 87 |
/// Default constructor |
89 | 88 |
ArcIt() {} |
90 | 89 |
/// Invalid constructor |
91 | 90 |
ArcIt(Invalid) {} |
92 | 91 |
/// Constructor for first arc |
93 | 92 |
ArcIt(const Path &) {} |
94 | 93 |
|
95 | 94 |
/// Conversion to Arc |
96 | 95 |
operator Arc() const { return INVALID; } |
97 | 96 |
|
98 | 97 |
/// Next arc |
99 | 98 |
ArcIt& operator++() {return *this;} |
100 | 99 |
|
101 | 100 |
/// Comparison operator |
102 | 101 |
bool operator==(const ArcIt&) const {return true;} |
103 | 102 |
/// Comparison operator |
104 | 103 |
bool operator!=(const ArcIt&) const {return true;} |
105 | 104 |
/// Comparison operator |
106 | 105 |
bool operator<(const ArcIt&) const {return false;} |
107 | 106 |
|
108 | 107 |
}; |
109 | 108 |
|
110 | 109 |
template <typename _Path> |
111 | 110 |
struct Constraints { |
112 | 111 |
void constraints() { |
113 | 112 |
Path<Digraph> pc; |
114 | 113 |
_Path p, pp(pc); |
115 | 114 |
int l = p.length(); |
116 | 115 |
int e = p.empty(); |
117 | 116 |
p.clear(); |
118 | 117 |
|
119 | 118 |
p = pc; |
120 | 119 |
|
121 | 120 |
typename _Path::ArcIt id, ii(INVALID), i(p); |
122 | 121 |
|
123 | 122 |
++i; |
124 | 123 |
typename Digraph::Arc ed = i; |
125 | 124 |
|
126 | 125 |
e = (i == ii); |
127 | 126 |
e = (i != ii); |
128 | 127 |
e = (i < ii); |
129 | 128 |
|
130 | 129 |
ignore_unused_variable_warning(l); |
131 | 130 |
ignore_unused_variable_warning(pp); |
132 | 131 |
ignore_unused_variable_warning(e); |
133 | 132 |
ignore_unused_variable_warning(id); |
134 | 133 |
ignore_unused_variable_warning(ii); |
135 | 134 |
ignore_unused_variable_warning(ed); |
136 | 135 |
} |
137 | 136 |
}; |
138 | 137 |
|
139 | 138 |
}; |
140 | 139 |
|
141 | 140 |
namespace _path_bits { |
142 | 141 |
|
143 | 142 |
template <typename _Digraph, typename _Path, typename RevPathTag = void> |
144 | 143 |
struct PathDumperConstraints { |
145 | 144 |
void constraints() { |
146 | 145 |
int l = p.length(); |
147 | 146 |
int e = p.empty(); |
148 | 147 |
|
149 | 148 |
typename _Path::ArcIt id, i(p); |
150 | 149 |
|
151 | 150 |
++i; |
152 | 151 |
typename _Digraph::Arc ed = i; |
153 | 152 |
|
154 | 153 |
e = (i == INVALID); |
155 | 154 |
e = (i != INVALID); |
156 | 155 |
|
157 | 156 |
ignore_unused_variable_warning(l); |
158 | 157 |
ignore_unused_variable_warning(e); |
159 | 158 |
ignore_unused_variable_warning(id); |
160 | 159 |
ignore_unused_variable_warning(ed); |
161 | 160 |
} |
162 | 161 |
_Path& p; |
163 | 162 |
}; |
164 | 163 |
|
165 | 164 |
template <typename _Digraph, typename _Path> |
166 | 165 |
struct PathDumperConstraints< |
167 | 166 |
_Digraph, _Path, |
168 | 167 |
typename enable_if<typename _Path::RevPathTag, void>::type |
169 | 168 |
> { |
170 | 169 |
void constraints() { |
171 | 170 |
int l = p.length(); |
172 | 171 |
int e = p.empty(); |
173 | 172 |
|
174 | 173 |
typename _Path::RevArcIt id, i(p); |
175 | 174 |
|
176 | 175 |
++i; |
177 | 176 |
typename _Digraph::Arc ed = i; |
178 | 177 |
|
179 | 178 |
e = (i == INVALID); |
180 | 179 |
e = (i != INVALID); |
181 | 180 |
|
182 | 181 |
ignore_unused_variable_warning(l); |
183 | 182 |
ignore_unused_variable_warning(e); |
184 | 183 |
ignore_unused_variable_warning(id); |
185 | 184 |
ignore_unused_variable_warning(ed); |
186 | 185 |
} |
187 | 186 |
_Path& p; |
188 | 187 |
}; |
189 | 188 |
|
190 | 189 |
} |
191 | 190 |
|
192 | 191 |
|
193 | 192 |
/// \brief A skeleton structure for path dumpers. |
194 | 193 |
/// |
195 | 194 |
/// A skeleton structure for path dumpers. The path dumpers are |
196 | 195 |
/// the generalization of the paths. The path dumpers can |
197 | 196 |
/// enumerate the arcs of the path wheter in forward or in |
198 | 197 |
/// backward order. In most time these classes are not used |
199 | 198 |
/// directly rather it used to assign a dumped class to a real |
200 | 199 |
/// path type. |
201 | 200 |
/// |
202 | 201 |
/// The main purpose of this concept is that the shortest path |
203 | 202 |
/// algorithms can enumerate easily the arcs in reverse order. |
204 | 203 |
/// If we would like to give back a real path from these |
205 | 204 |
/// algorithms then we should create a temporarly path object. In |
206 | 205 |
/// LEMON such algorithms gives back a path dumper what can |
207 | 206 |
/// assigned to a real path and the dumpers can be implemented as |
208 | 207 |
/// an adaptor class to the predecessor map. |
209 | 208 |
|
210 | 209 |
/// \tparam _Digraph The digraph type in which the path is. |
211 | 210 |
/// |
212 | 211 |
/// The paths can be constructed from any path type by a |
213 | 212 |
/// template constructor or a template assignment operator. |
214 | 213 |
/// |
215 | 214 |
template <typename _Digraph> |
216 | 215 |
class PathDumper { |
217 | 216 |
public: |
218 | 217 |
|
219 | 218 |
/// Type of the underlying digraph. |
220 | 219 |
typedef _Digraph Digraph; |
221 | 220 |
/// Arc type of the underlying digraph. |
222 | 221 |
typedef typename Digraph::Arc Arc; |
223 | 222 |
|
224 | 223 |
/// Length of the path ie. the number of arcs in the path. |
225 | 224 |
int length() const { return 0;} |
226 | 225 |
|
227 | 226 |
/// Returns whether the path is empty. |
228 | 227 |
bool empty() const { return true;} |
229 | 228 |
|
230 | 229 |
/// \brief Forward or reverse dumping |
231 | 230 |
/// |
232 | 231 |
/// If the RevPathTag is defined and true then reverse dumping |
233 | 232 |
/// is provided in the path dumper. In this case instead of the |
234 | 233 |
/// ArcIt the RevArcIt iterator should be implemented in the |
235 | 234 |
/// dumper. |
236 | 235 |
typedef False RevPathTag; |
237 | 236 |
|
238 | 237 |
/// \brief LEMON style iterator for path arcs |
239 | 238 |
/// |
240 | 239 |
/// This class is used to iterate on the arcs of the paths. |
241 | 240 |
class ArcIt { |
242 | 241 |
public: |
243 | 242 |
/// Default constructor |
244 | 243 |
ArcIt() {} |
245 | 244 |
/// Invalid constructor |
246 | 245 |
ArcIt(Invalid) {} |
247 | 246 |
/// Constructor for first arc |
248 | 247 |
ArcIt(const PathDumper&) {} |
249 | 248 |
|
250 | 249 |
/// Conversion to Arc |
251 | 250 |
operator Arc() const { return INVALID; } |
252 | 251 |
|
253 | 252 |
/// Next arc |
254 | 253 |
ArcIt& operator++() {return *this;} |
255 | 254 |
|
256 | 255 |
/// Comparison operator |
257 | 256 |
bool operator==(const ArcIt&) const {return true;} |
258 | 257 |
/// Comparison operator |
259 | 258 |
bool operator!=(const ArcIt&) const {return true;} |
260 | 259 |
/// Comparison operator |
261 | 260 |
bool operator<(const ArcIt&) const {return false;} |
262 | 261 |
|
263 | 262 |
}; |
264 | 263 |
|
265 | 264 |
/// \brief LEMON style iterator for path arcs |
266 | 265 |
/// |
267 | 266 |
/// This class is used to iterate on the arcs of the paths in |
268 | 267 |
/// reverse direction. |
269 | 268 |
class RevArcIt { |
270 | 269 |
public: |
271 | 270 |
/// Default constructor |
272 | 271 |
RevArcIt() {} |
273 | 272 |
/// Invalid constructor |
274 | 273 |
RevArcIt(Invalid) {} |
275 | 274 |
/// Constructor for first arc |
276 | 275 |
RevArcIt(const PathDumper &) {} |
277 | 276 |
|
278 | 277 |
/// Conversion to Arc |
279 | 278 |
operator Arc() const { return INVALID; } |
280 | 279 |
|
281 | 280 |
/// Next arc |
282 | 281 |
RevArcIt& operator++() {return *this;} |
283 | 282 |
|
284 | 283 |
/// Comparison operator |
285 | 284 |
bool operator==(const RevArcIt&) const {return true;} |
286 | 285 |
/// Comparison operator |
287 | 286 |
bool operator!=(const RevArcIt&) const {return true;} |
288 | 287 |
/// Comparison operator |
289 | 288 |
bool operator<(const RevArcIt&) const {return false;} |
290 | 289 |
|
291 | 290 |
}; |
292 | 291 |
|
293 | 292 |
template <typename _Path> |
294 | 293 |
struct Constraints { |
295 | 294 |
void constraints() { |
296 | 295 |
function_requires<_path_bits:: |
297 | 296 |
PathDumperConstraints<Digraph, _Path> >(); |
298 | 297 |
} |
299 | 298 |
}; |
300 | 299 |
|
301 | 300 |
}; |
302 | 301 |
|
303 | 302 |
|
304 | 303 |
///@} |
305 | 304 |
} |
306 | 305 |
|
307 | 306 |
} // namespace lemon |
308 | 307 |
|
309 | 308 |
#endif // LEMON_CONCEPT_PATH_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-2008 |
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_DFS_H |
20 | 20 |
#define LEMON_DFS_H |
21 | 21 |
|
22 | 22 |
///\ingroup search |
23 | 23 |
///\file |
24 | 24 |
///\brief DFS algorithm. |
25 | 25 |
|
26 | 26 |
#include <lemon/list_graph.h> |
27 | 27 |
#include <lemon/bits/path_dump.h> |
28 | 28 |
#include <lemon/core.h> |
29 | 29 |
#include <lemon/error.h> |
30 | 30 |
#include <lemon/assert.h> |
31 | 31 |
#include <lemon/maps.h> |
32 | 32 |
#include <lemon/path.h> |
33 | 33 |
|
34 | 34 |
namespace lemon { |
35 | 35 |
|
36 | 36 |
///Default traits class of Dfs class. |
37 | 37 |
|
38 | 38 |
///Default traits class of Dfs class. |
39 | 39 |
///\tparam GR Digraph type. |
40 | 40 |
template<class GR> |
41 | 41 |
struct DfsDefaultTraits |
42 | 42 |
{ |
43 | 43 |
///The type of the digraph the algorithm runs on. |
44 | 44 |
typedef GR Digraph; |
45 | 45 |
|
46 | 46 |
///\brief The type of the map that stores the predecessor |
47 | 47 |
///arcs of the %DFS paths. |
48 | 48 |
/// |
49 | 49 |
///The type of the map that stores the predecessor |
50 | 50 |
///arcs of the %DFS paths. |
51 | 51 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
52 | 52 |
typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap; |
53 | 53 |
///Instantiates a \ref PredMap. |
54 | 54 |
|
55 | 55 |
///This function instantiates a \ref PredMap. |
56 | 56 |
///\param g is the digraph, to which we would like to define the |
57 | 57 |
///\ref PredMap. |
58 |
///\todo The digraph alone may be insufficient to initialize |
|
59 | 58 |
static PredMap *createPredMap(const Digraph &g) |
60 | 59 |
{ |
61 | 60 |
return new PredMap(g); |
62 | 61 |
} |
63 | 62 |
|
64 | 63 |
///The type of the map that indicates which nodes are processed. |
65 | 64 |
|
66 | 65 |
///The type of the map that indicates which nodes are processed. |
67 | 66 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
68 |
///By default it is a NullMap. |
|
69 | 67 |
typedef NullMap<typename Digraph::Node,bool> ProcessedMap; |
70 | 68 |
///Instantiates a \ref ProcessedMap. |
71 | 69 |
|
72 | 70 |
///This function instantiates a \ref ProcessedMap. |
73 | 71 |
///\param g is the digraph, to which |
74 | 72 |
///we would like to define the \ref ProcessedMap |
75 | 73 |
#ifdef DOXYGEN |
76 | 74 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
77 | 75 |
#else |
78 | 76 |
static ProcessedMap *createProcessedMap(const Digraph &) |
79 | 77 |
#endif |
80 | 78 |
{ |
81 | 79 |
return new ProcessedMap(); |
82 | 80 |
} |
83 | 81 |
|
84 | 82 |
///The type of the map that indicates which nodes are reached. |
85 | 83 |
|
86 | 84 |
///The type of the map that indicates which nodes are reached. |
87 | 85 |
///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept. |
88 | 86 |
typedef typename Digraph::template NodeMap<bool> ReachedMap; |
89 | 87 |
///Instantiates a \ref ReachedMap. |
90 | 88 |
|
91 | 89 |
///This function instantiates a \ref ReachedMap. |
92 | 90 |
///\param g is the digraph, to which |
93 | 91 |
///we would like to define the \ref ReachedMap. |
94 | 92 |
static ReachedMap *createReachedMap(const Digraph &g) |
95 | 93 |
{ |
96 | 94 |
return new ReachedMap(g); |
97 | 95 |
} |
98 | 96 |
|
99 | 97 |
///The type of the map that stores the distances of the nodes. |
100 | 98 |
|
101 | 99 |
///The type of the map that stores the distances of the nodes. |
102 | 100 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
103 | 101 |
typedef typename Digraph::template NodeMap<int> DistMap; |
104 | 102 |
///Instantiates a \ref DistMap. |
105 | 103 |
|
106 | 104 |
///This function instantiates a \ref DistMap. |
107 | 105 |
///\param g is the digraph, to which we would like to define the |
108 | 106 |
///\ref DistMap. |
109 | 107 |
static DistMap *createDistMap(const Digraph &g) |
110 | 108 |
{ |
111 | 109 |
return new DistMap(g); |
112 | 110 |
} |
113 | 111 |
}; |
114 | 112 |
|
115 | 113 |
///%DFS algorithm class. |
116 | 114 |
|
117 | 115 |
///\ingroup search |
118 | 116 |
///This class provides an efficient implementation of the %DFS algorithm. |
119 | 117 |
/// |
120 | 118 |
///There is also a \ref dfs() "function-type interface" for the DFS |
121 | 119 |
///algorithm, which is convenient in the simplier cases and it can be |
122 | 120 |
///used easier. |
123 | 121 |
/// |
124 | 122 |
///\tparam GR The type of the digraph the algorithm runs on. |
125 | 123 |
///The default value is \ref ListDigraph. The value of GR is not used |
126 | 124 |
///directly by \ref Dfs, it is only passed to \ref DfsDefaultTraits. |
127 | 125 |
///\tparam TR Traits class to set various data types used by the algorithm. |
128 | 126 |
///The default traits class is |
129 | 127 |
///\ref DfsDefaultTraits "DfsDefaultTraits<GR>". |
130 | 128 |
///See \ref DfsDefaultTraits for the documentation of |
131 | 129 |
///a Dfs traits class. |
132 | 130 |
#ifdef DOXYGEN |
133 | 131 |
template <typename GR, |
134 | 132 |
typename TR> |
135 | 133 |
#else |
136 | 134 |
template <typename GR=ListDigraph, |
137 | 135 |
typename TR=DfsDefaultTraits<GR> > |
138 | 136 |
#endif |
139 | 137 |
class Dfs { |
140 | 138 |
public: |
141 | 139 |
///\ref Exception for uninitialized parameters. |
142 | 140 |
|
143 | 141 |
///This error represents problems in the initialization of the |
144 | 142 |
///parameters of the algorithm. |
145 | 143 |
class UninitializedParameter : public lemon::UninitializedParameter { |
146 | 144 |
public: |
147 | 145 |
virtual const char* what() const throw() { |
148 | 146 |
return "lemon::Dfs::UninitializedParameter"; |
149 | 147 |
} |
150 | 148 |
}; |
151 | 149 |
|
152 | 150 |
///The type of the digraph the algorithm runs on. |
153 | 151 |
typedef typename TR::Digraph Digraph; |
154 | 152 |
|
155 | 153 |
///\brief The type of the map that stores the predecessor arcs of the |
156 | 154 |
///DFS paths. |
157 | 155 |
typedef typename TR::PredMap PredMap; |
158 | 156 |
///The type of the map that stores the distances of the nodes. |
159 | 157 |
typedef typename TR::DistMap DistMap; |
160 | 158 |
///The type of the map that indicates which nodes are reached. |
161 | 159 |
typedef typename TR::ReachedMap ReachedMap; |
162 | 160 |
///The type of the map that indicates which nodes are processed. |
163 | 161 |
typedef typename TR::ProcessedMap ProcessedMap; |
164 | 162 |
///The type of the paths. |
165 | 163 |
typedef PredMapPath<Digraph, PredMap> Path; |
166 | 164 |
|
167 | 165 |
///The traits class. |
168 | 166 |
typedef TR Traits; |
169 | 167 |
|
170 | 168 |
private: |
171 | 169 |
|
172 | 170 |
typedef typename Digraph::Node Node; |
173 | 171 |
typedef typename Digraph::NodeIt NodeIt; |
174 | 172 |
typedef typename Digraph::Arc Arc; |
175 | 173 |
typedef typename Digraph::OutArcIt OutArcIt; |
176 | 174 |
|
177 | 175 |
//Pointer to the underlying digraph. |
178 | 176 |
const Digraph *G; |
179 | 177 |
//Pointer to the map of predecessor arcs. |
180 | 178 |
PredMap *_pred; |
181 | 179 |
//Indicates if _pred is locally allocated (true) or not. |
182 | 180 |
bool local_pred; |
183 | 181 |
//Pointer to the map of distances. |
184 | 182 |
DistMap *_dist; |
185 | 183 |
//Indicates if _dist is locally allocated (true) or not. |
186 | 184 |
bool local_dist; |
187 | 185 |
//Pointer to the map of reached status of the nodes. |
188 | 186 |
ReachedMap *_reached; |
189 | 187 |
//Indicates if _reached is locally allocated (true) or not. |
190 | 188 |
bool local_reached; |
191 | 189 |
//Pointer to the map of processed status of the nodes. |
192 | 190 |
ProcessedMap *_processed; |
193 | 191 |
//Indicates if _processed is locally allocated (true) or not. |
194 | 192 |
bool local_processed; |
195 | 193 |
|
196 | 194 |
std::vector<typename Digraph::OutArcIt> _stack; |
197 | 195 |
int _stack_head; |
198 | 196 |
|
199 |
///Creates the maps if necessary. |
|
200 |
///\todo Better memory allocation (instead of new). |
|
197 |
//Creates the maps if necessary. |
|
201 | 198 |
void create_maps() |
202 | 199 |
{ |
203 | 200 |
if(!_pred) { |
204 | 201 |
local_pred = true; |
205 | 202 |
_pred = Traits::createPredMap(*G); |
206 | 203 |
} |
207 | 204 |
if(!_dist) { |
208 | 205 |
local_dist = true; |
209 | 206 |
_dist = Traits::createDistMap(*G); |
210 | 207 |
} |
211 | 208 |
if(!_reached) { |
212 | 209 |
local_reached = true; |
213 | 210 |
_reached = Traits::createReachedMap(*G); |
214 | 211 |
} |
215 | 212 |
if(!_processed) { |
216 | 213 |
local_processed = true; |
217 | 214 |
_processed = Traits::createProcessedMap(*G); |
218 | 215 |
} |
219 | 216 |
} |
220 | 217 |
|
221 | 218 |
protected: |
222 | 219 |
|
223 | 220 |
Dfs() {} |
224 | 221 |
|
225 | 222 |
public: |
226 | 223 |
|
227 | 224 |
typedef Dfs Create; |
228 | 225 |
|
229 | 226 |
///\name Named template parameters |
230 | 227 |
|
231 | 228 |
///@{ |
232 | 229 |
|
233 | 230 |
template <class T> |
234 | 231 |
struct SetPredMapTraits : public Traits { |
235 | 232 |
typedef T PredMap; |
236 | 233 |
static PredMap *createPredMap(const Digraph &) |
237 | 234 |
{ |
238 | 235 |
throw UninitializedParameter(); |
239 | 236 |
} |
240 | 237 |
}; |
241 | 238 |
///\brief \ref named-templ-param "Named parameter" for setting |
242 | 239 |
///\ref PredMap type. |
243 | 240 |
/// |
244 | 241 |
///\ref named-templ-param "Named parameter" for setting |
245 | 242 |
///\ref PredMap type. |
246 | 243 |
template <class T> |
247 | 244 |
struct SetPredMap : public Dfs<Digraph, SetPredMapTraits<T> > { |
248 | 245 |
typedef Dfs<Digraph, SetPredMapTraits<T> > Create; |
249 | 246 |
}; |
250 | 247 |
|
251 | 248 |
template <class T> |
252 | 249 |
struct SetDistMapTraits : public Traits { |
253 | 250 |
typedef T DistMap; |
254 | 251 |
static DistMap *createDistMap(const Digraph &) |
255 | 252 |
{ |
256 | 253 |
throw UninitializedParameter(); |
257 | 254 |
} |
258 | 255 |
}; |
259 | 256 |
///\brief \ref named-templ-param "Named parameter" for setting |
260 | 257 |
///\ref DistMap type. |
261 | 258 |
/// |
262 | 259 |
///\ref named-templ-param "Named parameter" for setting |
263 | 260 |
///\ref DistMap type. |
264 | 261 |
template <class T> |
265 | 262 |
struct SetDistMap : public Dfs< Digraph, SetDistMapTraits<T> > { |
266 | 263 |
typedef Dfs<Digraph, SetDistMapTraits<T> > Create; |
267 | 264 |
}; |
268 | 265 |
|
269 | 266 |
template <class T> |
270 | 267 |
struct SetReachedMapTraits : public Traits { |
271 | 268 |
typedef T ReachedMap; |
272 | 269 |
static ReachedMap *createReachedMap(const Digraph &) |
273 | 270 |
{ |
274 | 271 |
throw UninitializedParameter(); |
275 | 272 |
} |
276 | 273 |
}; |
277 | 274 |
///\brief \ref named-templ-param "Named parameter" for setting |
278 | 275 |
///\ref ReachedMap type. |
279 | 276 |
/// |
280 | 277 |
///\ref named-templ-param "Named parameter" for setting |
281 | 278 |
///\ref ReachedMap type. |
282 | 279 |
template <class T> |
283 | 280 |
struct SetReachedMap : public Dfs< Digraph, SetReachedMapTraits<T> > { |
284 | 281 |
typedef Dfs< Digraph, SetReachedMapTraits<T> > Create; |
285 | 282 |
}; |
286 | 283 |
|
287 | 284 |
template <class T> |
288 | 285 |
struct SetProcessedMapTraits : public Traits { |
289 | 286 |
typedef T ProcessedMap; |
290 | 287 |
static ProcessedMap *createProcessedMap(const Digraph &) |
291 | 288 |
{ |
292 | 289 |
throw UninitializedParameter(); |
293 | 290 |
} |
294 | 291 |
}; |
295 | 292 |
///\brief \ref named-templ-param "Named parameter" for setting |
296 | 293 |
///\ref ProcessedMap type. |
297 | 294 |
/// |
298 | 295 |
///\ref named-templ-param "Named parameter" for setting |
299 | 296 |
///\ref ProcessedMap type. |
300 | 297 |
template <class T> |
301 | 298 |
struct SetProcessedMap : public Dfs< Digraph, SetProcessedMapTraits<T> > { |
302 | 299 |
typedef Dfs< Digraph, SetProcessedMapTraits<T> > Create; |
303 | 300 |
}; |
304 | 301 |
|
305 | 302 |
struct SetStandardProcessedMapTraits : public Traits { |
306 | 303 |
typedef typename Digraph::template NodeMap<bool> ProcessedMap; |
307 | 304 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
308 | 305 |
{ |
309 | 306 |
return new ProcessedMap(g); |
310 | 307 |
} |
311 | 308 |
}; |
312 | 309 |
///\brief \ref named-templ-param "Named parameter" for setting |
313 | 310 |
///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>. |
314 | 311 |
/// |
315 | 312 |
///\ref named-templ-param "Named parameter" for setting |
316 | 313 |
///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>. |
317 | 314 |
///If you don't set it explicitly, it will be automatically allocated. |
318 | 315 |
struct SetStandardProcessedMap : |
319 | 316 |
public Dfs< Digraph, SetStandardProcessedMapTraits > { |
320 | 317 |
typedef Dfs< Digraph, SetStandardProcessedMapTraits > Create; |
321 | 318 |
}; |
322 | 319 |
|
323 | 320 |
///@} |
324 | 321 |
|
325 | 322 |
public: |
326 | 323 |
|
327 | 324 |
///Constructor. |
328 | 325 |
|
329 | 326 |
///Constructor. |
330 | 327 |
///\param g The digraph the algorithm runs on. |
331 | 328 |
Dfs(const Digraph &g) : |
332 | 329 |
G(&g), |
333 | 330 |
_pred(NULL), local_pred(false), |
334 | 331 |
_dist(NULL), local_dist(false), |
335 | 332 |
_reached(NULL), local_reached(false), |
336 | 333 |
_processed(NULL), local_processed(false) |
337 | 334 |
{ } |
338 | 335 |
|
339 | 336 |
///Destructor. |
340 | 337 |
~Dfs() |
341 | 338 |
{ |
342 | 339 |
if(local_pred) delete _pred; |
343 | 340 |
if(local_dist) delete _dist; |
344 | 341 |
if(local_reached) delete _reached; |
345 | 342 |
if(local_processed) delete _processed; |
346 | 343 |
} |
347 | 344 |
|
348 | 345 |
///Sets the map that stores the predecessor arcs. |
349 | 346 |
|
350 | 347 |
///Sets the map that stores the predecessor arcs. |
351 | 348 |
///If you don't use this function before calling \ref run(), |
352 | 349 |
///it will allocate one. The destructor deallocates this |
353 | 350 |
///automatically allocated map, of course. |
354 | 351 |
///\return <tt> (*this) </tt> |
355 | 352 |
Dfs &predMap(PredMap &m) |
356 | 353 |
{ |
357 | 354 |
if(local_pred) { |
358 | 355 |
delete _pred; |
359 | 356 |
local_pred=false; |
360 | 357 |
} |
361 | 358 |
_pred = &m; |
362 | 359 |
return *this; |
363 | 360 |
} |
364 | 361 |
|
365 | 362 |
///Sets the map that indicates which nodes are reached. |
366 | 363 |
|
367 | 364 |
///Sets the map that indicates which nodes are reached. |
368 | 365 |
///If you don't use this function before calling \ref run(), |
369 | 366 |
///it will allocate one. The destructor deallocates this |
370 | 367 |
///automatically allocated map, of course. |
371 | 368 |
///\return <tt> (*this) </tt> |
372 | 369 |
Dfs &reachedMap(ReachedMap &m) |
373 | 370 |
{ |
374 | 371 |
if(local_reached) { |
375 | 372 |
delete _reached; |
376 | 373 |
local_reached=false; |
377 | 374 |
} |
378 | 375 |
_reached = &m; |
379 | 376 |
return *this; |
380 | 377 |
} |
381 | 378 |
|
382 | 379 |
///Sets the map that indicates which nodes are processed. |
383 | 380 |
|
384 | 381 |
///Sets the map that indicates which nodes are processed. |
385 | 382 |
///If you don't use this function before calling \ref run(), |
386 | 383 |
///it will allocate one. The destructor deallocates this |
387 | 384 |
///automatically allocated map, of course. |
388 | 385 |
///\return <tt> (*this) </tt> |
389 | 386 |
Dfs &processedMap(ProcessedMap &m) |
390 | 387 |
{ |
391 | 388 |
if(local_processed) { |
392 | 389 |
delete _processed; |
393 | 390 |
local_processed=false; |
394 | 391 |
} |
395 | 392 |
_processed = &m; |
396 | 393 |
return *this; |
397 | 394 |
} |
398 | 395 |
|
399 | 396 |
///Sets the map that stores the distances of the nodes. |
400 | 397 |
|
401 | 398 |
///Sets the map that stores the distances of the nodes calculated by |
402 | 399 |
///the algorithm. |
403 | 400 |
///If you don't use this function before calling \ref run(), |
404 | 401 |
///it will allocate one. The destructor deallocates this |
405 | 402 |
///automatically allocated map, of course. |
406 | 403 |
///\return <tt> (*this) </tt> |
407 | 404 |
Dfs &distMap(DistMap &m) |
408 | 405 |
{ |
409 | 406 |
if(local_dist) { |
410 | 407 |
delete _dist; |
411 | 408 |
local_dist=false; |
412 | 409 |
} |
413 | 410 |
_dist = &m; |
414 | 411 |
return *this; |
415 | 412 |
} |
416 | 413 |
|
417 | 414 |
public: |
418 | 415 |
|
419 | 416 |
///\name Execution control |
420 | 417 |
///The simplest way to execute the algorithm is to use |
421 | 418 |
///one of the member functions called \ref lemon::Dfs::run() "run()". |
422 | 419 |
///\n |
423 | 420 |
///If you need more control on the execution, first you must call |
424 | 421 |
///\ref lemon::Dfs::init() "init()", then you can add a source node |
425 | 422 |
///with \ref lemon::Dfs::addSource() "addSource()". |
426 | 423 |
///Finally \ref lemon::Dfs::start() "start()" will perform the |
427 | 424 |
///actual path computation. |
428 | 425 |
|
429 | 426 |
///@{ |
430 | 427 |
|
431 | 428 |
///Initializes the internal data structures. |
432 | 429 |
|
433 | 430 |
///Initializes the internal data structures. |
434 | 431 |
/// |
435 | 432 |
void init() |
436 | 433 |
{ |
437 | 434 |
create_maps(); |
438 | 435 |
_stack.resize(countNodes(*G)); |
439 | 436 |
_stack_head=-1; |
440 | 437 |
for ( NodeIt u(*G) ; u!=INVALID ; ++u ) { |
441 | 438 |
_pred->set(u,INVALID); |
442 | 439 |
_reached->set(u,false); |
443 | 440 |
_processed->set(u,false); |
444 | 441 |
} |
445 | 442 |
} |
446 | 443 |
|
447 | 444 |
///Adds a new source node. |
448 | 445 |
|
449 | 446 |
///Adds a new source node to the set of nodes to be processed. |
450 | 447 |
/// |
451 | 448 |
///\pre The stack must be empty. (Otherwise the algorithm gives |
452 | 449 |
///false results.) |
453 | 450 |
/// |
454 | 451 |
///\warning Distances will be wrong (or at least strange) in case of |
455 | 452 |
///multiple sources. |
456 | 453 |
void addSource(Node s) |
457 | 454 |
{ |
458 | 455 |
LEMON_DEBUG(emptyQueue(), "The stack is not empty."); |
459 | 456 |
if(!(*_reached)[s]) |
460 | 457 |
{ |
461 | 458 |
_reached->set(s,true); |
462 | 459 |
_pred->set(s,INVALID); |
463 | 460 |
OutArcIt e(*G,s); |
464 | 461 |
if(e!=INVALID) { |
465 | 462 |
_stack[++_stack_head]=e; |
466 | 463 |
_dist->set(s,_stack_head); |
467 | 464 |
} |
468 | 465 |
else { |
469 | 466 |
_processed->set(s,true); |
470 | 467 |
_dist->set(s,0); |
471 | 468 |
} |
472 | 469 |
} |
473 | 470 |
} |
474 | 471 |
|
475 | 472 |
///Processes the next arc. |
476 | 473 |
|
477 | 474 |
///Processes the next arc. |
478 | 475 |
/// |
479 | 476 |
///\return The processed arc. |
480 | 477 |
/// |
481 | 478 |
///\pre The stack must not be empty. |
482 | 479 |
Arc processNextArc() |
483 | 480 |
{ |
484 | 481 |
Node m; |
485 | 482 |
Arc e=_stack[_stack_head]; |
486 | 483 |
if(!(*_reached)[m=G->target(e)]) { |
487 | 484 |
_pred->set(m,e); |
488 | 485 |
_reached->set(m,true); |
489 | 486 |
++_stack_head; |
490 | 487 |
_stack[_stack_head] = OutArcIt(*G, m); |
491 | 488 |
_dist->set(m,_stack_head); |
492 | 489 |
} |
493 | 490 |
else { |
494 | 491 |
m=G->source(e); |
495 | 492 |
++_stack[_stack_head]; |
496 | 493 |
} |
497 | 494 |
while(_stack_head>=0 && _stack[_stack_head]==INVALID) { |
498 | 495 |
_processed->set(m,true); |
499 | 496 |
--_stack_head; |
500 | 497 |
if(_stack_head>=0) { |
501 | 498 |
m=G->source(_stack[_stack_head]); |
502 | 499 |
++_stack[_stack_head]; |
503 | 500 |
} |
504 | 501 |
} |
505 | 502 |
return e; |
506 | 503 |
} |
507 | 504 |
|
508 | 505 |
///Next arc to be processed. |
509 | 506 |
|
510 | 507 |
///Next arc to be processed. |
511 | 508 |
/// |
512 | 509 |
///\return The next arc to be processed or \c INVALID if the stack |
513 | 510 |
///is empty. |
514 | 511 |
OutArcIt nextArc() const |
515 | 512 |
{ |
516 | 513 |
return _stack_head>=0?_stack[_stack_head]:INVALID; |
517 | 514 |
} |
518 | 515 |
|
519 | 516 |
///\brief Returns \c false if there are nodes |
520 | 517 |
///to be processed. |
521 | 518 |
/// |
522 | 519 |
///Returns \c false if there are nodes |
523 | 520 |
///to be processed in the queue (stack). |
524 | 521 |
bool emptyQueue() const { return _stack_head<0; } |
525 | 522 |
|
526 | 523 |
///Returns the number of the nodes to be processed. |
527 | 524 |
|
528 | 525 |
///Returns the number of the nodes to be processed in the queue (stack). |
529 | 526 |
int queueSize() const { return _stack_head+1; } |
530 | 527 |
|
531 | 528 |
///Executes the algorithm. |
532 | 529 |
|
533 | 530 |
///Executes the algorithm. |
534 | 531 |
/// |
535 | 532 |
///This method runs the %DFS algorithm from the root node |
536 | 533 |
///in order to compute the DFS path to each node. |
537 | 534 |
/// |
538 | 535 |
/// The algorithm computes |
539 | 536 |
///- the %DFS tree, |
540 | 537 |
///- the distance of each node from the root in the %DFS tree. |
541 | 538 |
/// |
542 | 539 |
///\pre init() must be called and a root node should be |
543 | 540 |
///added with addSource() before using this function. |
544 | 541 |
/// |
545 | 542 |
///\note <tt>d.start()</tt> is just a shortcut of the following code. |
546 | 543 |
///\code |
547 | 544 |
/// while ( !d.emptyQueue() ) { |
548 | 545 |
/// d.processNextArc(); |
549 | 546 |
/// } |
550 | 547 |
///\endcode |
551 | 548 |
void start() |
552 | 549 |
{ |
553 | 550 |
while ( !emptyQueue() ) processNextArc(); |
554 | 551 |
} |
555 | 552 |
|
556 | 553 |
///Executes the algorithm until the given target node is reached. |
557 | 554 |
|
558 | 555 |
///Executes the algorithm until the given target node is reached. |
559 | 556 |
/// |
560 | 557 |
///This method runs the %DFS algorithm from the root node |
561 | 558 |
///in order to compute the DFS path to \c dest. |
562 | 559 |
/// |
563 | 560 |
///The algorithm computes |
564 | 561 |
///- the %DFS path to \c dest, |
565 | 562 |
///- the distance of \c dest from the root in the %DFS tree. |
566 | 563 |
/// |
567 | 564 |
///\pre init() must be called and a root node should be |
568 | 565 |
///added with addSource() before using this function. |
569 | 566 |
void start(Node dest) |
570 | 567 |
{ |
571 | 568 |
while ( !emptyQueue() && G->target(_stack[_stack_head])!=dest ) |
572 | 569 |
processNextArc(); |
573 | 570 |
} |
574 | 571 |
|
575 | 572 |
///Executes the algorithm until a condition is met. |
576 | 573 |
|
577 | 574 |
///Executes the algorithm until a condition is met. |
578 | 575 |
/// |
579 | 576 |
///This method runs the %DFS algorithm from the root node |
580 | 577 |
///until an arc \c a with <tt>am[a]</tt> true is found. |
581 | 578 |
/// |
582 | 579 |
///\param am A \c bool (or convertible) arc map. The algorithm |
583 | 580 |
///will stop when it reaches an arc \c a with <tt>am[a]</tt> true. |
584 | 581 |
/// |
585 | 582 |
///\return The reached arc \c a with <tt>am[a]</tt> true or |
586 | 583 |
///\c INVALID if no such arc was found. |
587 | 584 |
/// |
588 | 585 |
///\pre init() must be called and a root node should be |
589 | 586 |
///added with addSource() before using this function. |
590 | 587 |
/// |
591 | 588 |
///\warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map, |
592 | 589 |
///not a node map. |
593 | 590 |
template<class ArcBoolMap> |
594 | 591 |
Arc start(const ArcBoolMap &am) |
595 | 592 |
{ |
596 | 593 |
while ( !emptyQueue() && !am[_stack[_stack_head]] ) |
597 | 594 |
processNextArc(); |
598 | 595 |
return emptyQueue() ? INVALID : _stack[_stack_head]; |
599 | 596 |
} |
600 | 597 |
|
601 | 598 |
///Runs the algorithm from the given node. |
602 | 599 |
|
603 | 600 |
///This method runs the %DFS algorithm from node \c s |
604 | 601 |
///in order to compute the DFS path to each node. |
605 | 602 |
/// |
606 | 603 |
///The algorithm computes |
607 | 604 |
///- the %DFS tree, |
608 | 605 |
///- the distance of each node from the root in the %DFS tree. |
609 | 606 |
/// |
610 | 607 |
///\note <tt>d.run(s)</tt> is just a shortcut of the following code. |
611 | 608 |
///\code |
612 | 609 |
/// d.init(); |
613 | 610 |
/// d.addSource(s); |
614 | 611 |
/// d.start(); |
615 | 612 |
///\endcode |
616 | 613 |
void run(Node s) { |
617 | 614 |
init(); |
618 | 615 |
addSource(s); |
619 | 616 |
start(); |
620 | 617 |
} |
621 | 618 |
|
622 | 619 |
///Finds the %DFS path between \c s and \c t. |
623 | 620 |
|
624 | 621 |
///This method runs the %DFS algorithm from node \c s |
625 | 622 |
///in order to compute the DFS path to \c t. |
626 | 623 |
/// |
627 | 624 |
///\return The length of the <tt>s</tt>--<tt>t</tt> DFS path, |
628 | 625 |
///if \c t is reachable form \c s, \c 0 otherwise. |
629 | 626 |
/// |
630 | 627 |
///\note Apart from the return value, <tt>d.run(s,t)</tt> is |
631 | 628 |
///just a shortcut of the following code. |
632 | 629 |
///\code |
633 | 630 |
/// d.init(); |
634 | 631 |
/// d.addSource(s); |
635 | 632 |
/// d.start(t); |
636 | 633 |
///\endcode |
637 | 634 |
int run(Node s,Node t) { |
638 | 635 |
init(); |
639 | 636 |
addSource(s); |
640 | 637 |
start(t); |
641 | 638 |
return reached(t)?_stack_head+1:0; |
642 | 639 |
} |
643 | 640 |
|
644 | 641 |
///Runs the algorithm to visit all nodes in the digraph. |
645 | 642 |
|
646 | 643 |
///This method runs the %DFS algorithm in order to compute the |
647 | 644 |
///%DFS path to each node. |
648 | 645 |
/// |
649 | 646 |
///The algorithm computes |
650 | 647 |
///- the %DFS tree, |
651 | 648 |
///- the distance of each node from the root in the %DFS tree. |
652 | 649 |
/// |
653 | 650 |
///\note <tt>d.run()</tt> is just a shortcut of the following code. |
654 | 651 |
///\code |
655 | 652 |
/// d.init(); |
656 | 653 |
/// for (NodeIt n(digraph); n != INVALID; ++n) { |
657 | 654 |
/// if (!d.reached(n)) { |
658 | 655 |
/// d.addSource(n); |
659 | 656 |
/// d.start(); |
660 | 657 |
/// } |
661 | 658 |
/// } |
662 | 659 |
///\endcode |
663 | 660 |
void run() { |
664 | 661 |
init(); |
665 | 662 |
for (NodeIt it(*G); it != INVALID; ++it) { |
666 | 663 |
if (!reached(it)) { |
667 | 664 |
addSource(it); |
668 | 665 |
start(); |
669 | 666 |
} |
670 | 667 |
} |
671 | 668 |
} |
672 | 669 |
|
673 | 670 |
///@} |
674 | 671 |
|
675 | 672 |
///\name Query Functions |
676 | 673 |
///The result of the %DFS algorithm can be obtained using these |
677 | 674 |
///functions.\n |
678 | 675 |
///Either \ref lemon::Dfs::run() "run()" or \ref lemon::Dfs::start() |
679 | 676 |
///"start()" must be called before using them. |
680 | 677 |
|
681 | 678 |
///@{ |
682 | 679 |
|
683 | 680 |
///The DFS path to a node. |
684 | 681 |
|
685 | 682 |
///Returns the DFS path to a node. |
686 | 683 |
/// |
687 | 684 |
///\warning \c t should be reachable from the root. |
688 | 685 |
/// |
689 | 686 |
///\pre Either \ref run() or \ref start() must be called before |
690 | 687 |
///using this function. |
691 | 688 |
Path path(Node t) const { return Path(*G, *_pred, t); } |
692 | 689 |
|
693 | 690 |
///The distance of a node from the root. |
694 | 691 |
|
695 | 692 |
///Returns the distance of a node from the root. |
696 | 693 |
/// |
697 | 694 |
///\warning If node \c v is not reachable from the root, then |
698 | 695 |
///the return value of this function is undefined. |
699 | 696 |
/// |
700 | 697 |
///\pre Either \ref run() or \ref start() must be called before |
701 | 698 |
///using this function. |
702 | 699 |
int dist(Node v) const { return (*_dist)[v]; } |
703 | 700 |
|
704 | 701 |
///Returns the 'previous arc' of the %DFS tree for a node. |
705 | 702 |
|
706 | 703 |
///This function returns the 'previous arc' of the %DFS tree for the |
707 | 704 |
///node \c v, i.e. it returns the last arc of a %DFS path from the |
708 | 705 |
///root to \c v. It is \c INVALID |
709 | 706 |
///if \c v is not reachable from the root(s) or if \c v is a root. |
710 | 707 |
/// |
711 | 708 |
///The %DFS tree used here is equal to the %DFS tree used in |
712 | 709 |
///\ref predNode(). |
713 | 710 |
/// |
714 | 711 |
///\pre Either \ref run() or \ref start() must be called before using |
715 | 712 |
///this function. |
716 | 713 |
Arc predArc(Node v) const { return (*_pred)[v];} |
717 | 714 |
|
718 | 715 |
///Returns the 'previous node' of the %DFS tree. |
719 | 716 |
|
720 | 717 |
///This function returns the 'previous node' of the %DFS |
721 | 718 |
///tree for the node \c v, i.e. it returns the last but one node |
722 | 719 |
///from a %DFS path from the root to \c v. It is \c INVALID |
723 | 720 |
///if \c v is not reachable from the root(s) or if \c v is a root. |
724 | 721 |
/// |
725 | 722 |
///The %DFS tree used here is equal to the %DFS tree used in |
726 | 723 |
///\ref predArc(). |
727 | 724 |
/// |
728 | 725 |
///\pre Either \ref run() or \ref start() must be called before |
729 | 726 |
///using this function. |
730 | 727 |
Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID: |
731 | 728 |
G->source((*_pred)[v]); } |
732 | 729 |
|
733 | 730 |
///\brief Returns a const reference to the node map that stores the |
734 | 731 |
///distances of the nodes. |
735 | 732 |
/// |
736 | 733 |
///Returns a const reference to the node map that stores the |
737 | 734 |
///distances of the nodes calculated by the algorithm. |
738 | 735 |
/// |
739 | 736 |
///\pre Either \ref run() or \ref init() |
740 | 737 |
///must be called before using this function. |
741 | 738 |
const DistMap &distMap() const { return *_dist;} |
742 | 739 |
|
743 | 740 |
///\brief Returns a const reference to the node map that stores the |
744 | 741 |
///predecessor arcs. |
745 | 742 |
/// |
746 | 743 |
///Returns a const reference to the node map that stores the predecessor |
747 | 744 |
///arcs, which form the DFS tree. |
748 | 745 |
/// |
749 | 746 |
///\pre Either \ref run() or \ref init() |
750 | 747 |
///must be called before using this function. |
751 | 748 |
const PredMap &predMap() const { return *_pred;} |
752 | 749 |
|
753 | 750 |
///Checks if a node is reachable from the root(s). |
754 | 751 |
|
755 | 752 |
///Returns \c true if \c v is reachable from the root(s). |
756 | 753 |
///\pre Either \ref run() or \ref start() |
757 | 754 |
///must be called before using this function. |
758 | 755 |
bool reached(Node v) const { return (*_reached)[v]; } |
759 | 756 |
|
760 | 757 |
///@} |
761 | 758 |
}; |
762 | 759 |
|
763 | 760 |
///Default traits class of dfs() function. |
764 | 761 |
|
765 | 762 |
///Default traits class of dfs() function. |
766 | 763 |
///\tparam GR Digraph type. |
767 | 764 |
template<class GR> |
768 | 765 |
struct DfsWizardDefaultTraits |
769 | 766 |
{ |
770 | 767 |
///The type of the digraph the algorithm runs on. |
771 | 768 |
typedef GR Digraph; |
772 | 769 |
|
773 | 770 |
///\brief The type of the map that stores the predecessor |
774 | 771 |
///arcs of the %DFS paths. |
775 | 772 |
/// |
776 | 773 |
///The type of the map that stores the predecessor |
777 | 774 |
///arcs of the %DFS paths. |
778 | 775 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
779 | 776 |
typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap; |
780 | 777 |
///Instantiates a \ref PredMap. |
781 | 778 |
|
782 | 779 |
///This function instantiates a \ref PredMap. |
783 | 780 |
///\param g is the digraph, to which we would like to define the |
784 | 781 |
///\ref PredMap. |
785 |
///\todo The digraph alone may be insufficient to initialize |
|
786 | 782 |
static PredMap *createPredMap(const Digraph &g) |
787 | 783 |
{ |
788 | 784 |
return new PredMap(g); |
789 | 785 |
} |
790 | 786 |
|
791 | 787 |
///The type of the map that indicates which nodes are processed. |
792 | 788 |
|
793 | 789 |
///The type of the map that indicates which nodes are processed. |
794 | 790 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
795 | 791 |
///By default it is a NullMap. |
796 | 792 |
typedef NullMap<typename Digraph::Node,bool> ProcessedMap; |
797 | 793 |
///Instantiates a \ref ProcessedMap. |
798 | 794 |
|
799 | 795 |
///This function instantiates a \ref ProcessedMap. |
800 | 796 |
///\param g is the digraph, to which |
801 | 797 |
///we would like to define the \ref ProcessedMap. |
802 | 798 |
#ifdef DOXYGEN |
803 | 799 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
804 | 800 |
#else |
805 | 801 |
static ProcessedMap *createProcessedMap(const Digraph &) |
806 | 802 |
#endif |
807 | 803 |
{ |
808 | 804 |
return new ProcessedMap(); |
809 | 805 |
} |
810 | 806 |
|
811 | 807 |
///The type of the map that indicates which nodes are reached. |
812 | 808 |
|
813 | 809 |
///The type of the map that indicates which nodes are reached. |
814 | 810 |
///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept. |
815 | 811 |
typedef typename Digraph::template NodeMap<bool> ReachedMap; |
816 | 812 |
///Instantiates a \ref ReachedMap. |
817 | 813 |
|
818 | 814 |
///This function instantiates a \ref ReachedMap. |
819 | 815 |
///\param g is the digraph, to which |
820 | 816 |
///we would like to define the \ref ReachedMap. |
821 | 817 |
static ReachedMap *createReachedMap(const Digraph &g) |
822 | 818 |
{ |
823 | 819 |
return new ReachedMap(g); |
824 | 820 |
} |
825 | 821 |
|
826 | 822 |
///The type of the map that stores the distances of the nodes. |
827 | 823 |
|
828 | 824 |
///The type of the map that stores the distances of the nodes. |
829 | 825 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
830 | 826 |
typedef typename Digraph::template NodeMap<int> DistMap; |
831 | 827 |
///Instantiates a \ref DistMap. |
832 | 828 |
|
833 | 829 |
///This function instantiates a \ref DistMap. |
834 | 830 |
///\param g is the digraph, to which we would like to define |
835 | 831 |
///the \ref DistMap |
836 | 832 |
static DistMap *createDistMap(const Digraph &g) |
837 | 833 |
{ |
838 | 834 |
return new DistMap(g); |
839 | 835 |
} |
840 | 836 |
|
841 | 837 |
///The type of the DFS paths. |
842 | 838 |
|
843 | 839 |
///The type of the DFS paths. |
844 | 840 |
///It must meet the \ref concepts::Path "Path" concept. |
845 | 841 |
typedef lemon::Path<Digraph> Path; |
846 | 842 |
}; |
847 | 843 |
|
848 | 844 |
/// Default traits class used by \ref DfsWizard |
849 | 845 |
|
850 | 846 |
/// To make it easier to use Dfs algorithm |
851 | 847 |
/// we have created a wizard class. |
852 | 848 |
/// This \ref DfsWizard class needs default traits, |
853 | 849 |
/// as well as the \ref Dfs class. |
854 | 850 |
/// The \ref DfsWizardBase is a class to be the default traits of the |
855 | 851 |
/// \ref DfsWizard class. |
856 | 852 |
template<class GR> |
857 | 853 |
class DfsWizardBase : public DfsWizardDefaultTraits<GR> |
858 | 854 |
{ |
859 | 855 |
|
860 | 856 |
typedef DfsWizardDefaultTraits<GR> Base; |
861 | 857 |
protected: |
862 | 858 |
//The type of the nodes in the digraph. |
863 | 859 |
typedef typename Base::Digraph::Node Node; |
864 | 860 |
|
865 | 861 |
//Pointer to the digraph the algorithm runs on. |
866 | 862 |
void *_g; |
867 | 863 |
//Pointer to the map of reached nodes. |
868 | 864 |
void *_reached; |
869 | 865 |
//Pointer to the map of processed nodes. |
870 | 866 |
void *_processed; |
871 | 867 |
//Pointer to the map of predecessors arcs. |
872 | 868 |
void *_pred; |
873 | 869 |
//Pointer to the map of distances. |
874 | 870 |
void *_dist; |
875 | 871 |
//Pointer to the DFS path to the target node. |
876 | 872 |
void *_path; |
877 | 873 |
//Pointer to the distance of the target node. |
878 | 874 |
int *_di; |
879 | 875 |
|
880 | 876 |
public: |
881 | 877 |
/// Constructor. |
882 | 878 |
|
883 | 879 |
/// This constructor does not require parameters, therefore it initiates |
884 | 880 |
/// all of the attributes to \c 0. |
885 | 881 |
DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0), |
886 | 882 |
_dist(0), _path(0), _di(0) {} |
887 | 883 |
|
888 | 884 |
/// Constructor. |
889 | 885 |
|
890 | 886 |
/// This constructor requires one parameter, |
891 | 887 |
/// others are initiated to \c 0. |
892 | 888 |
/// \param g The digraph the algorithm runs on. |
893 | 889 |
DfsWizardBase(const GR &g) : |
894 | 890 |
_g(reinterpret_cast<void*>(const_cast<GR*>(&g))), |
895 | 891 |
_reached(0), _processed(0), _pred(0), _dist(0), _path(0), _di(0) {} |
896 | 892 |
|
897 | 893 |
}; |
898 | 894 |
|
899 | 895 |
/// Auxiliary class for the function-type interface of DFS algorithm. |
900 | 896 |
|
901 | 897 |
/// This auxiliary class is created to implement the |
902 | 898 |
/// \ref dfs() "function-type interface" of \ref Dfs algorithm. |
903 | 899 |
/// It does not have own \ref run() method, it uses the functions |
904 | 900 |
/// and features of the plain \ref Dfs. |
905 | 901 |
/// |
906 | 902 |
/// This class should only be used through the \ref dfs() function, |
907 | 903 |
/// which makes it easier to use the algorithm. |
908 | 904 |
template<class TR> |
909 | 905 |
class DfsWizard : public TR |
910 | 906 |
{ |
911 | 907 |
typedef TR Base; |
912 | 908 |
|
913 | 909 |
///The type of the digraph the algorithm runs on. |
914 | 910 |
typedef typename TR::Digraph Digraph; |
915 | 911 |
|
916 | 912 |
typedef typename Digraph::Node Node; |
917 | 913 |
typedef typename Digraph::NodeIt NodeIt; |
918 | 914 |
typedef typename Digraph::Arc Arc; |
919 | 915 |
typedef typename Digraph::OutArcIt OutArcIt; |
920 | 916 |
|
921 | 917 |
///\brief The type of the map that stores the predecessor |
922 | 918 |
///arcs of the DFS paths. |
923 | 919 |
typedef typename TR::PredMap PredMap; |
924 | 920 |
///\brief The type of the map that stores the distances of the nodes. |
925 | 921 |
typedef typename TR::DistMap DistMap; |
926 | 922 |
///\brief The type of the map that indicates which nodes are reached. |
927 | 923 |
typedef typename TR::ReachedMap ReachedMap; |
928 | 924 |
///\brief The type of the map that indicates which nodes are processed. |
929 | 925 |
typedef typename TR::ProcessedMap ProcessedMap; |
930 | 926 |
///The type of the DFS paths |
931 | 927 |
typedef typename TR::Path Path; |
932 | 928 |
|
933 | 929 |
public: |
934 | 930 |
|
935 | 931 |
/// Constructor. |
936 | 932 |
DfsWizard() : TR() {} |
937 | 933 |
|
938 | 934 |
/// Constructor that requires parameters. |
939 | 935 |
|
940 | 936 |
/// Constructor that requires parameters. |
941 | 937 |
/// These parameters will be the default values for the traits class. |
942 | 938 |
/// \param g The digraph the algorithm runs on. |
943 | 939 |
DfsWizard(const Digraph &g) : |
944 | 940 |
TR(g) {} |
945 | 941 |
|
946 | 942 |
///Copy constructor |
947 | 943 |
DfsWizard(const TR &b) : TR(b) {} |
948 | 944 |
|
949 | 945 |
~DfsWizard() {} |
950 | 946 |
|
951 | 947 |
///Runs DFS algorithm from the given source node. |
952 | 948 |
|
953 | 949 |
///This method runs DFS algorithm from node \c s |
954 | 950 |
///in order to compute the DFS path to each node. |
955 | 951 |
void run(Node s) |
956 | 952 |
{ |
957 | 953 |
Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g)); |
958 | 954 |
if (Base::_pred) |
959 | 955 |
alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); |
960 | 956 |
if (Base::_dist) |
961 | 957 |
alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); |
962 | 958 |
if (Base::_reached) |
963 | 959 |
alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached)); |
964 | 960 |
if (Base::_processed) |
965 | 961 |
alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed)); |
966 | 962 |
if (s!=INVALID) |
967 | 963 |
alg.run(s); |
968 | 964 |
else |
969 | 965 |
alg.run(); |
970 | 966 |
} |
971 | 967 |
|
972 | 968 |
///Finds the DFS path between \c s and \c t. |
973 | 969 |
|
974 | 970 |
///This method runs DFS algorithm from node \c s |
975 | 971 |
///in order to compute the DFS path to node \c t |
976 | 972 |
///(it stops searching when \c t is processed). |
977 | 973 |
/// |
978 | 974 |
///\return \c true if \c t is reachable form \c s. |
979 | 975 |
bool run(Node s, Node t) |
980 | 976 |
{ |
981 | 977 |
if (s==INVALID || t==INVALID) throw UninitializedParameter(); |
982 | 978 |
Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g)); |
983 | 979 |
if (Base::_pred) |
984 | 980 |
alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); |
985 | 981 |
if (Base::_dist) |
986 | 982 |
alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); |
987 | 983 |
if (Base::_reached) |
988 | 984 |
alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached)); |
989 | 985 |
if (Base::_processed) |
990 | 986 |
alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed)); |
991 | 987 |
alg.run(s,t); |
992 | 988 |
if (Base::_path) |
993 | 989 |
*reinterpret_cast<Path*>(Base::_path) = alg.path(t); |
994 | 990 |
if (Base::_di) |
995 | 991 |
*Base::_di = alg.dist(t); |
996 | 992 |
return alg.reached(t); |
997 | 993 |
} |
998 | 994 |
|
999 | 995 |
///Runs DFS algorithm to visit all nodes in the digraph. |
1000 | 996 |
|
1001 | 997 |
///This method runs DFS algorithm in order to compute |
1002 | 998 |
///the DFS path to each node. |
1003 | 999 |
void run() |
1004 | 1000 |
{ |
1005 | 1001 |
run(INVALID); |
1006 | 1002 |
} |
1007 | 1003 |
|
1008 | 1004 |
template<class T> |
1009 | 1005 |
struct SetPredMapBase : public Base { |
1010 | 1006 |
typedef T PredMap; |
1011 | 1007 |
static PredMap *createPredMap(const Digraph &) { return 0; }; |
1012 | 1008 |
SetPredMapBase(const TR &b) : TR(b) {} |
1013 | 1009 |
}; |
1014 | 1010 |
///\brief \ref named-func-param "Named parameter" |
1015 | 1011 |
///for setting \ref PredMap object. |
1016 | 1012 |
/// |
1017 | 1013 |
///\ref named-func-param "Named parameter" |
1018 | 1014 |
///for setting \ref PredMap object. |
1019 | 1015 |
template<class T> |
1020 | 1016 |
DfsWizard<SetPredMapBase<T> > predMap(const T &t) |
1021 | 1017 |
{ |
1022 | 1018 |
Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1023 | 1019 |
return DfsWizard<SetPredMapBase<T> >(*this); |
1024 | 1020 |
} |
1025 | 1021 |
|
1026 | 1022 |
template<class T> |
1027 | 1023 |
struct SetReachedMapBase : public Base { |
1028 | 1024 |
typedef T ReachedMap; |
1029 | 1025 |
static ReachedMap *createReachedMap(const Digraph &) { return 0; }; |
1030 | 1026 |
SetReachedMapBase(const TR &b) : TR(b) {} |
1031 | 1027 |
}; |
1032 | 1028 |
///\brief \ref named-func-param "Named parameter" |
1033 | 1029 |
///for setting \ref ReachedMap object. |
1034 | 1030 |
/// |
1035 | 1031 |
/// \ref named-func-param "Named parameter" |
1036 | 1032 |
///for setting \ref ReachedMap object. |
1037 | 1033 |
template<class T> |
1038 | 1034 |
DfsWizard<SetReachedMapBase<T> > reachedMap(const T &t) |
1039 | 1035 |
{ |
1040 | 1036 |
Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1041 | 1037 |
return DfsWizard<SetReachedMapBase<T> >(*this); |
1042 | 1038 |
} |
1043 | 1039 |
|
1044 | 1040 |
template<class T> |
1045 | 1041 |
struct SetDistMapBase : public Base { |
1046 | 1042 |
typedef T DistMap; |
1047 | 1043 |
static DistMap *createDistMap(const Digraph &) { return 0; }; |
1048 | 1044 |
SetDistMapBase(const TR &b) : TR(b) {} |
1049 | 1045 |
}; |
1050 | 1046 |
///\brief \ref named-func-param "Named parameter" |
1051 | 1047 |
///for setting \ref DistMap object. |
1052 | 1048 |
/// |
1053 | 1049 |
/// \ref named-func-param "Named parameter" |
1054 | 1050 |
///for setting \ref DistMap object. |
1055 | 1051 |
template<class T> |
1056 | 1052 |
DfsWizard<SetDistMapBase<T> > distMap(const T &t) |
1057 | 1053 |
{ |
1058 | 1054 |
Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1059 | 1055 |
return DfsWizard<SetDistMapBase<T> >(*this); |
1060 | 1056 |
} |
1061 | 1057 |
|
1062 | 1058 |
template<class T> |
1063 | 1059 |
struct SetProcessedMapBase : public Base { |
1064 | 1060 |
typedef T ProcessedMap; |
1065 | 1061 |
static ProcessedMap *createProcessedMap(const Digraph &) { return 0; }; |
1066 | 1062 |
SetProcessedMapBase(const TR &b) : TR(b) {} |
1067 | 1063 |
}; |
1068 | 1064 |
///\brief \ref named-func-param "Named parameter" |
1069 | 1065 |
///for setting \ref ProcessedMap object. |
1070 | 1066 |
/// |
1071 | 1067 |
/// \ref named-func-param "Named parameter" |
1072 | 1068 |
///for setting \ref ProcessedMap object. |
1073 | 1069 |
template<class T> |
1074 | 1070 |
DfsWizard<SetProcessedMapBase<T> > processedMap(const T &t) |
1075 | 1071 |
{ |
1076 | 1072 |
Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1077 | 1073 |
return DfsWizard<SetProcessedMapBase<T> >(*this); |
1078 | 1074 |
} |
1079 | 1075 |
|
1080 | 1076 |
template<class T> |
1081 | 1077 |
struct SetPathBase : public Base { |
1082 | 1078 |
typedef T Path; |
1083 | 1079 |
SetPathBase(const TR &b) : TR(b) {} |
1084 | 1080 |
}; |
1085 | 1081 |
///\brief \ref named-func-param "Named parameter" |
1086 | 1082 |
///for getting the DFS path to the target node. |
1087 | 1083 |
/// |
1088 | 1084 |
///\ref named-func-param "Named parameter" |
1089 | 1085 |
///for getting the DFS path to the target node. |
1090 | 1086 |
template<class T> |
1091 | 1087 |
DfsWizard<SetPathBase<T> > path(const T &t) |
1092 | 1088 |
{ |
1093 | 1089 |
Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1094 | 1090 |
return DfsWizard<SetPathBase<T> >(*this); |
1095 | 1091 |
} |
1096 | 1092 |
|
1097 | 1093 |
///\brief \ref named-func-param "Named parameter" |
1098 | 1094 |
///for getting the distance of the target node. |
1099 | 1095 |
/// |
1100 | 1096 |
///\ref named-func-param "Named parameter" |
1101 | 1097 |
///for getting the distance of the target node. |
1102 | 1098 |
DfsWizard dist(const int &d) |
1103 | 1099 |
{ |
1104 | 1100 |
Base::_di=const_cast<int*>(&d); |
1105 | 1101 |
return *this; |
1106 | 1102 |
} |
1107 | 1103 |
|
1108 | 1104 |
}; |
1109 | 1105 |
|
1110 | 1106 |
///Function-type interface for DFS algorithm. |
1111 | 1107 |
|
1112 | 1108 |
///\ingroup search |
1113 | 1109 |
///Function-type interface for DFS algorithm. |
1114 | 1110 |
/// |
1115 | 1111 |
///This function also has several \ref named-func-param "named parameters", |
1116 | 1112 |
///they are declared as the members of class \ref DfsWizard. |
1117 | 1113 |
///The following examples show how to use these parameters. |
1118 | 1114 |
///\code |
1119 | 1115 |
/// // Compute the DFS tree |
1120 | 1116 |
/// dfs(g).predMap(preds).distMap(dists).run(s); |
1121 | 1117 |
/// |
1122 | 1118 |
/// // Compute the DFS path from s to t |
1123 | 1119 |
/// bool reached = dfs(g).path(p).dist(d).run(s,t); |
1124 | 1120 |
///\endcode |
1125 | 1121 |
|
1126 | 1122 |
///\warning Don't forget to put the \ref DfsWizard::run() "run()" |
1127 | 1123 |
///to the end of the parameter list. |
1128 | 1124 |
///\sa DfsWizard |
1129 | 1125 |
///\sa Dfs |
1130 | 1126 |
template<class GR> |
1131 | 1127 |
DfsWizard<DfsWizardBase<GR> > |
1132 | 1128 |
dfs(const GR &digraph) |
1133 | 1129 |
{ |
1134 | 1130 |
return DfsWizard<DfsWizardBase<GR> >(digraph); |
1135 | 1131 |
} |
1136 | 1132 |
|
1137 | 1133 |
#ifdef DOXYGEN |
1138 | 1134 |
/// \brief Visitor class for DFS. |
1139 | 1135 |
/// |
1140 | 1136 |
/// This class defines the interface of the DfsVisit events, and |
1141 | 1137 |
/// it could be the base of a real visitor class. |
1142 | 1138 |
template <typename _Digraph> |
1143 | 1139 |
struct DfsVisitor { |
1144 | 1140 |
typedef _Digraph Digraph; |
1145 | 1141 |
typedef typename Digraph::Arc Arc; |
1146 | 1142 |
typedef typename Digraph::Node Node; |
1147 | 1143 |
/// \brief Called for the source node of the DFS. |
1148 | 1144 |
/// |
1149 | 1145 |
/// This function is called for the source node of the DFS. |
1150 | 1146 |
void start(const Node& node) {} |
1151 | 1147 |
/// \brief Called when the source node is leaved. |
1152 | 1148 |
/// |
1153 | 1149 |
/// This function is called when the source node is leaved. |
1154 | 1150 |
void stop(const Node& node) {} |
1155 | 1151 |
/// \brief Called when a node is reached first time. |
1156 | 1152 |
/// |
1157 | 1153 |
/// This function is called when a node is reached first time. |
1158 | 1154 |
void reach(const Node& node) {} |
1159 | 1155 |
/// \brief Called when an arc reaches a new node. |
1160 | 1156 |
/// |
1161 | 1157 |
/// This function is called when the DFS finds an arc whose target node |
1162 | 1158 |
/// is not reached yet. |
1163 | 1159 |
void discover(const Arc& arc) {} |
1164 | 1160 |
/// \brief Called when an arc is examined but its target node is |
1165 | 1161 |
/// already discovered. |
1166 | 1162 |
/// |
1167 | 1163 |
/// This function is called when an arc is examined but its target node is |
1168 | 1164 |
/// already discovered. |
1169 | 1165 |
void examine(const Arc& arc) {} |
1170 | 1166 |
/// \brief Called when the DFS steps back from a node. |
1171 | 1167 |
/// |
1172 | 1168 |
/// This function is called when the DFS steps back from a node. |
1173 | 1169 |
void leave(const Node& node) {} |
1174 | 1170 |
/// \brief Called when the DFS steps back on an arc. |
1175 | 1171 |
/// |
1176 | 1172 |
/// This function is called when the DFS steps back on an arc. |
1177 | 1173 |
void backtrack(const Arc& arc) {} |
1178 | 1174 |
}; |
1179 | 1175 |
#else |
1180 | 1176 |
template <typename _Digraph> |
1181 | 1177 |
struct DfsVisitor { |
1182 | 1178 |
typedef _Digraph Digraph; |
1183 | 1179 |
typedef typename Digraph::Arc Arc; |
1184 | 1180 |
typedef typename Digraph::Node Node; |
1185 | 1181 |
void start(const Node&) {} |
1186 | 1182 |
void stop(const Node&) {} |
1187 | 1183 |
void reach(const Node&) {} |
1188 | 1184 |
void discover(const Arc&) {} |
1189 | 1185 |
void examine(const Arc&) {} |
1190 | 1186 |
void leave(const Node&) {} |
1191 | 1187 |
void backtrack(const Arc&) {} |
1192 | 1188 |
|
1193 | 1189 |
template <typename _Visitor> |
1194 | 1190 |
struct Constraints { |
1195 | 1191 |
void constraints() { |
1196 | 1192 |
Arc arc; |
1197 | 1193 |
Node node; |
1198 | 1194 |
visitor.start(node); |
1199 | 1195 |
visitor.stop(arc); |
1200 | 1196 |
visitor.reach(node); |
1201 | 1197 |
visitor.discover(arc); |
1202 | 1198 |
visitor.examine(arc); |
1203 | 1199 |
visitor.leave(node); |
1204 | 1200 |
visitor.backtrack(arc); |
1205 | 1201 |
} |
1206 | 1202 |
_Visitor& visitor; |
1207 | 1203 |
}; |
1208 | 1204 |
}; |
1209 | 1205 |
#endif |
1210 | 1206 |
|
1211 | 1207 |
/// \brief Default traits class of DfsVisit class. |
1212 | 1208 |
/// |
1213 | 1209 |
/// Default traits class of DfsVisit class. |
1214 | 1210 |
/// \tparam _Digraph The type of the digraph the algorithm runs on. |
1215 | 1211 |
template<class _Digraph> |
1216 | 1212 |
struct DfsVisitDefaultTraits { |
1217 | 1213 |
|
1218 | 1214 |
/// \brief The type of the digraph the algorithm runs on. |
1219 | 1215 |
typedef _Digraph Digraph; |
1220 | 1216 |
|
1221 | 1217 |
/// \brief The type of the map that indicates which nodes are reached. |
1222 | 1218 |
/// |
1223 | 1219 |
/// The type of the map that indicates which nodes are reached. |
1224 | 1220 |
/// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept. |
1225 | 1221 |
typedef typename Digraph::template NodeMap<bool> ReachedMap; |
1226 | 1222 |
|
1227 | 1223 |
/// \brief Instantiates a \ref ReachedMap. |
1228 | 1224 |
/// |
1229 | 1225 |
/// This function instantiates a \ref ReachedMap. |
1230 | 1226 |
/// \param digraph is the digraph, to which |
1231 | 1227 |
/// we would like to define the \ref ReachedMap. |
1232 | 1228 |
static ReachedMap *createReachedMap(const Digraph &digraph) { |
1233 | 1229 |
return new ReachedMap(digraph); |
1234 | 1230 |
} |
1235 | 1231 |
|
1236 | 1232 |
}; |
1237 | 1233 |
|
1238 | 1234 |
/// \ingroup search |
1239 | 1235 |
/// |
1240 | 1236 |
/// \brief %DFS algorithm class with visitor interface. |
1241 | 1237 |
/// |
1242 | 1238 |
/// This class provides an efficient implementation of the %DFS algorithm |
1243 | 1239 |
/// with visitor interface. |
1244 | 1240 |
/// |
1245 | 1241 |
/// The %DfsVisit class provides an alternative interface to the Dfs |
1246 | 1242 |
/// class. It works with callback mechanism, the DfsVisit object calls |
1247 | 1243 |
/// the member functions of the \c Visitor class on every DFS event. |
1248 | 1244 |
/// |
1249 | 1245 |
/// This interface of the DFS algorithm should be used in special cases |
1250 | 1246 |
/// when extra actions have to be performed in connection with certain |
1251 | 1247 |
/// events of the DFS algorithm. Otherwise consider to use Dfs or dfs() |
1252 | 1248 |
/// instead. |
1253 | 1249 |
/// |
1254 | 1250 |
/// \tparam _Digraph The type of the digraph the algorithm runs on. |
1255 | 1251 |
/// The default value is |
1256 | 1252 |
/// \ref ListDigraph. The value of _Digraph is not used directly by |
1257 | 1253 |
/// \ref DfsVisit, it is only passed to \ref DfsVisitDefaultTraits. |
1258 | 1254 |
/// \tparam _Visitor The Visitor type that is used by the algorithm. |
1259 | 1255 |
/// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty visitor, which |
1260 | 1256 |
/// does not observe the DFS events. If you want to observe the DFS |
1261 | 1257 |
/// events, you should implement your own visitor class. |
1262 | 1258 |
/// \tparam _Traits Traits class to set various data types used by the |
1263 | 1259 |
/// algorithm. The default traits class is |
1264 | 1260 |
/// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>". |
1265 | 1261 |
/// See \ref DfsVisitDefaultTraits for the documentation of |
1266 | 1262 |
/// a DFS visit traits class. |
1267 | 1263 |
#ifdef DOXYGEN |
1268 | 1264 |
template <typename _Digraph, typename _Visitor, typename _Traits> |
1269 | 1265 |
#else |
1270 | 1266 |
template <typename _Digraph = ListDigraph, |
1271 | 1267 |
typename _Visitor = DfsVisitor<_Digraph>, |
1272 | 1268 |
typename _Traits = DfsDefaultTraits<_Digraph> > |
1273 | 1269 |
#endif |
1274 | 1270 |
class DfsVisit { |
1275 | 1271 |
public: |
1276 | 1272 |
|
1277 | 1273 |
/// \brief \ref Exception for uninitialized parameters. |
1278 | 1274 |
/// |
1279 | 1275 |
/// This error represents problems in the initialization |
1280 | 1276 |
/// of the parameters of the algorithm. |
1281 | 1277 |
class UninitializedParameter : public lemon::UninitializedParameter { |
1282 | 1278 |
public: |
1283 | 1279 |
virtual const char* what() const throw() |
1284 | 1280 |
{ |
1285 | 1281 |
return "lemon::DfsVisit::UninitializedParameter"; |
1286 | 1282 |
} |
1287 | 1283 |
}; |
1288 | 1284 |
|
1289 | 1285 |
///The traits class. |
1290 | 1286 |
typedef _Traits Traits; |
1291 | 1287 |
|
1292 | 1288 |
///The type of the digraph the algorithm runs on. |
1293 | 1289 |
typedef typename Traits::Digraph Digraph; |
1294 | 1290 |
|
1295 | 1291 |
///The visitor type used by the algorithm. |
1296 | 1292 |
typedef _Visitor Visitor; |
1297 | 1293 |
|
1298 | 1294 |
///The type of the map that indicates which nodes are reached. |
1299 | 1295 |
typedef typename Traits::ReachedMap ReachedMap; |
1300 | 1296 |
|
1301 | 1297 |
private: |
1302 | 1298 |
|
1303 | 1299 |
typedef typename Digraph::Node Node; |
1304 | 1300 |
typedef typename Digraph::NodeIt NodeIt; |
1305 | 1301 |
typedef typename Digraph::Arc Arc; |
1306 | 1302 |
typedef typename Digraph::OutArcIt OutArcIt; |
1307 | 1303 |
|
1308 | 1304 |
//Pointer to the underlying digraph. |
1309 | 1305 |
const Digraph *_digraph; |
1310 | 1306 |
//Pointer to the visitor object. |
1311 | 1307 |
Visitor *_visitor; |
1312 | 1308 |
//Pointer to the map of reached status of the nodes. |
1313 | 1309 |
ReachedMap *_reached; |
1314 | 1310 |
//Indicates if _reached is locally allocated (true) or not. |
1315 | 1311 |
bool local_reached; |
1316 | 1312 |
|
1317 | 1313 |
std::vector<typename Digraph::Arc> _stack; |
1318 | 1314 |
int _stack_head; |
1319 | 1315 |
|
1320 |
///Creates the maps if necessary. |
|
1321 |
///\todo Better memory allocation (instead of new). |
|
1316 |
//Creates the maps if necessary. |
|
1322 | 1317 |
void create_maps() { |
1323 | 1318 |
if(!_reached) { |
1324 | 1319 |
local_reached = true; |
1325 | 1320 |
_reached = Traits::createReachedMap(*_digraph); |
1326 | 1321 |
} |
1327 | 1322 |
} |
1328 | 1323 |
|
1329 | 1324 |
protected: |
1330 | 1325 |
|
1331 | 1326 |
DfsVisit() {} |
1332 | 1327 |
|
1333 | 1328 |
public: |
1334 | 1329 |
|
1335 | 1330 |
typedef DfsVisit Create; |
1336 | 1331 |
|
1337 | 1332 |
/// \name Named template parameters |
1338 | 1333 |
|
1339 | 1334 |
///@{ |
1340 | 1335 |
template <class T> |
1341 | 1336 |
struct SetReachedMapTraits : public Traits { |
1342 | 1337 |
typedef T ReachedMap; |
1343 | 1338 |
static ReachedMap *createReachedMap(const Digraph &digraph) { |
1344 | 1339 |
throw UninitializedParameter(); |
1345 | 1340 |
} |
1346 | 1341 |
}; |
1347 | 1342 |
/// \brief \ref named-templ-param "Named parameter" for setting |
1348 | 1343 |
/// ReachedMap type. |
1349 | 1344 |
/// |
1350 | 1345 |
/// \ref named-templ-param "Named parameter" for setting ReachedMap type. |
1351 | 1346 |
template <class T> |
1352 | 1347 |
struct SetReachedMap : public DfsVisit< Digraph, Visitor, |
1353 | 1348 |
SetReachedMapTraits<T> > { |
1354 | 1349 |
typedef DfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create; |
1355 | 1350 |
}; |
1356 | 1351 |
///@} |
1357 | 1352 |
|
1358 | 1353 |
public: |
1359 | 1354 |
|
1360 | 1355 |
/// \brief Constructor. |
1361 | 1356 |
/// |
1362 | 1357 |
/// Constructor. |
1363 | 1358 |
/// |
1364 | 1359 |
/// \param digraph The digraph the algorithm runs on. |
1365 | 1360 |
/// \param visitor The visitor object of the algorithm. |
1366 | 1361 |
DfsVisit(const Digraph& digraph, Visitor& visitor) |
1367 | 1362 |
: _digraph(&digraph), _visitor(&visitor), |
1368 | 1363 |
_reached(0), local_reached(false) {} |
1369 | 1364 |
|
1370 | 1365 |
/// \brief Destructor. |
1371 | 1366 |
~DfsVisit() { |
1372 | 1367 |
if(local_reached) delete _reached; |
1373 | 1368 |
} |
1374 | 1369 |
|
1375 | 1370 |
/// \brief Sets the map that indicates which nodes are reached. |
1376 | 1371 |
/// |
1377 | 1372 |
/// Sets the map that indicates which nodes are reached. |
1378 | 1373 |
/// If you don't use this function before calling \ref run(), |
1379 | 1374 |
/// it will allocate one. The destructor deallocates this |
1380 | 1375 |
/// automatically allocated map, of course. |
1381 | 1376 |
/// \return <tt> (*this) </tt> |
1382 | 1377 |
DfsVisit &reachedMap(ReachedMap &m) { |
1383 | 1378 |
if(local_reached) { |
1384 | 1379 |
delete _reached; |
1385 | 1380 |
local_reached=false; |
1386 | 1381 |
} |
1387 | 1382 |
_reached = &m; |
1388 | 1383 |
return *this; |
1389 | 1384 |
} |
1390 | 1385 |
|
1391 | 1386 |
public: |
1392 | 1387 |
|
1393 | 1388 |
/// \name Execution control |
1394 | 1389 |
/// The simplest way to execute the algorithm is to use |
1395 | 1390 |
/// one of the member functions called \ref lemon::DfsVisit::run() |
1396 | 1391 |
/// "run()". |
1397 | 1392 |
/// \n |
1398 | 1393 |
/// If you need more control on the execution, first you must call |
1399 | 1394 |
/// \ref lemon::DfsVisit::init() "init()", then you can add several |
1400 | 1395 |
/// source nodes with \ref lemon::DfsVisit::addSource() "addSource()". |
1401 | 1396 |
/// Finally \ref lemon::DfsVisit::start() "start()" will perform the |
1402 | 1397 |
/// actual path computation. |
1403 | 1398 |
|
1404 | 1399 |
/// @{ |
1405 | 1400 |
|
1406 | 1401 |
/// \brief Initializes the internal data structures. |
1407 | 1402 |
/// |
1408 | 1403 |
/// Initializes the internal data structures. |
1409 | 1404 |
void init() { |
1410 | 1405 |
create_maps(); |
1411 | 1406 |
_stack.resize(countNodes(*_digraph)); |
1412 | 1407 |
_stack_head = -1; |
1413 | 1408 |
for (NodeIt u(*_digraph) ; u != INVALID ; ++u) { |
1414 | 1409 |
_reached->set(u, false); |
1415 | 1410 |
} |
1416 | 1411 |
} |
1417 | 1412 |
|
1418 | 1413 |
///Adds a new source node. |
1419 | 1414 |
|
1420 | 1415 |
///Adds a new source node to the set of nodes to be processed. |
1421 | 1416 |
/// |
1422 | 1417 |
///\pre The stack must be empty. (Otherwise the algorithm gives |
1423 | 1418 |
///false results.) |
1424 | 1419 |
/// |
1425 | 1420 |
///\warning Distances will be wrong (or at least strange) in case of |
1426 | 1421 |
///multiple sources. |
1427 | 1422 |
void addSource(Node s) |
1428 | 1423 |
{ |
1429 | 1424 |
LEMON_DEBUG(emptyQueue(), "The stack is not empty."); |
1430 | 1425 |
if(!(*_reached)[s]) { |
1431 | 1426 |
_reached->set(s,true); |
1432 | 1427 |
_visitor->start(s); |
1433 | 1428 |
_visitor->reach(s); |
1434 | 1429 |
Arc e; |
1435 | 1430 |
_digraph->firstOut(e, s); |
1436 | 1431 |
if (e != INVALID) { |
1437 | 1432 |
_stack[++_stack_head] = e; |
1438 | 1433 |
} else { |
1439 | 1434 |
_visitor->leave(s); |
1440 | 1435 |
} |
1441 | 1436 |
} |
1442 | 1437 |
} |
1443 | 1438 |
|
1444 | 1439 |
/// \brief Processes the next arc. |
1445 | 1440 |
/// |
1446 | 1441 |
/// Processes the next arc. |
1447 | 1442 |
/// |
1448 | 1443 |
/// \return The processed arc. |
1449 | 1444 |
/// |
1450 | 1445 |
/// \pre The stack must not be empty. |
1451 | 1446 |
Arc processNextArc() { |
1452 | 1447 |
Arc e = _stack[_stack_head]; |
1453 | 1448 |
Node m = _digraph->target(e); |
1454 | 1449 |
if(!(*_reached)[m]) { |
1455 | 1450 |
_visitor->discover(e); |
1456 | 1451 |
_visitor->reach(m); |
1457 | 1452 |
_reached->set(m, true); |
1458 | 1453 |
_digraph->firstOut(_stack[++_stack_head], m); |
1459 | 1454 |
} else { |
1460 | 1455 |
_visitor->examine(e); |
1461 | 1456 |
m = _digraph->source(e); |
1462 | 1457 |
_digraph->nextOut(_stack[_stack_head]); |
1463 | 1458 |
} |
1464 | 1459 |
while (_stack_head>=0 && _stack[_stack_head] == INVALID) { |
1465 | 1460 |
_visitor->leave(m); |
1466 | 1461 |
--_stack_head; |
1467 | 1462 |
if (_stack_head >= 0) { |
1468 | 1463 |
_visitor->backtrack(_stack[_stack_head]); |
1469 | 1464 |
m = _digraph->source(_stack[_stack_head]); |
1470 | 1465 |
_digraph->nextOut(_stack[_stack_head]); |
1471 | 1466 |
} else { |
1472 | 1467 |
_visitor->stop(m); |
1473 | 1468 |
} |
1474 | 1469 |
} |
1475 | 1470 |
return e; |
1476 | 1471 |
} |
1477 | 1472 |
|
1478 | 1473 |
/// \brief Next arc to be processed. |
1479 | 1474 |
/// |
1480 | 1475 |
/// Next arc to be processed. |
1481 | 1476 |
/// |
1482 | 1477 |
/// \return The next arc to be processed or INVALID if the stack is |
1483 | 1478 |
/// empty. |
1484 | 1479 |
Arc nextArc() const { |
1485 | 1480 |
return _stack_head >= 0 ? _stack[_stack_head] : INVALID; |
1486 | 1481 |
} |
1487 | 1482 |
|
1488 | 1483 |
/// \brief Returns \c false if there are nodes |
1489 | 1484 |
/// to be processed. |
1490 | 1485 |
/// |
1491 | 1486 |
/// Returns \c false if there are nodes |
1492 | 1487 |
/// to be processed in the queue (stack). |
1493 | 1488 |
bool emptyQueue() const { return _stack_head < 0; } |
1494 | 1489 |
|
1495 | 1490 |
/// \brief Returns the number of the nodes to be processed. |
1496 | 1491 |
/// |
1497 | 1492 |
/// Returns the number of the nodes to be processed in the queue (stack). |
1498 | 1493 |
int queueSize() const { return _stack_head + 1; } |
1499 | 1494 |
|
1500 | 1495 |
/// \brief Executes the algorithm. |
1501 | 1496 |
/// |
1502 | 1497 |
/// Executes the algorithm. |
1503 | 1498 |
/// |
1504 | 1499 |
/// This method runs the %DFS algorithm from the root node |
1505 | 1500 |
/// in order to compute the %DFS path to each node. |
1506 | 1501 |
/// |
1507 | 1502 |
/// The algorithm computes |
1508 | 1503 |
/// - the %DFS tree, |
1509 | 1504 |
/// - the distance of each node from the root in the %DFS tree. |
1510 | 1505 |
/// |
1511 | 1506 |
/// \pre init() must be called and a root node should be |
1512 | 1507 |
/// added with addSource() before using this function. |
1513 | 1508 |
/// |
1514 | 1509 |
/// \note <tt>d.start()</tt> is just a shortcut of the following code. |
1515 | 1510 |
/// \code |
1516 | 1511 |
/// while ( !d.emptyQueue() ) { |
1517 | 1512 |
/// d.processNextArc(); |
1518 | 1513 |
/// } |
1519 | 1514 |
/// \endcode |
1520 | 1515 |
void start() { |
1521 | 1516 |
while ( !emptyQueue() ) processNextArc(); |
1522 | 1517 |
} |
1523 | 1518 |
|
1524 | 1519 |
/// \brief Executes the algorithm until the given target node is reached. |
1525 | 1520 |
/// |
1526 | 1521 |
/// Executes the algorithm until the given target node is reached. |
1527 | 1522 |
/// |
1528 | 1523 |
/// This method runs the %DFS algorithm from the root node |
1529 | 1524 |
/// in order to compute the DFS path to \c dest. |
1530 | 1525 |
/// |
1531 | 1526 |
/// The algorithm computes |
1532 | 1527 |
/// - the %DFS path to \c dest, |
1533 | 1528 |
/// - the distance of \c dest from the root in the %DFS tree. |
1534 | 1529 |
/// |
1535 | 1530 |
/// \pre init() must be called and a root node should be added |
1536 | 1531 |
/// with addSource() before using this function. |
1537 | 1532 |
void start(Node dest) { |
1538 | 1533 |
while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != dest ) |
1539 | 1534 |
processNextArc(); |
1540 | 1535 |
} |
1541 | 1536 |
|
1542 | 1537 |
/// \brief Executes the algorithm until a condition is met. |
1543 | 1538 |
/// |
1544 | 1539 |
/// Executes the algorithm until a condition is met. |
1545 | 1540 |
/// |
1546 | 1541 |
/// This method runs the %DFS algorithm from the root node |
1547 | 1542 |
/// until an arc \c a with <tt>am[a]</tt> true is found. |
1548 | 1543 |
/// |
1549 | 1544 |
/// \param am A \c bool (or convertible) arc map. The algorithm |
1550 | 1545 |
/// will stop when it reaches an arc \c a with <tt>am[a]</tt> true. |
1551 | 1546 |
/// |
1552 | 1547 |
/// \return The reached arc \c a with <tt>am[a]</tt> true or |
1553 | 1548 |
/// \c INVALID if no such arc was found. |
1554 | 1549 |
/// |
1555 | 1550 |
/// \pre init() must be called and a root node should be added |
1556 | 1551 |
/// with addSource() before using this function. |
1557 | 1552 |
/// |
1558 | 1553 |
/// \warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map, |
1559 | 1554 |
/// not a node map. |
1560 | 1555 |
template <typename AM> |
1561 | 1556 |
Arc start(const AM &am) { |
1562 | 1557 |
while ( !emptyQueue() && !am[_stack[_stack_head]] ) |
1563 | 1558 |
processNextArc(); |
1564 | 1559 |
return emptyQueue() ? INVALID : _stack[_stack_head]; |
1565 | 1560 |
} |
1566 | 1561 |
|
1567 | 1562 |
/// \brief Runs the algorithm from the given node. |
1568 | 1563 |
/// |
1569 | 1564 |
/// This method runs the %DFS algorithm from node \c s. |
1570 | 1565 |
/// in order to compute the DFS path to each node. |
1571 | 1566 |
/// |
1572 | 1567 |
/// The algorithm computes |
1573 | 1568 |
/// - the %DFS tree, |
1574 | 1569 |
/// - the distance of each node from the root in the %DFS tree. |
1575 | 1570 |
/// |
1576 | 1571 |
/// \note <tt>d.run(s)</tt> is just a shortcut of the following code. |
1577 | 1572 |
///\code |
1578 | 1573 |
/// d.init(); |
1579 | 1574 |
/// d.addSource(s); |
1580 | 1575 |
/// d.start(); |
1581 | 1576 |
///\endcode |
1582 | 1577 |
void run(Node s) { |
1583 | 1578 |
init(); |
1584 | 1579 |
addSource(s); |
1585 | 1580 |
start(); |
1586 | 1581 |
} |
1587 | 1582 |
|
1588 | 1583 |
/// \brief Finds the %DFS path between \c s and \c t. |
1589 | 1584 |
|
1590 | 1585 |
/// This method runs the %DFS algorithm from node \c s |
1591 | 1586 |
/// in order to compute the DFS path to \c t. |
1592 | 1587 |
/// |
1593 | 1588 |
/// \return The length of the <tt>s</tt>--<tt>t</tt> DFS path, |
1594 | 1589 |
/// if \c t is reachable form \c s, \c 0 otherwise. |
1595 | 1590 |
/// |
1596 | 1591 |
/// \note Apart from the return value, <tt>d.run(s,t)</tt> is |
1597 | 1592 |
/// just a shortcut of the following code. |
1598 | 1593 |
///\code |
1599 | 1594 |
/// d.init(); |
1600 | 1595 |
/// d.addSource(s); |
1601 | 1596 |
/// d.start(t); |
1602 | 1597 |
///\endcode |
1603 | 1598 |
int run(Node s,Node t) { |
1604 | 1599 |
init(); |
1605 | 1600 |
addSource(s); |
1606 | 1601 |
start(t); |
1607 | 1602 |
return reached(t)?_stack_head+1:0; |
1608 | 1603 |
} |
1609 | 1604 |
|
1610 | 1605 |
/// \brief Runs the algorithm to visit all nodes in the digraph. |
1611 | 1606 |
|
1612 | 1607 |
/// This method runs the %DFS algorithm in order to |
1613 | 1608 |
/// compute the %DFS path to each node. |
1614 | 1609 |
/// |
1615 | 1610 |
/// The algorithm computes |
1616 | 1611 |
/// - the %DFS tree, |
1617 | 1612 |
/// - the distance of each node from the root in the %DFS tree. |
1618 | 1613 |
/// |
1619 | 1614 |
/// \note <tt>d.run()</tt> is just a shortcut of the following code. |
1620 | 1615 |
///\code |
1621 | 1616 |
/// d.init(); |
1622 | 1617 |
/// for (NodeIt n(digraph); n != INVALID; ++n) { |
1623 | 1618 |
/// if (!d.reached(n)) { |
1624 | 1619 |
/// d.addSource(n); |
1625 | 1620 |
/// d.start(); |
1626 | 1621 |
/// } |
1627 | 1622 |
/// } |
1628 | 1623 |
///\endcode |
1629 | 1624 |
void run() { |
1630 | 1625 |
init(); |
1631 | 1626 |
for (NodeIt it(*_digraph); it != INVALID; ++it) { |
1632 | 1627 |
if (!reached(it)) { |
1633 | 1628 |
addSource(it); |
1634 | 1629 |
start(); |
1635 | 1630 |
} |
1636 | 1631 |
} |
1637 | 1632 |
} |
1638 | 1633 |
|
1639 | 1634 |
///@} |
1640 | 1635 |
|
1641 | 1636 |
/// \name Query Functions |
1642 | 1637 |
/// The result of the %DFS algorithm can be obtained using these |
1643 | 1638 |
/// functions.\n |
1644 | 1639 |
/// Either \ref lemon::DfsVisit::run() "run()" or |
1645 | 1640 |
/// \ref lemon::DfsVisit::start() "start()" must be called before |
1646 | 1641 |
/// using them. |
1647 | 1642 |
///@{ |
1648 | 1643 |
|
1649 | 1644 |
/// \brief Checks if a node is reachable from the root(s). |
1650 | 1645 |
/// |
1651 | 1646 |
/// Returns \c true if \c v is reachable from the root(s). |
1652 | 1647 |
/// \pre Either \ref run() or \ref start() |
1653 | 1648 |
/// must be called before using this function. |
1654 | 1649 |
bool reached(Node v) { return (*_reached)[v]; } |
1655 | 1650 |
|
1656 | 1651 |
///@} |
1657 | 1652 |
|
1658 | 1653 |
}; |
1659 | 1654 |
|
1660 | 1655 |
} //END OF NAMESPACE LEMON |
1661 | 1656 |
|
1662 | 1657 |
#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-2008 |
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_DIJKSTRA_H |
20 | 20 |
#define LEMON_DIJKSTRA_H |
21 | 21 |
|
22 | 22 |
///\ingroup shortest_path |
23 | 23 |
///\file |
24 | 24 |
///\brief Dijkstra algorithm. |
25 | 25 |
|
26 | 26 |
#include <limits> |
27 | 27 |
#include <lemon/list_graph.h> |
28 | 28 |
#include <lemon/bin_heap.h> |
29 | 29 |
#include <lemon/bits/path_dump.h> |
30 | 30 |
#include <lemon/core.h> |
31 | 31 |
#include <lemon/error.h> |
32 | 32 |
#include <lemon/maps.h> |
33 | 33 |
#include <lemon/path.h> |
34 | 34 |
|
35 | 35 |
namespace lemon { |
36 | 36 |
|
37 | 37 |
/// \brief Default operation traits for the Dijkstra algorithm class. |
38 | 38 |
/// |
39 | 39 |
/// This operation traits class defines all computational operations and |
40 | 40 |
/// constants which are used in the Dijkstra algorithm. |
41 | 41 |
template <typename Value> |
42 | 42 |
struct DijkstraDefaultOperationTraits { |
43 | 43 |
/// \brief Gives back the zero value of the type. |
44 | 44 |
static Value zero() { |
45 | 45 |
return static_cast<Value>(0); |
46 | 46 |
} |
47 | 47 |
/// \brief Gives back the sum of the given two elements. |
48 | 48 |
static Value plus(const Value& left, const Value& right) { |
49 | 49 |
return left + right; |
50 | 50 |
} |
51 | 51 |
/// \brief Gives back true only if the first value is less than the second. |
52 | 52 |
static bool less(const Value& left, const Value& right) { |
53 | 53 |
return left < right; |
54 | 54 |
} |
55 | 55 |
}; |
56 | 56 |
|
57 | 57 |
/// \brief Widest path operation traits for the Dijkstra algorithm class. |
58 | 58 |
/// |
59 | 59 |
/// This operation traits class defines all computational operations and |
60 | 60 |
/// constants which are used in the Dijkstra algorithm for widest path |
61 | 61 |
/// computation. |
62 | 62 |
/// |
63 | 63 |
/// \see DijkstraDefaultOperationTraits |
64 | 64 |
template <typename Value> |
65 | 65 |
struct DijkstraWidestPathOperationTraits { |
66 | 66 |
/// \brief Gives back the maximum value of the type. |
67 | 67 |
static Value zero() { |
68 | 68 |
return std::numeric_limits<Value>::max(); |
69 | 69 |
} |
70 | 70 |
/// \brief Gives back the minimum of the given two elements. |
71 | 71 |
static Value plus(const Value& left, const Value& right) { |
72 | 72 |
return std::min(left, right); |
73 | 73 |
} |
74 | 74 |
/// \brief Gives back true only if the first value is less than the second. |
75 | 75 |
static bool less(const Value& left, const Value& right) { |
76 | 76 |
return left < right; |
77 | 77 |
} |
78 | 78 |
}; |
79 | 79 |
|
80 | 80 |
///Default traits class of Dijkstra class. |
81 | 81 |
|
82 | 82 |
///Default traits class of Dijkstra class. |
83 | 83 |
///\tparam GR The type of the digraph. |
84 | 84 |
///\tparam LM The type of the length map. |
85 | 85 |
template<class GR, class LM> |
86 | 86 |
struct DijkstraDefaultTraits |
87 | 87 |
{ |
88 | 88 |
///The type of the digraph the algorithm runs on. |
89 | 89 |
typedef GR Digraph; |
90 | 90 |
|
91 | 91 |
///The type of the map that stores the arc lengths. |
92 | 92 |
|
93 | 93 |
///The type of the map that stores the arc lengths. |
94 | 94 |
///It must meet the \ref concepts::ReadMap "ReadMap" concept. |
95 | 95 |
typedef LM LengthMap; |
96 | 96 |
///The type of the length of the arcs. |
97 | 97 |
typedef typename LM::Value Value; |
98 | 98 |
|
99 | 99 |
/// Operation traits for Dijkstra algorithm. |
100 | 100 |
|
101 | 101 |
/// This class defines the operations that are used in the algorithm. |
102 | 102 |
/// \see DijkstraDefaultOperationTraits |
103 | 103 |
typedef DijkstraDefaultOperationTraits<Value> OperationTraits; |
104 | 104 |
|
105 | 105 |
/// The cross reference type used by the heap. |
106 | 106 |
|
107 | 107 |
/// The cross reference type used by the heap. |
108 | 108 |
/// Usually it is \c Digraph::NodeMap<int>. |
109 | 109 |
typedef typename Digraph::template NodeMap<int> HeapCrossRef; |
110 | 110 |
///Instantiates a \ref HeapCrossRef. |
111 | 111 |
|
112 | 112 |
///This function instantiates a \ref HeapCrossRef. |
113 | 113 |
/// \param g is the digraph, to which we would like to define the |
114 | 114 |
/// \ref HeapCrossRef. |
115 | 115 |
static HeapCrossRef *createHeapCrossRef(const Digraph &g) |
116 | 116 |
{ |
117 | 117 |
return new HeapCrossRef(g); |
118 | 118 |
} |
119 | 119 |
|
120 | 120 |
///The heap type used by the Dijkstra algorithm. |
121 | 121 |
|
122 | 122 |
///The heap type used by the Dijkstra algorithm. |
123 | 123 |
/// |
124 | 124 |
///\sa BinHeap |
125 | 125 |
///\sa Dijkstra |
126 | 126 |
typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap; |
127 | 127 |
///Instantiates a \ref Heap. |
128 | 128 |
|
129 | 129 |
///This function instantiates a \ref Heap. |
130 | 130 |
static Heap *createHeap(HeapCrossRef& r) |
131 | 131 |
{ |
132 | 132 |
return new Heap(r); |
133 | 133 |
} |
134 | 134 |
|
135 | 135 |
///\brief The type of the map that stores the predecessor |
136 | 136 |
///arcs of the shortest paths. |
137 | 137 |
/// |
138 | 138 |
///The type of the map that stores the predecessor |
139 | 139 |
///arcs of the shortest paths. |
140 | 140 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
141 | 141 |
typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap; |
142 | 142 |
///Instantiates a \ref PredMap. |
143 | 143 |
|
144 | 144 |
///This function instantiates a \ref PredMap. |
145 | 145 |
///\param g is the digraph, to which we would like to define the |
146 | 146 |
///\ref PredMap. |
147 |
///\todo The digraph alone may be insufficient for the initialization |
|
148 | 147 |
static PredMap *createPredMap(const Digraph &g) |
149 | 148 |
{ |
150 | 149 |
return new PredMap(g); |
151 | 150 |
} |
152 | 151 |
|
153 | 152 |
///The type of the map that indicates which nodes are processed. |
154 | 153 |
|
155 | 154 |
///The type of the map that indicates which nodes are processed. |
156 | 155 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
157 | 156 |
///By default it is a NullMap. |
158 |
///\todo If it is set to a real map, |
|
159 |
///Dijkstra::processed() should read this. |
|
160 | 157 |
typedef NullMap<typename Digraph::Node,bool> ProcessedMap; |
161 | 158 |
///Instantiates a \ref ProcessedMap. |
162 | 159 |
|
163 | 160 |
///This function instantiates a \ref ProcessedMap. |
164 | 161 |
///\param g is the digraph, to which |
165 | 162 |
///we would like to define the \ref ProcessedMap |
166 | 163 |
#ifdef DOXYGEN |
167 | 164 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
168 | 165 |
#else |
169 | 166 |
static ProcessedMap *createProcessedMap(const Digraph &) |
170 | 167 |
#endif |
171 | 168 |
{ |
172 | 169 |
return new ProcessedMap(); |
173 | 170 |
} |
174 | 171 |
|
175 | 172 |
///The type of the map that stores the distances of the nodes. |
176 | 173 |
|
177 | 174 |
///The type of the map that stores the distances of the nodes. |
178 | 175 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
179 | 176 |
typedef typename Digraph::template NodeMap<typename LM::Value> DistMap; |
180 | 177 |
///Instantiates a \ref DistMap. |
181 | 178 |
|
182 | 179 |
///This function instantiates a \ref DistMap. |
183 | 180 |
///\param g is the digraph, to which we would like to define |
184 | 181 |
///the \ref DistMap |
185 | 182 |
static DistMap *createDistMap(const Digraph &g) |
186 | 183 |
{ |
187 | 184 |
return new DistMap(g); |
188 | 185 |
} |
189 | 186 |
}; |
190 | 187 |
|
191 | 188 |
///%Dijkstra algorithm class. |
192 | 189 |
|
193 | 190 |
/// \ingroup shortest_path |
194 | 191 |
///This class provides an efficient implementation of the %Dijkstra algorithm. |
195 | 192 |
/// |
196 | 193 |
///The arc lengths are passed to the algorithm using a |
197 | 194 |
///\ref concepts::ReadMap "ReadMap", |
198 | 195 |
///so it is easy to change it to any kind of length. |
199 | 196 |
///The type of the length is determined by the |
200 | 197 |
///\ref concepts::ReadMap::Value "Value" of the length map. |
201 | 198 |
///It is also possible to change the underlying priority heap. |
202 | 199 |
/// |
203 | 200 |
///There is also a \ref dijkstra() "function-type interface" for the |
204 | 201 |
///%Dijkstra algorithm, which is convenient in the simplier cases and |
205 | 202 |
///it can be used easier. |
206 | 203 |
/// |
207 | 204 |
///\tparam GR The type of the digraph the algorithm runs on. |
208 | 205 |
///The default value is \ref ListDigraph. |
209 | 206 |
///The value of GR is not used directly by \ref Dijkstra, it is only |
210 | 207 |
///passed to \ref DijkstraDefaultTraits. |
211 | 208 |
///\tparam LM A readable arc map that determines the lengths of the |
212 | 209 |
///arcs. It is read once for each arc, so the map may involve in |
213 | 210 |
///relatively time consuming process to compute the arc lengths if |
214 | 211 |
///it is necessary. The default map type is \ref |
215 | 212 |
///concepts::Digraph::ArcMap "Digraph::ArcMap<int>". |
216 | 213 |
///The value of LM is not used directly by \ref Dijkstra, it is only |
217 | 214 |
///passed to \ref DijkstraDefaultTraits. |
218 | 215 |
///\tparam TR Traits class to set various data types used by the algorithm. |
219 | 216 |
///The default traits class is \ref DijkstraDefaultTraits |
220 | 217 |
///"DijkstraDefaultTraits<GR,LM>". See \ref DijkstraDefaultTraits |
221 | 218 |
///for the documentation of a Dijkstra traits class. |
222 | 219 |
#ifdef DOXYGEN |
223 | 220 |
template <typename GR, typename LM, typename TR> |
224 | 221 |
#else |
225 | 222 |
template <typename GR=ListDigraph, |
226 | 223 |
typename LM=typename GR::template ArcMap<int>, |
227 | 224 |
typename TR=DijkstraDefaultTraits<GR,LM> > |
228 | 225 |
#endif |
229 | 226 |
class Dijkstra { |
230 | 227 |
public: |
231 | 228 |
///\ref Exception for uninitialized parameters. |
232 | 229 |
|
233 | 230 |
///This error represents problems in the initialization of the |
234 | 231 |
///parameters of the algorithm. |
235 | 232 |
class UninitializedParameter : public lemon::UninitializedParameter { |
236 | 233 |
public: |
237 | 234 |
virtual const char* what() const throw() { |
238 | 235 |
return "lemon::Dijkstra::UninitializedParameter"; |
239 | 236 |
} |
240 | 237 |
}; |
241 | 238 |
|
242 | 239 |
///The type of the digraph the algorithm runs on. |
243 | 240 |
typedef typename TR::Digraph Digraph; |
244 | 241 |
|
245 | 242 |
///The type of the length of the arcs. |
246 | 243 |
typedef typename TR::LengthMap::Value Value; |
247 | 244 |
///The type of the map that stores the arc lengths. |
248 | 245 |
typedef typename TR::LengthMap LengthMap; |
249 | 246 |
///\brief The type of the map that stores the predecessor arcs of the |
250 | 247 |
///shortest paths. |
251 | 248 |
typedef typename TR::PredMap PredMap; |
252 | 249 |
///The type of the map that stores the distances of the nodes. |
253 | 250 |
typedef typename TR::DistMap DistMap; |
254 | 251 |
///The type of the map that indicates which nodes are processed. |
255 | 252 |
typedef typename TR::ProcessedMap ProcessedMap; |
256 | 253 |
///The type of the paths. |
257 | 254 |
typedef PredMapPath<Digraph, PredMap> Path; |
258 | 255 |
///The cross reference type used for the current heap. |
259 | 256 |
typedef typename TR::HeapCrossRef HeapCrossRef; |
260 | 257 |
///The heap type used by the algorithm. |
261 | 258 |
typedef typename TR::Heap Heap; |
262 | 259 |
///The operation traits class. |
263 | 260 |
typedef typename TR::OperationTraits OperationTraits; |
264 | 261 |
|
265 | 262 |
///The traits class. |
266 | 263 |
typedef TR Traits; |
267 | 264 |
|
268 | 265 |
private: |
269 | 266 |
|
270 | 267 |
typedef typename Digraph::Node Node; |
271 | 268 |
typedef typename Digraph::NodeIt NodeIt; |
272 | 269 |
typedef typename Digraph::Arc Arc; |
273 | 270 |
typedef typename Digraph::OutArcIt OutArcIt; |
274 | 271 |
|
275 | 272 |
//Pointer to the underlying digraph. |
276 | 273 |
const Digraph *G; |
277 | 274 |
//Pointer to the length map. |
278 | 275 |
const LengthMap *length; |
279 | 276 |
//Pointer to the map of predecessors arcs. |
280 | 277 |
PredMap *_pred; |
281 | 278 |
//Indicates if _pred is locally allocated (true) or not. |
282 | 279 |
bool local_pred; |
283 | 280 |
//Pointer to the map of distances. |
284 | 281 |
DistMap *_dist; |
285 | 282 |
//Indicates if _dist is locally allocated (true) or not. |
286 | 283 |
bool local_dist; |
287 | 284 |
//Pointer to the map of processed status of the nodes. |
288 | 285 |
ProcessedMap *_processed; |
289 | 286 |
//Indicates if _processed is locally allocated (true) or not. |
290 | 287 |
bool local_processed; |
291 | 288 |
//Pointer to the heap cross references. |
292 | 289 |
HeapCrossRef *_heap_cross_ref; |
293 | 290 |
//Indicates if _heap_cross_ref is locally allocated (true) or not. |
294 | 291 |
bool local_heap_cross_ref; |
295 | 292 |
//Pointer to the heap. |
296 | 293 |
Heap *_heap; |
297 | 294 |
//Indicates if _heap is locally allocated (true) or not. |
298 | 295 |
bool local_heap; |
299 | 296 |
|
300 |
///Creates the maps if necessary. |
|
301 |
///\todo Better memory allocation (instead of new). |
|
297 |
//Creates the maps if necessary. |
|
302 | 298 |
void create_maps() |
303 | 299 |
{ |
304 | 300 |
if(!_pred) { |
305 | 301 |
local_pred = true; |
306 | 302 |
_pred = Traits::createPredMap(*G); |
307 | 303 |
} |
308 | 304 |
if(!_dist) { |
309 | 305 |
local_dist = true; |
310 | 306 |
_dist = Traits::createDistMap(*G); |
311 | 307 |
} |
312 | 308 |
if(!_processed) { |
313 | 309 |
local_processed = true; |
314 | 310 |
_processed = Traits::createProcessedMap(*G); |
315 | 311 |
} |
316 | 312 |
if (!_heap_cross_ref) { |
317 | 313 |
local_heap_cross_ref = true; |
318 | 314 |
_heap_cross_ref = Traits::createHeapCrossRef(*G); |
319 | 315 |
} |
320 | 316 |
if (!_heap) { |
321 | 317 |
local_heap = true; |
322 | 318 |
_heap = Traits::createHeap(*_heap_cross_ref); |
323 | 319 |
} |
324 | 320 |
} |
325 | 321 |
|
326 | 322 |
public: |
327 | 323 |
|
328 | 324 |
typedef Dijkstra Create; |
329 | 325 |
|
330 | 326 |
///\name Named template parameters |
331 | 327 |
|
332 | 328 |
///@{ |
333 | 329 |
|
334 | 330 |
template <class T> |
335 | 331 |
struct SetPredMapTraits : public Traits { |
336 | 332 |
typedef T PredMap; |
337 | 333 |
static PredMap *createPredMap(const Digraph &) |
338 | 334 |
{ |
339 | 335 |
throw UninitializedParameter(); |
340 | 336 |
} |
341 | 337 |
}; |
342 | 338 |
///\brief \ref named-templ-param "Named parameter" for setting |
343 | 339 |
///\ref PredMap type. |
344 | 340 |
/// |
345 | 341 |
///\ref named-templ-param "Named parameter" for setting |
346 | 342 |
///\ref PredMap type. |
347 | 343 |
template <class T> |
348 | 344 |
struct SetPredMap |
349 | 345 |
: public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > { |
350 | 346 |
typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create; |
351 | 347 |
}; |
352 | 348 |
|
353 | 349 |
template <class T> |
354 | 350 |
struct SetDistMapTraits : public Traits { |
355 | 351 |
typedef T DistMap; |
356 | 352 |
static DistMap *createDistMap(const Digraph &) |
357 | 353 |
{ |
358 | 354 |
throw UninitializedParameter(); |
359 | 355 |
} |
360 | 356 |
}; |
361 | 357 |
///\brief \ref named-templ-param "Named parameter" for setting |
362 | 358 |
///\ref DistMap type. |
363 | 359 |
/// |
364 | 360 |
///\ref named-templ-param "Named parameter" for setting |
365 | 361 |
///\ref DistMap type. |
366 | 362 |
template <class T> |
367 | 363 |
struct SetDistMap |
368 | 364 |
: public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > { |
369 | 365 |
typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create; |
370 | 366 |
}; |
371 | 367 |
|
372 | 368 |
template <class T> |
373 | 369 |
struct SetProcessedMapTraits : public Traits { |
374 | 370 |
typedef T ProcessedMap; |
375 | 371 |
static ProcessedMap *createProcessedMap(const Digraph &) |
376 | 372 |
{ |
377 | 373 |
throw UninitializedParameter(); |
378 | 374 |
} |
379 | 375 |
}; |
380 | 376 |
///\brief \ref named-templ-param "Named parameter" for setting |
381 | 377 |
///\ref ProcessedMap type. |
382 | 378 |
/// |
383 | 379 |
///\ref named-templ-param "Named parameter" for setting |
384 | 380 |
///\ref ProcessedMap type. |
385 | 381 |
template <class T> |
386 | 382 |
struct SetProcessedMap |
387 | 383 |
: public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > { |
388 | 384 |
typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create; |
389 | 385 |
}; |
390 | 386 |
|
391 | 387 |
struct SetStandardProcessedMapTraits : public Traits { |
392 | 388 |
typedef typename Digraph::template NodeMap<bool> ProcessedMap; |
393 | 389 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
394 | 390 |
{ |
395 | 391 |
return new ProcessedMap(g); |
396 | 392 |
} |
397 | 393 |
}; |
398 | 394 |
///\brief \ref named-templ-param "Named parameter" for setting |
399 | 395 |
///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>. |
400 | 396 |
/// |
401 | 397 |
///\ref named-templ-param "Named parameter" for setting |
402 | 398 |
///\ref ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>. |
403 | 399 |
///If you don't set it explicitly, it will be automatically allocated. |
404 | 400 |
struct SetStandardProcessedMap |
405 | 401 |
: public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > { |
406 | 402 |
typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > |
407 | 403 |
Create; |
408 | 404 |
}; |
409 | 405 |
|
410 | 406 |
template <class H, class CR> |
411 | 407 |
struct SetHeapTraits : public Traits { |
412 | 408 |
typedef CR HeapCrossRef; |
413 | 409 |
typedef H Heap; |
414 | 410 |
static HeapCrossRef *createHeapCrossRef(const Digraph &) { |
415 | 411 |
throw UninitializedParameter(); |
416 | 412 |
} |
417 | 413 |
static Heap *createHeap(HeapCrossRef &) |
418 | 414 |
{ |
419 | 415 |
throw UninitializedParameter(); |
420 | 416 |
} |
421 | 417 |
}; |
422 | 418 |
///\brief \ref named-templ-param "Named parameter" for setting |
423 | 419 |
///heap and cross reference type |
424 | 420 |
/// |
425 | 421 |
///\ref named-templ-param "Named parameter" for setting heap and cross |
426 | 422 |
///reference type. |
427 | 423 |
template <class H, class CR = typename Digraph::template NodeMap<int> > |
428 | 424 |
struct SetHeap |
429 | 425 |
: public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > { |
430 | 426 |
typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create; |
431 | 427 |
}; |
432 | 428 |
|
433 | 429 |
template <class H, class CR> |
434 | 430 |
struct SetStandardHeapTraits : public Traits { |
435 | 431 |
typedef CR HeapCrossRef; |
436 | 432 |
typedef H Heap; |
437 | 433 |
static HeapCrossRef *createHeapCrossRef(const Digraph &G) { |
438 | 434 |
return new HeapCrossRef(G); |
439 | 435 |
} |
440 | 436 |
static Heap *createHeap(HeapCrossRef &R) |
441 | 437 |
{ |
442 | 438 |
return new Heap(R); |
443 | 439 |
} |
444 | 440 |
}; |
445 | 441 |
///\brief \ref named-templ-param "Named parameter" for setting |
446 | 442 |
///heap and cross reference type with automatic allocation |
447 | 443 |
/// |
448 | 444 |
///\ref named-templ-param "Named parameter" for setting heap and cross |
449 | 445 |
///reference type. It can allocate the heap and the cross reference |
450 | 446 |
///object if the cross reference's constructor waits for the digraph as |
451 | 447 |
///parameter and the heap's constructor waits for the cross reference. |
452 | 448 |
template <class H, class CR = typename Digraph::template NodeMap<int> > |
453 | 449 |
struct SetStandardHeap |
454 | 450 |
: public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > { |
455 | 451 |
typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > |
456 | 452 |
Create; |
457 | 453 |
}; |
458 | 454 |
|
459 | 455 |
template <class T> |
460 | 456 |
struct SetOperationTraitsTraits : public Traits { |
461 | 457 |
typedef T OperationTraits; |
462 | 458 |
}; |
463 | 459 |
|
464 | 460 |
/// \brief \ref named-templ-param "Named parameter" for setting |
465 | 461 |
///\ref OperationTraits type |
466 | 462 |
/// |
467 | 463 |
///\ref named-templ-param "Named parameter" for setting |
468 | 464 |
///\ref OperationTraits type. |
469 | 465 |
template <class T> |
470 | 466 |
struct SetOperationTraits |
471 | 467 |
: public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > { |
472 | 468 |
typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > |
473 | 469 |
Create; |
474 | 470 |
}; |
475 | 471 |
|
476 | 472 |
///@} |
477 | 473 |
|
478 | 474 |
protected: |
479 | 475 |
|
480 | 476 |
Dijkstra() {} |
481 | 477 |
|
482 | 478 |
public: |
483 | 479 |
|
484 | 480 |
///Constructor. |
485 | 481 |
|
486 | 482 |
///Constructor. |
487 | 483 |
///\param _g The digraph the algorithm runs on. |
488 | 484 |
///\param _length The length map used by the algorithm. |
489 | 485 |
Dijkstra(const Digraph& _g, const LengthMap& _length) : |
490 | 486 |
G(&_g), length(&_length), |
491 | 487 |
_pred(NULL), local_pred(false), |
492 | 488 |
_dist(NULL), local_dist(false), |
493 | 489 |
_processed(NULL), local_processed(false), |
494 | 490 |
_heap_cross_ref(NULL), local_heap_cross_ref(false), |
495 | 491 |
_heap(NULL), local_heap(false) |
496 | 492 |
{ } |
497 | 493 |
|
498 | 494 |
///Destructor. |
499 | 495 |
~Dijkstra() |
500 | 496 |
{ |
501 | 497 |
if(local_pred) delete _pred; |
502 | 498 |
if(local_dist) delete _dist; |
503 | 499 |
if(local_processed) delete _processed; |
504 | 500 |
if(local_heap_cross_ref) delete _heap_cross_ref; |
505 | 501 |
if(local_heap) delete _heap; |
506 | 502 |
} |
507 | 503 |
|
508 | 504 |
///Sets the length map. |
509 | 505 |
|
510 | 506 |
///Sets the length map. |
511 | 507 |
///\return <tt> (*this) </tt> |
512 | 508 |
Dijkstra &lengthMap(const LengthMap &m) |
513 | 509 |
{ |
514 | 510 |
length = &m; |
515 | 511 |
return *this; |
516 | 512 |
} |
517 | 513 |
|
518 | 514 |
///Sets the map that stores the predecessor arcs. |
519 | 515 |
|
520 | 516 |
///Sets the map that stores the predecessor arcs. |
521 | 517 |
///If you don't use this function before calling \ref run(), |
522 | 518 |
///it will allocate one. The destructor deallocates this |
523 | 519 |
///automatically allocated map, of course. |
524 | 520 |
///\return <tt> (*this) </tt> |
525 | 521 |
Dijkstra &predMap(PredMap &m) |
526 | 522 |
{ |
527 | 523 |
if(local_pred) { |
528 | 524 |
delete _pred; |
529 | 525 |
local_pred=false; |
530 | 526 |
} |
531 | 527 |
_pred = &m; |
532 | 528 |
return *this; |
533 | 529 |
} |
534 | 530 |
|
535 | 531 |
///Sets the map that indicates which nodes are processed. |
536 | 532 |
|
537 | 533 |
///Sets the map that indicates which nodes are processed. |
538 | 534 |
///If you don't use this function before calling \ref run(), |
539 | 535 |
///it will allocate one. The destructor deallocates this |
540 | 536 |
///automatically allocated map, of course. |
541 | 537 |
///\return <tt> (*this) </tt> |
542 | 538 |
Dijkstra &processedMap(ProcessedMap &m) |
543 | 539 |
{ |
544 | 540 |
if(local_processed) { |
545 | 541 |
delete _processed; |
546 | 542 |
local_processed=false; |
547 | 543 |
} |
548 | 544 |
_processed = &m; |
549 | 545 |
return *this; |
550 | 546 |
} |
551 | 547 |
|
552 | 548 |
///Sets the map that stores the distances of the nodes. |
553 | 549 |
|
554 | 550 |
///Sets the map that stores the distances of the nodes calculated by the |
555 | 551 |
///algorithm. |
556 | 552 |
///If you don't use this function before calling \ref run(), |
557 | 553 |
///it will allocate one. The destructor deallocates this |
558 | 554 |
///automatically allocated map, of course. |
559 | 555 |
///\return <tt> (*this) </tt> |
560 | 556 |
Dijkstra &distMap(DistMap &m) |
561 | 557 |
{ |
562 | 558 |
if(local_dist) { |
563 | 559 |
delete _dist; |
564 | 560 |
local_dist=false; |
565 | 561 |
} |
566 | 562 |
_dist = &m; |
567 | 563 |
return *this; |
568 | 564 |
} |
569 | 565 |
|
570 | 566 |
///Sets the heap and the cross reference used by algorithm. |
571 | 567 |
|
572 | 568 |
///Sets the heap and the cross reference used by algorithm. |
573 | 569 |
///If you don't use this function before calling \ref run(), |
574 | 570 |
///it will allocate one. The destructor deallocates this |
575 | 571 |
///automatically allocated heap and cross reference, of course. |
576 | 572 |
///\return <tt> (*this) </tt> |
577 | 573 |
Dijkstra &heap(Heap& hp, HeapCrossRef &cr) |
578 | 574 |
{ |
579 | 575 |
if(local_heap_cross_ref) { |
580 | 576 |
delete _heap_cross_ref; |
581 | 577 |
local_heap_cross_ref=false; |
582 | 578 |
} |
583 | 579 |
_heap_cross_ref = &cr; |
584 | 580 |
if(local_heap) { |
585 | 581 |
delete _heap; |
586 | 582 |
local_heap=false; |
587 | 583 |
} |
588 | 584 |
_heap = &hp; |
589 | 585 |
return *this; |
590 | 586 |
} |
591 | 587 |
|
592 | 588 |
private: |
593 | 589 |
|
594 | 590 |
void finalizeNodeData(Node v,Value dst) |
595 | 591 |
{ |
596 | 592 |
_processed->set(v,true); |
597 | 593 |
_dist->set(v, dst); |
598 | 594 |
} |
599 | 595 |
|
600 | 596 |
public: |
601 | 597 |
|
602 | 598 |
///\name Execution control |
603 | 599 |
///The simplest way to execute the algorithm is to use one of the |
604 | 600 |
///member functions called \ref lemon::Dijkstra::run() "run()". |
605 | 601 |
///\n |
606 | 602 |
///If you need more control on the execution, first you must call |
607 | 603 |
///\ref lemon::Dijkstra::init() "init()", then you can add several |
608 | 604 |
///source nodes with \ref lemon::Dijkstra::addSource() "addSource()". |
609 | 605 |
///Finally \ref lemon::Dijkstra::start() "start()" will perform the |
610 | 606 |
///actual path computation. |
611 | 607 |
|
612 | 608 |
///@{ |
613 | 609 |
|
614 | 610 |
///Initializes the internal data structures. |
615 | 611 |
|
616 | 612 |
///Initializes the internal data structures. |
617 | 613 |
/// |
618 | 614 |
void init() |
619 | 615 |
{ |
620 | 616 |
create_maps(); |
621 | 617 |
_heap->clear(); |
622 | 618 |
for ( NodeIt u(*G) ; u!=INVALID ; ++u ) { |
623 | 619 |
_pred->set(u,INVALID); |
624 | 620 |
_processed->set(u,false); |
625 | 621 |
_heap_cross_ref->set(u,Heap::PRE_HEAP); |
626 | 622 |
} |
627 | 623 |
} |
628 | 624 |
|
629 | 625 |
///Adds a new source node. |
630 | 626 |
|
631 | 627 |
///Adds a new source node to the priority heap. |
632 | 628 |
///The optional second parameter is the initial distance of the node. |
633 | 629 |
/// |
634 | 630 |
///The function checks if the node has already been added to the heap and |
635 | 631 |
///it is pushed to the heap only if either it was not in the heap |
636 | 632 |
///or the shortest path found till then is shorter than \c dst. |
637 | 633 |
void addSource(Node s,Value dst=OperationTraits::zero()) |
638 | 634 |
{ |
639 | 635 |
if(_heap->state(s) != Heap::IN_HEAP) { |
640 | 636 |
_heap->push(s,dst); |
641 | 637 |
} else if(OperationTraits::less((*_heap)[s], dst)) { |
642 | 638 |
_heap->set(s,dst); |
643 | 639 |
_pred->set(s,INVALID); |
644 | 640 |
} |
645 | 641 |
} |
646 | 642 |
|
647 | 643 |
///Processes the next node in the priority heap |
648 | 644 |
|
649 | 645 |
///Processes the next node in the priority heap. |
650 | 646 |
/// |
651 | 647 |
///\return The processed node. |
652 | 648 |
/// |
653 | 649 |
///\warning The priority heap must not be empty. |
654 | 650 |
Node processNextNode() |
655 | 651 |
{ |
656 | 652 |
Node v=_heap->top(); |
657 | 653 |
Value oldvalue=_heap->prio(); |
658 | 654 |
_heap->pop(); |
659 | 655 |
finalizeNodeData(v,oldvalue); |
660 | 656 |
|
661 | 657 |
for(OutArcIt e(*G,v); e!=INVALID; ++e) { |
662 | 658 |
Node w=G->target(e); |
663 | 659 |
switch(_heap->state(w)) { |
664 | 660 |
case Heap::PRE_HEAP: |
665 | 661 |
_heap->push(w,OperationTraits::plus(oldvalue, (*length)[e])); |
666 | 662 |
_pred->set(w,e); |
667 | 663 |
break; |
668 | 664 |
case Heap::IN_HEAP: |
669 | 665 |
{ |
670 | 666 |
Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]); |
671 | 667 |
if ( OperationTraits::less(newvalue, (*_heap)[w]) ) { |
672 | 668 |
_heap->decrease(w, newvalue); |
673 | 669 |
_pred->set(w,e); |
674 | 670 |
} |
675 | 671 |
} |
676 | 672 |
break; |
677 | 673 |
case Heap::POST_HEAP: |
678 | 674 |
break; |
679 | 675 |
} |
680 | 676 |
} |
681 | 677 |
return v; |
682 | 678 |
} |
683 | 679 |
|
684 | 680 |
///The next node to be processed. |
685 | 681 |
|
686 | 682 |
///Returns the next node to be processed or \c INVALID if the |
687 | 683 |
///priority heap is empty. |
688 | 684 |
Node nextNode() const |
689 | 685 |
{ |
690 | 686 |
return !_heap->empty()?_heap->top():INVALID; |
691 | 687 |
} |
692 | 688 |
|
693 | 689 |
///\brief Returns \c false if there are nodes |
694 | 690 |
///to be processed. |
695 | 691 |
/// |
696 | 692 |
///Returns \c false if there are nodes |
697 | 693 |
///to be processed in the priority heap. |
698 | 694 |
bool emptyQueue() const { return _heap->empty(); } |
699 | 695 |
|
700 | 696 |
///Returns the number of the nodes to be processed in the priority heap |
701 | 697 |
|
702 | 698 |
///Returns the number of the nodes to be processed in the priority heap. |
703 | 699 |
/// |
704 | 700 |
int queueSize() const { return _heap->size(); } |
705 | 701 |
|
706 | 702 |
///Executes the algorithm. |
707 | 703 |
|
708 | 704 |
///Executes the algorithm. |
709 | 705 |
/// |
710 | 706 |
///This method runs the %Dijkstra algorithm from the root node(s) |
711 | 707 |
///in order to compute the shortest path to each node. |
712 | 708 |
/// |
713 | 709 |
///The algorithm computes |
714 | 710 |
///- the shortest path tree (forest), |
715 | 711 |
///- the distance of each node from the root(s). |
716 | 712 |
/// |
717 | 713 |
///\pre init() must be called and at least one root node should be |
718 | 714 |
///added with addSource() before using this function. |
719 | 715 |
/// |
720 | 716 |
///\note <tt>d.start()</tt> is just a shortcut of the following code. |
721 | 717 |
///\code |
722 | 718 |
/// while ( !d.emptyQueue() ) { |
723 | 719 |
/// d.processNextNode(); |
724 | 720 |
/// } |
725 | 721 |
///\endcode |
726 | 722 |
void start() |
727 | 723 |
{ |
728 | 724 |
while ( !emptyQueue() ) processNextNode(); |
729 | 725 |
} |
730 | 726 |
|
731 | 727 |
///Executes the algorithm until the given target node is reached. |
732 | 728 |
|
733 | 729 |
///Executes the algorithm until the given target node is reached. |
734 | 730 |
/// |
735 | 731 |
///This method runs the %Dijkstra algorithm from the root node(s) |
736 | 732 |
///in order to compute the shortest path to \c dest. |
737 | 733 |
/// |
738 | 734 |
///The algorithm computes |
739 | 735 |
///- the shortest path to \c dest, |
740 | 736 |
///- the distance of \c dest from the root(s). |
741 | 737 |
/// |
742 | 738 |
///\pre init() must be called and at least one root node should be |
743 | 739 |
///added with addSource() before using this function. |
744 | 740 |
void start(Node dest) |
745 | 741 |
{ |
746 | 742 |
while ( !_heap->empty() && _heap->top()!=dest ) processNextNode(); |
747 | 743 |
if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio()); |
748 | 744 |
} |
749 | 745 |
|
750 | 746 |
///Executes the algorithm until a condition is met. |
751 | 747 |
|
752 | 748 |
///Executes the algorithm until a condition is met. |
753 | 749 |
/// |
754 | 750 |
///This method runs the %Dijkstra algorithm from the root node(s) in |
755 | 751 |
///order to compute the shortest path to a node \c v with |
756 | 752 |
/// <tt>nm[v]</tt> true, if such a node can be found. |
757 | 753 |
/// |
758 | 754 |
///\param nm A \c bool (or convertible) node map. The algorithm |
759 | 755 |
///will stop when it reaches a node \c v with <tt>nm[v]</tt> true. |
760 | 756 |
/// |
761 | 757 |
///\return The reached node \c v with <tt>nm[v]</tt> true or |
762 | 758 |
///\c INVALID if no such node was found. |
763 | 759 |
/// |
764 | 760 |
///\pre init() must be called and at least one root node should be |
765 | 761 |
///added with addSource() before using this function. |
766 | 762 |
template<class NodeBoolMap> |
767 | 763 |
Node start(const NodeBoolMap &nm) |
768 | 764 |
{ |
769 | 765 |
while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode(); |
770 | 766 |
if ( _heap->empty() ) return INVALID; |
771 | 767 |
finalizeNodeData(_heap->top(),_heap->prio()); |
772 | 768 |
return _heap->top(); |
773 | 769 |
} |
774 | 770 |
|
775 | 771 |
///Runs the algorithm from the given node. |
776 | 772 |
|
777 | 773 |
///This method runs the %Dijkstra algorithm from node \c s |
778 | 774 |
///in order to compute the shortest path to each node. |
779 | 775 |
/// |
780 | 776 |
///The algorithm computes |
781 | 777 |
///- the shortest path tree, |
782 | 778 |
///- the distance of each node from the root. |
783 | 779 |
/// |
784 | 780 |
///\note <tt>d.run(s)</tt> is just a shortcut of the following code. |
785 | 781 |
///\code |
786 | 782 |
/// d.init(); |
787 | 783 |
/// d.addSource(s); |
788 | 784 |
/// d.start(); |
789 | 785 |
///\endcode |
790 | 786 |
void run(Node s) { |
791 | 787 |
init(); |
792 | 788 |
addSource(s); |
793 | 789 |
start(); |
794 | 790 |
} |
795 | 791 |
|
796 | 792 |
///Finds the shortest path between \c s and \c t. |
797 | 793 |
|
798 | 794 |
///This method runs the %Dijkstra algorithm from node \c s |
799 | 795 |
///in order to compute the shortest path to \c t. |
800 | 796 |
/// |
801 | 797 |
///\return The length of the shortest <tt>s</tt>--<tt>t</tt> path, |
802 | 798 |
///if \c t is reachable form \c s, \c 0 otherwise. |
803 | 799 |
/// |
804 | 800 |
///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a |
805 | 801 |
///shortcut of the following code. |
806 | 802 |
///\code |
807 | 803 |
/// d.init(); |
808 | 804 |
/// d.addSource(s); |
809 | 805 |
/// d.start(t); |
810 | 806 |
///\endcode |
811 | 807 |
Value run(Node s,Node t) { |
812 | 808 |
init(); |
813 | 809 |
addSource(s); |
814 | 810 |
start(t); |
815 | 811 |
return (*_pred)[t]==INVALID?OperationTraits::zero():(*_dist)[t]; |
816 | 812 |
} |
817 | 813 |
|
818 | 814 |
///@} |
819 | 815 |
|
820 | 816 |
///\name Query Functions |
821 | 817 |
///The result of the %Dijkstra algorithm can be obtained using these |
822 | 818 |
///functions.\n |
823 | 819 |
///Either \ref lemon::Dijkstra::run() "run()" or |
824 | 820 |
///\ref lemon::Dijkstra::start() "start()" must be called before |
825 | 821 |
///using them. |
826 | 822 |
|
827 | 823 |
///@{ |
828 | 824 |
|
829 | 825 |
///The shortest path to a node. |
830 | 826 |
|
831 | 827 |
///Returns the shortest path to a node. |
832 | 828 |
/// |
833 | 829 |
///\warning \c t should be reachable from the root(s). |
834 | 830 |
/// |
835 | 831 |
///\pre Either \ref run() or \ref start() must be called before |
836 | 832 |
///using this function. |
837 | 833 |
Path path(Node t) const { return Path(*G, *_pred, t); } |
838 | 834 |
|
839 | 835 |
///The distance of a node from the root(s). |
840 | 836 |
|
841 | 837 |
///Returns the distance of a node from the root(s). |
842 | 838 |
/// |
843 | 839 |
///\warning If node \c v is not reachable from the root(s), then |
844 | 840 |
///the return value of this function is undefined. |
845 | 841 |
/// |
846 | 842 |
///\pre Either \ref run() or \ref start() must be called before |
847 | 843 |
///using this function. |
848 | 844 |
Value dist(Node v) const { return (*_dist)[v]; } |
849 | 845 |
|
850 | 846 |
///Returns the 'previous arc' of the shortest path tree for a node. |
851 | 847 |
|
852 | 848 |
///This function returns the 'previous arc' of the shortest path |
853 | 849 |
///tree for the node \c v, i.e. it returns the last arc of a |
854 | 850 |
///shortest path from the root(s) to \c v. It is \c INVALID if \c v |
855 | 851 |
///is not reachable from the root(s) or if \c v is a root. |
856 | 852 |
/// |
857 | 853 |
///The shortest path tree used here is equal to the shortest path |
858 | 854 |
///tree used in \ref predNode(). |
859 | 855 |
/// |
860 | 856 |
///\pre Either \ref run() or \ref start() must be called before |
861 | 857 |
///using this function. |
862 | 858 |
Arc predArc(Node v) const { return (*_pred)[v]; } |
863 | 859 |
|
864 | 860 |
///Returns the 'previous node' of the shortest path tree for a node. |
865 | 861 |
|
866 | 862 |
///This function returns the 'previous node' of the shortest path |
867 | 863 |
///tree for the node \c v, i.e. it returns the last but one node |
868 | 864 |
///from a shortest path from the root(s) to \c v. It is \c INVALID |
869 | 865 |
///if \c v is not reachable from the root(s) or if \c v is a root. |
870 | 866 |
/// |
871 | 867 |
///The shortest path tree used here is equal to the shortest path |
872 | 868 |
///tree used in \ref predArc(). |
873 | 869 |
/// |
874 | 870 |
///\pre Either \ref run() or \ref start() must be called before |
875 | 871 |
///using this function. |
876 | 872 |
Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID: |
877 | 873 |
G->source((*_pred)[v]); } |
878 | 874 |
|
879 | 875 |
///\brief Returns a const reference to the node map that stores the |
880 | 876 |
///distances of the nodes. |
881 | 877 |
/// |
882 | 878 |
///Returns a const reference to the node map that stores the distances |
883 | 879 |
///of the nodes calculated by the algorithm. |
884 | 880 |
/// |
885 | 881 |
///\pre Either \ref run() or \ref init() |
886 | 882 |
///must be called before using this function. |
887 | 883 |
const DistMap &distMap() const { return *_dist;} |
888 | 884 |
|
889 | 885 |
///\brief Returns a const reference to the node map that stores the |
890 | 886 |
///predecessor arcs. |
891 | 887 |
/// |
892 | 888 |
///Returns a const reference to the node map that stores the predecessor |
893 | 889 |
///arcs, which form the shortest path tree. |
894 | 890 |
/// |
895 | 891 |
///\pre Either \ref run() or \ref init() |
896 | 892 |
///must be called before using this function. |
897 | 893 |
const PredMap &predMap() const { return *_pred;} |
898 | 894 |
|
899 | 895 |
///Checks if a node is reachable from the root(s). |
900 | 896 |
|
901 | 897 |
///Returns \c true if \c v is reachable from the root(s). |
902 | 898 |
///\pre Either \ref run() or \ref start() |
903 | 899 |
///must be called before using this function. |
904 | 900 |
bool reached(Node v) const { return (*_heap_cross_ref)[v] != |
905 | 901 |
Heap::PRE_HEAP; } |
906 | 902 |
|
907 | 903 |
///Checks if a node is processed. |
908 | 904 |
|
909 | 905 |
///Returns \c true if \c v is processed, i.e. the shortest |
910 | 906 |
///path to \c v has already found. |
911 | 907 |
///\pre Either \ref run() or \ref start() |
912 | 908 |
///must be called before using this function. |
913 | 909 |
bool processed(Node v) const { return (*_heap_cross_ref)[v] == |
914 | 910 |
Heap::POST_HEAP; } |
915 | 911 |
|
916 | 912 |
///The current distance of a node from the root(s). |
917 | 913 |
|
918 | 914 |
///Returns the current distance of a node from the root(s). |
919 | 915 |
///It may be decreased in the following processes. |
920 | 916 |
///\pre \c v should be reached but not processed. |
921 | 917 |
Value currentDist(Node v) const { return (*_heap)[v]; } |
922 | 918 |
|
923 | 919 |
///@} |
924 | 920 |
}; |
925 | 921 |
|
926 | 922 |
|
927 | 923 |
///Default traits class of dijkstra() function. |
928 | 924 |
|
929 | 925 |
///Default traits class of dijkstra() function. |
930 | 926 |
///\tparam GR The type of the digraph. |
931 | 927 |
///\tparam LM The type of the length map. |
932 | 928 |
template<class GR, class LM> |
933 | 929 |
struct DijkstraWizardDefaultTraits |
934 | 930 |
{ |
935 | 931 |
///The type of the digraph the algorithm runs on. |
936 | 932 |
typedef GR Digraph; |
937 | 933 |
///The type of the map that stores the arc lengths. |
938 | 934 |
|
939 | 935 |
///The type of the map that stores the arc lengths. |
940 | 936 |
///It must meet the \ref concepts::ReadMap "ReadMap" concept. |
941 | 937 |
typedef LM LengthMap; |
942 | 938 |
///The type of the length of the arcs. |
943 | 939 |
typedef typename LM::Value Value; |
944 | 940 |
|
945 | 941 |
/// Operation traits for Dijkstra algorithm. |
946 | 942 |
|
947 | 943 |
/// This class defines the operations that are used in the algorithm. |
948 | 944 |
/// \see DijkstraDefaultOperationTraits |
949 | 945 |
typedef DijkstraDefaultOperationTraits<Value> OperationTraits; |
950 | 946 |
|
951 | 947 |
/// The cross reference type used by the heap. |
952 | 948 |
|
953 | 949 |
/// The cross reference type used by the heap. |
954 | 950 |
/// Usually it is \c Digraph::NodeMap<int>. |
955 | 951 |
typedef typename Digraph::template NodeMap<int> HeapCrossRef; |
956 | 952 |
///Instantiates a \ref HeapCrossRef. |
957 | 953 |
|
958 | 954 |
///This function instantiates a \ref HeapCrossRef. |
959 | 955 |
/// \param g is the digraph, to which we would like to define the |
960 | 956 |
/// HeapCrossRef. |
961 |
/// \todo The digraph alone may be insufficient for the initialization |
|
962 | 957 |
static HeapCrossRef *createHeapCrossRef(const Digraph &g) |
963 | 958 |
{ |
964 | 959 |
return new HeapCrossRef(g); |
965 | 960 |
} |
966 | 961 |
|
967 | 962 |
///The heap type used by the Dijkstra algorithm. |
968 | 963 |
|
969 | 964 |
///The heap type used by the Dijkstra algorithm. |
970 | 965 |
/// |
971 | 966 |
///\sa BinHeap |
972 | 967 |
///\sa Dijkstra |
973 | 968 |
typedef BinHeap<Value, typename Digraph::template NodeMap<int>, |
974 | 969 |
std::less<Value> > Heap; |
975 | 970 |
|
976 | 971 |
///Instantiates a \ref Heap. |
977 | 972 |
|
978 | 973 |
///This function instantiates a \ref Heap. |
979 | 974 |
/// \param r is the HeapCrossRef which is used. |
980 | 975 |
static Heap *createHeap(HeapCrossRef& r) |
981 | 976 |
{ |
982 | 977 |
return new Heap(r); |
983 | 978 |
} |
984 | 979 |
|
985 | 980 |
///\brief The type of the map that stores the predecessor |
986 | 981 |
///arcs of the shortest paths. |
987 | 982 |
/// |
988 | 983 |
///The type of the map that stores the predecessor |
989 | 984 |
///arcs of the shortest paths. |
990 | 985 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
991 | 986 |
typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap; |
992 | 987 |
///Instantiates a \ref PredMap. |
993 | 988 |
|
994 | 989 |
///This function instantiates a \ref PredMap. |
995 | 990 |
///\param g is the digraph, to which we would like to define the |
996 | 991 |
///\ref PredMap. |
997 |
///\todo The digraph alone may be insufficient to initialize |
|
998 | 992 |
static PredMap *createPredMap(const Digraph &g) |
999 | 993 |
{ |
1000 | 994 |
return new PredMap(g); |
1001 | 995 |
} |
1002 | 996 |
|
1003 | 997 |
///The type of the map that indicates which nodes are processed. |
1004 | 998 |
|
1005 | 999 |
///The type of the map that indicates which nodes are processed. |
1006 | 1000 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
1007 | 1001 |
///By default it is a NullMap. |
1008 |
///\todo If it is set to a real map, |
|
1009 |
///Dijkstra::processed() should read this. |
|
1010 |
///\todo named parameter to set this type, function to read and write. |
|
1011 | 1002 |
typedef NullMap<typename Digraph::Node,bool> ProcessedMap; |
1012 | 1003 |
///Instantiates a \ref ProcessedMap. |
1013 | 1004 |
|
1014 | 1005 |
///This function instantiates a \ref ProcessedMap. |
1015 | 1006 |
///\param g is the digraph, to which |
1016 | 1007 |
///we would like to define the \ref ProcessedMap. |
1017 | 1008 |
#ifdef DOXYGEN |
1018 | 1009 |
static ProcessedMap *createProcessedMap(const Digraph &g) |
1019 | 1010 |
#else |
1020 | 1011 |
static ProcessedMap *createProcessedMap(const Digraph &) |
1021 | 1012 |
#endif |
1022 | 1013 |
{ |
1023 | 1014 |
return new ProcessedMap(); |
1024 | 1015 |
} |
1025 | 1016 |
|
1026 | 1017 |
///The type of the map that stores the distances of the nodes. |
1027 | 1018 |
|
1028 | 1019 |
///The type of the map that stores the distances of the nodes. |
1029 | 1020 |
///It must meet the \ref concepts::WriteMap "WriteMap" concept. |
1030 | 1021 |
typedef typename Digraph::template NodeMap<typename LM::Value> DistMap; |
1031 | 1022 |
///Instantiates a \ref DistMap. |
1032 | 1023 |
|
1033 | 1024 |
///This function instantiates a \ref DistMap. |
1034 | 1025 |
///\param g is the digraph, to which we would like to define |
1035 | 1026 |
///the \ref DistMap |
1036 | 1027 |
static DistMap *createDistMap(const Digraph &g) |
1037 | 1028 |
{ |
1038 | 1029 |
return new DistMap(g); |
1039 | 1030 |
} |
1040 | 1031 |
|
1041 | 1032 |
///The type of the shortest paths. |
1042 | 1033 |
|
1043 | 1034 |
///The type of the shortest paths. |
1044 | 1035 |
///It must meet the \ref concepts::Path "Path" concept. |
1045 | 1036 |
typedef lemon::Path<Digraph> Path; |
1046 | 1037 |
}; |
1047 | 1038 |
|
1048 | 1039 |
/// Default traits class used by \ref DijkstraWizard |
1049 | 1040 |
|
1050 | 1041 |
/// To make it easier to use Dijkstra algorithm |
1051 | 1042 |
/// we have created a wizard class. |
1052 | 1043 |
/// This \ref DijkstraWizard class needs default traits, |
1053 | 1044 |
/// as well as the \ref Dijkstra class. |
1054 | 1045 |
/// The \ref DijkstraWizardBase is a class to be the default traits of the |
1055 | 1046 |
/// \ref DijkstraWizard class. |
1056 |
/// \todo More named parameters are required... |
|
1057 | 1047 |
template<class GR,class LM> |
1058 | 1048 |
class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM> |
1059 | 1049 |
{ |
1060 | 1050 |
typedef DijkstraWizardDefaultTraits<GR,LM> Base; |
1061 | 1051 |
protected: |
1062 | 1052 |
//The type of the nodes in the digraph. |
1063 | 1053 |
typedef typename Base::Digraph::Node Node; |
1064 | 1054 |
|
1065 | 1055 |
//Pointer to the digraph the algorithm runs on. |
1066 | 1056 |
void *_g; |
1067 | 1057 |
//Pointer to the length map. |
1068 | 1058 |
void *_length; |
1069 | 1059 |
//Pointer to the map of processed nodes. |
1070 | 1060 |
void *_processed; |
1071 | 1061 |
//Pointer to the map of predecessors arcs. |
1072 | 1062 |
void *_pred; |
1073 | 1063 |
//Pointer to the map of distances. |
1074 | 1064 |
void *_dist; |
1075 | 1065 |
//Pointer to the shortest path to the target node. |
1076 | 1066 |
void *_path; |
1077 | 1067 |
//Pointer to the distance of the target node. |
1078 | 1068 |
void *_di; |
1079 | 1069 |
|
1080 | 1070 |
public: |
1081 | 1071 |
/// Constructor. |
1082 | 1072 |
|
1083 | 1073 |
/// This constructor does not require parameters, therefore it initiates |
1084 | 1074 |
/// all of the attributes to \c 0. |
1085 | 1075 |
DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0), |
1086 | 1076 |
_dist(0), _path(0), _di(0) {} |
1087 | 1077 |
|
1088 | 1078 |
/// Constructor. |
1089 | 1079 |
|
1090 | 1080 |
/// This constructor requires two parameters, |
1091 | 1081 |
/// others are initiated to \c 0. |
1092 | 1082 |
/// \param g The digraph the algorithm runs on. |
1093 | 1083 |
/// \param l The length map. |
1094 | 1084 |
DijkstraWizardBase(const GR &g,const LM &l) : |
1095 | 1085 |
_g(reinterpret_cast<void*>(const_cast<GR*>(&g))), |
1096 | 1086 |
_length(reinterpret_cast<void*>(const_cast<LM*>(&l))), |
1097 | 1087 |
_processed(0), _pred(0), _dist(0), _path(0), _di(0) {} |
1098 | 1088 |
|
1099 | 1089 |
}; |
1100 | 1090 |
|
1101 | 1091 |
/// Auxiliary class for the function-type interface of Dijkstra algorithm. |
1102 | 1092 |
|
1103 | 1093 |
/// This auxiliary class is created to implement the |
1104 | 1094 |
/// \ref dijkstra() "function-type interface" of \ref Dijkstra algorithm. |
1105 | 1095 |
/// It does not have own \ref run() method, it uses the functions |
1106 | 1096 |
/// and features of the plain \ref Dijkstra. |
1107 | 1097 |
/// |
1108 | 1098 |
/// This class should only be used through the \ref dijkstra() function, |
1109 | 1099 |
/// which makes it easier to use the algorithm. |
1110 | 1100 |
template<class TR> |
1111 | 1101 |
class DijkstraWizard : public TR |
1112 | 1102 |
{ |
1113 | 1103 |
typedef TR Base; |
1114 | 1104 |
|
1115 | 1105 |
///The type of the digraph the algorithm runs on. |
1116 | 1106 |
typedef typename TR::Digraph Digraph; |
1117 | 1107 |
|
1118 | 1108 |
typedef typename Digraph::Node Node; |
1119 | 1109 |
typedef typename Digraph::NodeIt NodeIt; |
1120 | 1110 |
typedef typename Digraph::Arc Arc; |
1121 | 1111 |
typedef typename Digraph::OutArcIt OutArcIt; |
1122 | 1112 |
|
1123 | 1113 |
///The type of the map that stores the arc lengths. |
1124 | 1114 |
typedef typename TR::LengthMap LengthMap; |
1125 | 1115 |
///The type of the length of the arcs. |
1126 | 1116 |
typedef typename LengthMap::Value Value; |
1127 | 1117 |
///\brief The type of the map that stores the predecessor |
1128 | 1118 |
///arcs of the shortest paths. |
1129 | 1119 |
typedef typename TR::PredMap PredMap; |
1130 | 1120 |
///The type of the map that stores the distances of the nodes. |
1131 | 1121 |
typedef typename TR::DistMap DistMap; |
1132 | 1122 |
///The type of the map that indicates which nodes are processed. |
1133 | 1123 |
typedef typename TR::ProcessedMap ProcessedMap; |
1134 | 1124 |
///The type of the shortest paths |
1135 | 1125 |
typedef typename TR::Path Path; |
1136 | 1126 |
///The heap type used by the dijkstra algorithm. |
1137 | 1127 |
typedef typename TR::Heap Heap; |
1138 | 1128 |
|
1139 | 1129 |
public: |
1140 | 1130 |
|
1141 | 1131 |
/// Constructor. |
1142 | 1132 |
DijkstraWizard() : TR() {} |
1143 | 1133 |
|
1144 | 1134 |
/// Constructor that requires parameters. |
1145 | 1135 |
|
1146 | 1136 |
/// Constructor that requires parameters. |
1147 | 1137 |
/// These parameters will be the default values for the traits class. |
1148 | 1138 |
/// \param g The digraph the algorithm runs on. |
1149 | 1139 |
/// \param l The length map. |
1150 | 1140 |
DijkstraWizard(const Digraph &g, const LengthMap &l) : |
1151 | 1141 |
TR(g,l) {} |
1152 | 1142 |
|
1153 | 1143 |
///Copy constructor |
1154 | 1144 |
DijkstraWizard(const TR &b) : TR(b) {} |
1155 | 1145 |
|
1156 | 1146 |
~DijkstraWizard() {} |
1157 | 1147 |
|
1158 | 1148 |
///Runs Dijkstra algorithm from the given source node. |
1159 | 1149 |
|
1160 | 1150 |
///This method runs %Dijkstra algorithm from the given source node |
1161 | 1151 |
///in order to compute the shortest path to each node. |
1162 | 1152 |
void run(Node s) |
1163 | 1153 |
{ |
1164 | 1154 |
if (s==INVALID) throw UninitializedParameter(); |
1165 | 1155 |
Dijkstra<Digraph,LengthMap,TR> |
1166 | 1156 |
dijk(*reinterpret_cast<const Digraph*>(Base::_g), |
1167 | 1157 |
*reinterpret_cast<const LengthMap*>(Base::_length)); |
1168 | 1158 |
if (Base::_pred) |
1169 | 1159 |
dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); |
1170 | 1160 |
if (Base::_dist) |
1171 | 1161 |
dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); |
1172 | 1162 |
if (Base::_processed) |
1173 | 1163 |
dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed)); |
1174 | 1164 |
dijk.run(s); |
1175 | 1165 |
} |
1176 | 1166 |
|
1177 | 1167 |
///Finds the shortest path between \c s and \c t. |
1178 | 1168 |
|
1179 | 1169 |
///This method runs the %Dijkstra algorithm from node \c s |
1180 | 1170 |
///in order to compute the shortest path to node \c t |
1181 | 1171 |
///(it stops searching when \c t is processed). |
1182 | 1172 |
/// |
1183 | 1173 |
///\return \c true if \c t is reachable form \c s. |
1184 | 1174 |
bool run(Node s, Node t) |
1185 | 1175 |
{ |
1186 | 1176 |
if (s==INVALID || t==INVALID) throw UninitializedParameter(); |
1187 | 1177 |
Dijkstra<Digraph,LengthMap,TR> |
1188 | 1178 |
dijk(*reinterpret_cast<const Digraph*>(Base::_g), |
1189 | 1179 |
*reinterpret_cast<const LengthMap*>(Base::_length)); |
1190 | 1180 |
if (Base::_pred) |
1191 | 1181 |
dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred)); |
1192 | 1182 |
if (Base::_dist) |
1193 | 1183 |
dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist)); |
1194 | 1184 |
if (Base::_processed) |
1195 | 1185 |
dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed)); |
1196 | 1186 |
dijk.run(s,t); |
1197 | 1187 |
if (Base::_path) |
1198 | 1188 |
*reinterpret_cast<Path*>(Base::_path) = dijk.path(t); |
1199 | 1189 |
if (Base::_di) |
1200 | 1190 |
*reinterpret_cast<Value*>(Base::_di) = dijk.dist(t); |
1201 | 1191 |
return dijk.reached(t); |
1202 | 1192 |
} |
1203 | 1193 |
|
1204 | 1194 |
template<class T> |
1205 | 1195 |
struct SetPredMapBase : public Base { |
1206 | 1196 |
typedef T PredMap; |
1207 | 1197 |
static PredMap *createPredMap(const Digraph &) { return 0; }; |
1208 | 1198 |
SetPredMapBase(const TR &b) : TR(b) {} |
1209 | 1199 |
}; |
1210 | 1200 |
///\brief \ref named-func-param "Named parameter" |
1211 | 1201 |
///for setting \ref PredMap object. |
1212 | 1202 |
/// |
1213 | 1203 |
///\ref named-func-param "Named parameter" |
1214 | 1204 |
///for setting \ref PredMap object. |
1215 | 1205 |
template<class T> |
1216 | 1206 |
DijkstraWizard<SetPredMapBase<T> > predMap(const T &t) |
1217 | 1207 |
{ |
1218 | 1208 |
Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1219 | 1209 |
return DijkstraWizard<SetPredMapBase<T> >(*this); |
1220 | 1210 |
} |
1221 | 1211 |
|
1222 | 1212 |
template<class T> |
1223 | 1213 |
struct SetDistMapBase : public Base { |
1224 | 1214 |
typedef T DistMap; |
1225 | 1215 |
static DistMap *createDistMap(const Digraph &) { return 0; }; |
1226 | 1216 |
SetDistMapBase(const TR &b) : TR(b) {} |
1227 | 1217 |
}; |
1228 | 1218 |
///\brief \ref named-func-param "Named parameter" |
1229 | 1219 |
///for setting \ref DistMap object. |
1230 | 1220 |
/// |
1231 | 1221 |
///\ref named-func-param "Named parameter" |
1232 | 1222 |
///for setting \ref DistMap object. |
1233 | 1223 |
template<class T> |
1234 | 1224 |
DijkstraWizard<SetDistMapBase<T> > distMap(const T &t) |
1235 | 1225 |
{ |
1236 | 1226 |
Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1237 | 1227 |
return DijkstraWizard<SetDistMapBase<T> >(*this); |
1238 | 1228 |
} |
1239 | 1229 |
|
1240 | 1230 |
template<class T> |
1241 | 1231 |
struct SetProcessedMapBase : public Base { |
1242 | 1232 |
typedef T ProcessedMap; |
1243 | 1233 |
static ProcessedMap *createProcessedMap(const Digraph &) { return 0; }; |
1244 | 1234 |
SetProcessedMapBase(const TR &b) : TR(b) {} |
1245 | 1235 |
}; |
1246 | 1236 |
///\brief \ref named-func-param "Named parameter" |
1247 | 1237 |
///for setting \ref ProcessedMap object. |
1248 | 1238 |
/// |
1249 | 1239 |
/// \ref named-func-param "Named parameter" |
1250 | 1240 |
///for setting \ref ProcessedMap object. |
1251 | 1241 |
template<class T> |
1252 | 1242 |
DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t) |
1253 | 1243 |
{ |
1254 | 1244 |
Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1255 | 1245 |
return DijkstraWizard<SetProcessedMapBase<T> >(*this); |
1256 | 1246 |
} |
1257 | 1247 |
|
1258 | 1248 |
template<class T> |
1259 | 1249 |
struct SetPathBase : public Base { |
1260 | 1250 |
typedef T Path; |
1261 | 1251 |
SetPathBase(const TR &b) : TR(b) {} |
1262 | 1252 |
}; |
1263 | 1253 |
///\brief \ref named-func-param "Named parameter" |
1264 | 1254 |
///for getting the shortest path to the target node. |
1265 | 1255 |
/// |
1266 | 1256 |
///\ref named-func-param "Named parameter" |
1267 | 1257 |
///for getting the shortest path to the target node. |
1268 | 1258 |
template<class T> |
1269 | 1259 |
DijkstraWizard<SetPathBase<T> > path(const T &t) |
1270 | 1260 |
{ |
1271 | 1261 |
Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t)); |
1272 | 1262 |
return DijkstraWizard<SetPathBase<T> >(*this); |
1273 | 1263 |
} |
1274 | 1264 |
|
1275 | 1265 |
///\brief \ref named-func-param "Named parameter" |
1276 | 1266 |
///for getting the distance of the target node. |
1277 | 1267 |
/// |
1278 | 1268 |
///\ref named-func-param "Named parameter" |
1279 | 1269 |
///for getting the distance of the target node. |
1280 | 1270 |
DijkstraWizard dist(const Value &d) |
1281 | 1271 |
{ |
1282 | 1272 |
Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d)); |
1283 | 1273 |
return *this; |
1284 | 1274 |
} |
1285 | 1275 |
|
1286 | 1276 |
}; |
1287 | 1277 |
|
1288 | 1278 |
///Function-type interface for Dijkstra algorithm. |
1289 | 1279 |
|
1290 | 1280 |
/// \ingroup shortest_path |
1291 | 1281 |
///Function-type interface for Dijkstra algorithm. |
1292 | 1282 |
/// |
1293 | 1283 |
///This function also has several \ref named-func-param "named parameters", |
1294 | 1284 |
///they are declared as the members of class \ref DijkstraWizard. |
1295 | 1285 |
///The following examples show how to use these parameters. |
1296 | 1286 |
///\code |
1297 | 1287 |
/// // Compute shortest path from node s to each node |
1298 | 1288 |
/// dijkstra(g,length).predMap(preds).distMap(dists).run(s); |
1299 | 1289 |
/// |
1300 | 1290 |
/// // Compute shortest path from s to t |
1301 | 1291 |
/// bool reached = dijkstra(g,length).path(p).dist(d).run(s,t); |
1302 | 1292 |
///\endcode |
1303 | 1293 |
///\warning Don't forget to put the \ref DijkstraWizard::run() "run()" |
1304 | 1294 |
///to the end of the parameter list. |
1305 | 1295 |
///\sa DijkstraWizard |
1306 | 1296 |
///\sa Dijkstra |
1307 | 1297 |
template<class GR, class LM> |
1308 | 1298 |
DijkstraWizard<DijkstraWizardBase<GR,LM> > |
1309 | 1299 |
dijkstra(const GR &digraph, const LM &length) |
1310 | 1300 |
{ |
1311 | 1301 |
return DijkstraWizard<DijkstraWizardBase<GR,LM> >(digraph,length); |
1312 | 1302 |
} |
1313 | 1303 |
|
1314 | 1304 |
} //END OF NAMESPACE LEMON |
1315 | 1305 |
|
1316 | 1306 |
#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-2008 |
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_ERROR_H |
20 | 20 |
#define LEMON_ERROR_H |
21 | 21 |
|
22 | 22 |
/// \ingroup exceptions |
23 | 23 |
/// \file |
24 | 24 |
/// \brief Basic exception classes and error handling. |
25 | 25 |
|
26 | 26 |
#include <exception> |
27 | 27 |
#include <string> |
28 | 28 |
#include <sstream> |
29 | 29 |
#include <iostream> |
30 | 30 |
#include <cstdlib> |
31 | 31 |
#include <memory> |
32 | 32 |
|
33 | 33 |
namespace lemon { |
34 | 34 |
|
35 | 35 |
/// \addtogroup exceptions |
36 | 36 |
/// @{ |
37 | 37 |
|
38 | 38 |
/// \brief Exception safe wrapper class. |
39 | 39 |
/// |
40 | 40 |
/// Exception safe wrapper class to implement the members of exceptions. |
41 | 41 |
template <typename _Type> |
42 | 42 |
class ExceptionMember { |
43 | 43 |
public: |
44 | 44 |
typedef _Type Type; |
45 | 45 |
|
46 | 46 |
ExceptionMember() throw() { |
47 | 47 |
try { |
48 | 48 |
ptr.reset(new Type()); |
49 | 49 |
} catch (...) {} |
50 | 50 |
} |
51 | 51 |
|
52 | 52 |
ExceptionMember(const Type& type) throw() { |
53 | 53 |
try { |
54 | 54 |
ptr.reset(new Type()); |
55 | 55 |
if (ptr.get() == 0) return; |
56 | 56 |
*ptr = type; |
57 | 57 |
} catch (...) {} |
58 | 58 |
} |
59 | 59 |
|
60 | 60 |
ExceptionMember(const ExceptionMember& copy) throw() { |
61 | 61 |
try { |
62 | 62 |
if (!copy.valid()) return; |
63 | 63 |
ptr.reset(new Type()); |
64 | 64 |
if (ptr.get() == 0) return; |
65 | 65 |
*ptr = copy.get(); |
66 | 66 |
} catch (...) {} |
67 | 67 |
} |
68 | 68 |
|
69 | 69 |
ExceptionMember& operator=(const ExceptionMember& copy) throw() { |
70 | 70 |
if (ptr.get() == 0) return; |
71 | 71 |
try { |
72 | 72 |
if (!copy.valid()) return; |
73 | 73 |
*ptr = copy.get(); |
74 | 74 |
} catch (...) {} |
75 | 75 |
} |
76 | 76 |
|
77 | 77 |
void set(const Type& type) throw() { |
78 | 78 |
if (ptr.get() == 0) return; |
79 | 79 |
try { |
80 | 80 |
*ptr = type; |
81 | 81 |
} catch (...) {} |
82 | 82 |
} |
83 | 83 |
|
84 | 84 |
const Type& get() const { |
85 | 85 |
return *ptr; |
86 | 86 |
} |
87 | 87 |
|
88 | 88 |
bool valid() const throw() { |
89 | 89 |
return ptr.get() != 0; |
90 | 90 |
} |
91 | 91 |
|
92 | 92 |
private: |
93 | 93 |
std::auto_ptr<_Type> ptr; |
94 | 94 |
}; |
95 | 95 |
|
96 | 96 |
/// Exception-safe convenient error message builder class. |
97 | 97 |
|
98 | 98 |
/// Helper class which provides a convenient ostream-like (operator << |
99 | 99 |
/// based) interface to create a string message. Mostly useful in |
100 | 100 |
/// exception classes (therefore the name). |
101 | 101 |
class ErrorMessage { |
102 | 102 |
protected: |
103 | 103 |
///\e |
104 | 104 |
|
105 |
///\todo The good solution is boost::shared_ptr... |
|
106 |
/// |
|
107 | 105 |
mutable std::auto_ptr<std::ostringstream> buf; |
108 | 106 |
|
109 | 107 |
///\e |
110 | 108 |
bool init() throw() { |
111 | 109 |
try { |
112 | 110 |
buf.reset(new std::ostringstream); |
113 | 111 |
} |
114 | 112 |
catch(...) { |
115 | 113 |
buf.reset(); |
116 | 114 |
} |
117 | 115 |
return buf.get(); |
118 | 116 |
} |
119 | 117 |
|
120 | 118 |
public: |
121 | 119 |
|
122 | 120 |
///\e |
123 | 121 |
ErrorMessage() throw() { init(); } |
124 | 122 |
|
125 | 123 |
ErrorMessage(const ErrorMessage& em) throw() : buf(em.buf) { } |
126 | 124 |
|
127 | 125 |
///\e |
128 | 126 |
ErrorMessage(const char *msg) throw() { |
129 | 127 |
init(); |
130 | 128 |
*this << msg; |
131 | 129 |
} |
132 | 130 |
|
133 | 131 |
///\e |
134 | 132 |
ErrorMessage(const std::string &msg) throw() { |
135 | 133 |
init(); |
136 | 134 |
*this << msg; |
137 | 135 |
} |
138 | 136 |
|
139 | 137 |
///\e |
140 | 138 |
template <typename T> |
141 | 139 |
ErrorMessage& operator<<(const T &t) throw() { |
142 | 140 |
if( ! buf.get() ) return *this; |
143 | 141 |
|
144 | 142 |
try { |
145 | 143 |
*buf << t; |
146 | 144 |
} |
147 | 145 |
catch(...) { |
148 | 146 |
buf.reset(); |
149 | 147 |
} |
150 | 148 |
return *this; |
151 | 149 |
} |
152 | 150 |
|
153 | 151 |
///\e |
154 | 152 |
const char* message() throw() { |
155 | 153 |
if( ! buf.get() ) return 0; |
156 | 154 |
|
157 | 155 |
const char* mes = 0; |
158 | 156 |
try { |
159 | 157 |
mes = buf->str().c_str(); |
160 | 158 |
} |
161 | 159 |
catch(...) {} |
162 | 160 |
return mes; |
163 | 161 |
} |
164 | 162 |
|
165 | 163 |
}; |
166 | 164 |
|
167 | 165 |
/// Generic exception class. |
168 | 166 |
|
169 | 167 |
/// Base class for exceptions used in LEMON. |
170 | 168 |
/// |
171 | 169 |
class Exception : public std::exception { |
172 | 170 |
public: |
173 | 171 |
///\e |
174 | 172 |
Exception() {} |
175 | 173 |
///\e |
176 | 174 |
virtual ~Exception() throw() {} |
177 | 175 |
///\e |
178 | 176 |
virtual const char* what() const throw() { |
179 | 177 |
return "lemon::Exception"; |
180 | 178 |
} |
181 | 179 |
}; |
182 | 180 |
|
183 | 181 |
/// One of the two main subclasses of \ref Exception. |
184 | 182 |
|
185 | 183 |
/// Logic errors represent problems in the internal logic of a program; |
186 | 184 |
/// in theory, these are preventable, and even detectable before the |
187 | 185 |
/// program runs (e.g. violations of class invariants). |
188 | 186 |
/// |
189 | 187 |
/// A typical example for this is \ref UninitializedParameter. |
190 | 188 |
class LogicError : public Exception { |
191 | 189 |
public: |
192 | 190 |
virtual const char* what() const throw() { |
193 | 191 |
return "lemon::LogicError"; |
194 | 192 |
} |
195 | 193 |
}; |
196 | 194 |
|
197 | 195 |
/// \ref Exception for uninitialized parameters. |
198 | 196 |
|
199 | 197 |
/// This error represents problems in the initialization |
200 | 198 |
/// of the parameters of the algorithms. |
201 | 199 |
class UninitializedParameter : public LogicError { |
202 | 200 |
public: |
203 | 201 |
virtual const char* what() const throw() { |
204 | 202 |
return "lemon::UninitializedParameter"; |
205 | 203 |
} |
206 | 204 |
}; |
207 | 205 |
|
208 | 206 |
|
209 | 207 |
/// One of the two main subclasses of \ref Exception. |
210 | 208 |
|
211 | 209 |
/// Runtime errors represent problems outside the scope of a program; |
212 | 210 |
/// they cannot be easily predicted and can generally only be caught |
213 | 211 |
/// as the program executes. |
214 | 212 |
class RuntimeError : public Exception { |
215 | 213 |
public: |
216 | 214 |
virtual const char* what() const throw() { |
217 | 215 |
return "lemon::RuntimeError"; |
218 | 216 |
} |
219 | 217 |
}; |
220 | 218 |
|
221 | 219 |
///\e |
222 | 220 |
class RangeError : public RuntimeError { |
223 | 221 |
public: |
224 | 222 |
virtual const char* what() const throw() { |
225 | 223 |
return "lemon::RangeError"; |
226 | 224 |
} |
227 | 225 |
}; |
228 | 226 |
|
229 | 227 |
///\e |
230 | 228 |
class IoError : public RuntimeError { |
231 | 229 |
public: |
232 | 230 |
virtual const char* what() const throw() { |
233 | 231 |
return "lemon::IoError"; |
234 | 232 |
} |
235 | 233 |
}; |
236 | 234 |
|
237 | 235 |
///\e |
238 | 236 |
class DataFormatError : public IoError { |
239 | 237 |
protected: |
240 | 238 |
ExceptionMember<std::string> _message; |
241 | 239 |
ExceptionMember<std::string> _file; |
242 | 240 |
int _line; |
243 | 241 |
|
244 | 242 |
mutable ExceptionMember<std::string> _message_holder; |
245 | 243 |
public: |
246 | 244 |
|
247 | 245 |
DataFormatError(const DataFormatError &dfe) : |
248 | 246 |
IoError(dfe), _message(dfe._message), _file(dfe._file), |
249 | 247 |
_line(dfe._line) {} |
250 | 248 |
|
251 | 249 |
///\e |
252 | 250 |
explicit DataFormatError(const char *the_message) |
253 | 251 |
: _message(the_message), _line(0) {} |
254 | 252 |
|
255 | 253 |
///\e |
256 | 254 |
DataFormatError(const std::string &file_name, int line_num, |
257 | 255 |
const char *the_message) |
258 | 256 |
: _message(the_message), _line(line_num) { file(file_name); } |
259 | 257 |
|
260 | 258 |
///\e |
261 | 259 |
void line(int ln) { _line = ln; } |
262 | 260 |
///\e |
263 | 261 |
void message(const std::string& msg) { _message.set(msg); } |
264 | 262 |
///\e |
265 | 263 |
void file(const std::string &fl) { _file.set(fl); } |
266 | 264 |
|
267 | 265 |
///\e |
268 | 266 |
int line() const { return _line; } |
269 | 267 |
///\e |
270 | 268 |
const char* message() const { |
271 | 269 |
if (_message.valid() && !_message.get().empty()) { |
272 | 270 |
return _message.get().c_str(); |
273 | 271 |
} else { |
274 | 272 |
return 0; |
275 | 273 |
} |
276 | 274 |
} |
277 | 275 |
|
278 | 276 |
/// \brief Returns the filename. |
279 | 277 |
/// |
280 | 278 |
/// Returns \e null if the filename was not specified. |
281 | 279 |
const char* file() const { |
282 | 280 |
if (_file.valid() && !_file.get().empty()) { |
283 | 281 |
return _file.get().c_str(); |
284 | 282 |
} else { |
285 | 283 |
return 0; |
286 | 284 |
} |
287 | 285 |
} |
288 | 286 |
|
289 | 287 |
///\e |
290 | 288 |
virtual const char* what() const throw() { |
291 | 289 |
try { |
292 | 290 |
std::ostringstream ostr; |
293 | 291 |
ostr << "lemon:DataFormatError" << ": "; |
294 | 292 |
if (message()) ostr << message(); |
295 | 293 |
if( file() || line() != 0 ) { |
296 | 294 |
ostr << " ("; |
297 | 295 |
if( file() ) ostr << "in file '" << file() << "'"; |
298 | 296 |
if( file() && line() != 0 ) ostr << " "; |
299 | 297 |
if( line() != 0 ) ostr << "at line " << line(); |
300 | 298 |
ostr << ")"; |
301 | 299 |
} |
302 | 300 |
_message_holder.set(ostr.str()); |
303 | 301 |
} |
304 | 302 |
catch (...) {} |
305 | 303 |
if( _message_holder.valid()) return _message_holder.get().c_str(); |
306 | 304 |
return "lemon:DataFormatError"; |
307 | 305 |
} |
308 | 306 |
|
309 | 307 |
virtual ~DataFormatError() throw() {} |
310 | 308 |
}; |
311 | 309 |
|
312 | 310 |
///\e |
313 | 311 |
class FileOpenError : public IoError { |
314 | 312 |
protected: |
315 | 313 |
ExceptionMember<std::string> _file; |
316 | 314 |
|
317 | 315 |
mutable ExceptionMember<std::string> _message_holder; |
318 | 316 |
public: |
319 | 317 |
|
320 | 318 |
FileOpenError(const FileOpenError &foe) : |
321 | 319 |
IoError(foe), _file(foe._file) {} |
322 | 320 |
|
323 | 321 |
///\e |
324 | 322 |
explicit FileOpenError(const std::string& fl) |
325 | 323 |
: _file(fl) {} |
326 | 324 |
|
327 | 325 |
|
328 | 326 |
///\e |
329 | 327 |
void file(const std::string &fl) { _file.set(fl); } |
330 | 328 |
|
331 | 329 |
/// \brief Returns the filename. |
332 | 330 |
/// |
333 | 331 |
/// Returns \e null if the filename was not specified. |
334 | 332 |
const char* file() const { |
335 | 333 |
if (_file.valid() && !_file.get().empty()) { |
336 | 334 |
return _file.get().c_str(); |
337 | 335 |
} else { |
338 | 336 |
return 0; |
339 | 337 |
} |
340 | 338 |
} |
341 | 339 |
|
342 | 340 |
///\e |
343 | 341 |
virtual const char* what() const throw() { |
344 | 342 |
try { |
345 | 343 |
std::ostringstream ostr; |
346 | 344 |
ostr << "lemon::FileOpenError" << ": "; |
347 | 345 |
ostr << "Cannot open file - " << file(); |
348 | 346 |
_message_holder.set(ostr.str()); |
349 | 347 |
} |
350 | 348 |
catch (...) {} |
351 | 349 |
if( _message_holder.valid()) return _message_holder.get().c_str(); |
352 | 350 |
return "lemon::FileOpenError"; |
353 | 351 |
} |
354 | 352 |
virtual ~FileOpenError() throw() {} |
355 | 353 |
}; |
356 | 354 |
|
357 | 355 |
class IoParameterError : public IoError { |
358 | 356 |
protected: |
359 | 357 |
ExceptionMember<std::string> _message; |
360 | 358 |
ExceptionMember<std::string> _file; |
361 | 359 |
|
362 | 360 |
mutable ExceptionMember<std::string> _message_holder; |
363 | 361 |
public: |
364 | 362 |
|
365 | 363 |
IoParameterError(const IoParameterError &ile) : |
366 | 364 |
IoError(ile), _message(ile._message), _file(ile._file) {} |
367 | 365 |
|
368 | 366 |
///\e |
369 | 367 |
explicit IoParameterError(const char *the_message) |
370 | 368 |
: _message(the_message) {} |
371 | 369 |
|
372 | 370 |
///\e |
373 | 371 |
IoParameterError(const char *file_name, const char *the_message) |
374 | 372 |
: _message(the_message), _file(file_name) {} |
375 | 373 |
|
376 | 374 |
///\e |
377 | 375 |
void message(const std::string& msg) { _message.set(msg); } |
378 | 376 |
///\e |
379 | 377 |
void file(const std::string &fl) { _file.set(fl); } |
380 | 378 |
|
381 | 379 |
///\e |
382 | 380 |
const char* message() const { |
383 | 381 |
if (_message.valid()) { |
384 | 382 |
return _message.get().c_str(); |
385 | 383 |
} else { |
386 | 384 |
return 0; |
387 | 385 |
} |
388 | 386 |
} |
389 | 387 |
|
390 | 388 |
/// \brief Returns the filename. |
391 | 389 |
/// |
392 | 390 |
/// Returns \c 0 if the filename was not specified. |
393 | 391 |
const char* file() const { |
394 | 392 |
if (_file.valid()) { |
395 | 393 |
return _file.get().c_str(); |
396 | 394 |
} else { |
397 | 395 |
return 0; |
398 | 396 |
} |
399 | 397 |
} |
400 | 398 |
|
401 | 399 |
///\e |
402 | 400 |
virtual const char* what() const throw() { |
403 | 401 |
try { |
404 | 402 |
std::ostringstream ostr; |
405 | 403 |
if (message()) ostr << message(); |
406 | 404 |
if (file()) ostr << "(when reading file '" << file() << "')"; |
407 | 405 |
_message_holder.set(ostr.str()); |
408 | 406 |
} |
409 | 407 |
catch (...) {} |
410 | 408 |
if( _message_holder.valid() ) return _message_holder.get().c_str(); |
411 | 409 |
return "lemon:IoParameterError"; |
412 | 410 |
} |
413 | 411 |
virtual ~IoParameterError() throw() {} |
414 | 412 |
}; |
415 | 413 |
|
416 | 414 |
/// @} |
417 | 415 |
|
418 | 416 |
} |
419 | 417 |
|
420 | 418 |
#endif // LEMON_ERROR_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-2008 |
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_GRAPH_TO_EPS_H |
20 | 20 |
#define LEMON_GRAPH_TO_EPS_H |
21 | 21 |
|
22 | 22 |
#include<iostream> |
23 | 23 |
#include<fstream> |
24 | 24 |
#include<sstream> |
25 | 25 |
#include<algorithm> |
26 | 26 |
#include<vector> |
27 | 27 |
|
28 | 28 |
#ifndef WIN32 |
29 | 29 |
#include<sys/time.h> |
30 | 30 |
#include<ctime> |
31 | 31 |
#else |
32 | 32 |
#define WIN32_LEAN_AND_MEAN |
33 | 33 |
#define NOMINMAX |
34 | 34 |
#include<windows.h> |
35 | 35 |
#endif |
36 | 36 |
|
37 | 37 |
#include<lemon/math.h> |
38 | 38 |
#include<lemon/core.h> |
39 | 39 |
#include<lemon/dim2.h> |
40 | 40 |
#include<lemon/maps.h> |
41 | 41 |
#include<lemon/color.h> |
42 | 42 |
#include<lemon/bits/bezier.h> |
43 | 43 |
|
44 | 44 |
|
45 | 45 |
///\ingroup eps_io |
46 | 46 |
///\file |
47 | 47 |
///\brief A well configurable tool for visualizing graphs |
48 | 48 |
|
49 | 49 |
namespace lemon { |
50 | 50 |
|
51 | 51 |
namespace _graph_to_eps_bits { |
52 | 52 |
template<class MT> |
53 | 53 |
class _NegY { |
54 | 54 |
public: |
55 | 55 |
typedef typename MT::Key Key; |
56 | 56 |
typedef typename MT::Value Value; |
57 | 57 |
const MT ↦ |
58 | 58 |
int yscale; |
59 | 59 |
_NegY(const MT &m,bool b) : map(m), yscale(1-b*2) {} |
60 | 60 |
Value operator[](Key n) { return Value(map[n].x,map[n].y*yscale);} |
61 | 61 |
}; |
62 | 62 |
} |
63 | 63 |
|
64 | 64 |
///Default traits class of \ref GraphToEps |
65 | 65 |
|
66 | 66 |
///Default traits class of \ref GraphToEps. |
67 | 67 |
/// |
68 | 68 |
///\c G is the type of the underlying graph. |
69 | 69 |
template<class G> |
70 | 70 |
struct DefaultGraphToEpsTraits |
71 | 71 |
{ |
72 | 72 |
typedef G Graph; |
73 | 73 |
typedef typename Graph::Node Node; |
74 | 74 |
typedef typename Graph::NodeIt NodeIt; |
75 | 75 |
typedef typename Graph::Arc Arc; |
76 | 76 |
typedef typename Graph::ArcIt ArcIt; |
77 | 77 |
typedef typename Graph::InArcIt InArcIt; |
78 | 78 |
typedef typename Graph::OutArcIt OutArcIt; |
79 | 79 |
|
80 | 80 |
|
81 | 81 |
const Graph &g; |
82 | 82 |
|
83 | 83 |
std::ostream& os; |
84 | 84 |
|
85 | 85 |
typedef ConstMap<typename Graph::Node,dim2::Point<double> > CoordsMapType; |
86 | 86 |
CoordsMapType _coords; |
87 | 87 |
ConstMap<typename Graph::Node,double > _nodeSizes; |
88 | 88 |
ConstMap<typename Graph::Node,int > _nodeShapes; |
89 | 89 |
|
90 | 90 |
ConstMap<typename Graph::Node,Color > _nodeColors; |
91 | 91 |
ConstMap<typename Graph::Arc,Color > _arcColors; |
92 | 92 |
|
93 | 93 |
ConstMap<typename Graph::Arc,double > _arcWidths; |
94 | 94 |
|
95 | 95 |
double _arcWidthScale; |
96 | 96 |
|
97 | 97 |
double _nodeScale; |
98 | 98 |
double _xBorder, _yBorder; |
99 | 99 |
double _scale; |
100 | 100 |
double _nodeBorderQuotient; |
101 | 101 |
|
102 | 102 |
bool _drawArrows; |
103 | 103 |
double _arrowLength, _arrowWidth; |
104 | 104 |
|
105 | 105 |
bool _showNodes, _showArcs; |
106 | 106 |
|
107 | 107 |
bool _enableParallel; |
108 | 108 |
double _parArcDist; |
109 | 109 |
|
110 | 110 |
bool _showNodeText; |
111 | 111 |
ConstMap<typename Graph::Node,bool > _nodeTexts; |
112 | 112 |
double _nodeTextSize; |
113 | 113 |
|
114 | 114 |
bool _showNodePsText; |
115 | 115 |
ConstMap<typename Graph::Node,bool > _nodePsTexts; |
116 | 116 |
char *_nodePsTextsPreamble; |
117 | 117 |
|
118 | 118 |
bool _undirected; |
119 | 119 |
|
120 | 120 |
bool _pleaseRemoveOsStream; |
121 | 121 |
|
122 | 122 |
bool _scaleToA4; |
123 | 123 |
|
124 | 124 |
std::string _title; |
125 | 125 |
std::string _copyright; |
126 | 126 |
|
127 | 127 |
enum NodeTextColorType |
128 | 128 |
{ DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType; |
129 | 129 |
ConstMap<typename Graph::Node,Color > _nodeTextColors; |
130 | 130 |
|
131 | 131 |
bool _autoNodeScale; |
132 | 132 |
bool _autoArcWidthScale; |
133 | 133 |
|
134 | 134 |
bool _absoluteNodeSizes; |
135 | 135 |
bool _absoluteArcWidths; |
136 | 136 |
|
137 | 137 |
bool _negY; |
138 | 138 |
|
139 | 139 |
bool _preScale; |
140 | 140 |
///Constructor |
141 | 141 |
|
142 | 142 |
///Constructor |
143 | 143 |
///\param _g Reference to the graph to be printed. |
144 | 144 |
///\param _os Reference to the output stream. |
145 | 145 |
///\param _os Reference to the output stream. |
146 | 146 |
///By default it is <tt>std::cout</tt>. |
147 | 147 |
///\param _pros If it is \c true, then the \c ostream referenced by \c _os |
148 | 148 |
///will be explicitly deallocated by the destructor. |
149 | 149 |
DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout, |
150 | 150 |
bool _pros=false) : |
151 | 151 |
g(_g), os(_os), |
152 | 152 |
_coords(dim2::Point<double>(1,1)), _nodeSizes(1), _nodeShapes(0), |
153 | 153 |
_nodeColors(WHITE), _arcColors(BLACK), |
154 | 154 |
_arcWidths(1.0), _arcWidthScale(0.003), |
155 | 155 |
_nodeScale(.01), _xBorder(10), _yBorder(10), _scale(1.0), |
156 | 156 |
_nodeBorderQuotient(.1), |
157 | 157 |
_drawArrows(false), _arrowLength(1), _arrowWidth(0.3), |
158 | 158 |
_showNodes(true), _showArcs(true), |
159 | 159 |
_enableParallel(false), _parArcDist(1), |
160 | 160 |
_showNodeText(false), _nodeTexts(false), _nodeTextSize(1), |
161 | 161 |
_showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0), |
162 | 162 |
_undirected(lemon::UndirectedTagIndicator<G>::value), |
163 | 163 |
_pleaseRemoveOsStream(_pros), _scaleToA4(false), |
164 | 164 |
_nodeTextColorType(SAME_COL), _nodeTextColors(BLACK), |
165 | 165 |
_autoNodeScale(false), |
166 | 166 |
_autoArcWidthScale(false), |
167 | 167 |
_absoluteNodeSizes(false), |
168 | 168 |
_absoluteArcWidths(false), |
169 | 169 |
_negY(false), |
170 | 170 |
_preScale(true) |
171 | 171 |
{} |
172 | 172 |
}; |
173 | 173 |
|
174 | 174 |
///Auxiliary class to implement the named parameters of \ref graphToEps() |
175 | 175 |
|
176 | 176 |
///Auxiliary class to implement the named parameters of \ref graphToEps(). |
177 | 177 |
/// |
178 | 178 |
///For detailed examples see the \ref graph_to_eps_demo.cc demo file. |
179 | 179 |
template<class T> class GraphToEps : public T |
180 | 180 |
{ |
181 | 181 |
// Can't believe it is required by the C++ standard |
182 | 182 |
using T::g; |
183 | 183 |
using T::os; |
184 | 184 |
|
185 | 185 |
using T::_coords; |
186 | 186 |
using T::_nodeSizes; |
187 | 187 |
using T::_nodeShapes; |
188 | 188 |
using T::_nodeColors; |
189 | 189 |
using T::_arcColors; |
190 | 190 |
using T::_arcWidths; |
191 | 191 |
|
192 | 192 |
using T::_arcWidthScale; |
193 | 193 |
using T::_nodeScale; |
194 | 194 |
using T::_xBorder; |
195 | 195 |
using T::_yBorder; |
196 | 196 |
using T::_scale; |
197 | 197 |
using T::_nodeBorderQuotient; |
198 | 198 |
|
199 | 199 |
using T::_drawArrows; |
200 | 200 |
using T::_arrowLength; |
201 | 201 |
using T::_arrowWidth; |
202 | 202 |
|
203 | 203 |
using T::_showNodes; |
204 | 204 |
using T::_showArcs; |
205 | 205 |
|
206 | 206 |
using T::_enableParallel; |
207 | 207 |
using T::_parArcDist; |
208 | 208 |
|
209 | 209 |
using T::_showNodeText; |
210 | 210 |
using T::_nodeTexts; |
211 | 211 |
using T::_nodeTextSize; |
212 | 212 |
|
213 | 213 |
using T::_showNodePsText; |
214 | 214 |
using T::_nodePsTexts; |
215 | 215 |
using T::_nodePsTextsPreamble; |
216 | 216 |
|
217 | 217 |
using T::_undirected; |
218 | 218 |
|
219 | 219 |
using T::_pleaseRemoveOsStream; |
220 | 220 |
|
221 | 221 |
using T::_scaleToA4; |
222 | 222 |
|
223 | 223 |
using T::_title; |
224 | 224 |
using T::_copyright; |
225 | 225 |
|
226 | 226 |
using T::NodeTextColorType; |
227 | 227 |
using T::CUST_COL; |
228 | 228 |
using T::DIST_COL; |
229 | 229 |
using T::DIST_BW; |
230 | 230 |
using T::_nodeTextColorType; |
231 | 231 |
using T::_nodeTextColors; |
232 | 232 |
|
233 | 233 |
using T::_autoNodeScale; |
234 | 234 |
using T::_autoArcWidthScale; |
235 | 235 |
|
236 | 236 |
using T::_absoluteNodeSizes; |
237 | 237 |
using T::_absoluteArcWidths; |
238 | 238 |
|
239 | 239 |
|
240 | 240 |
using T::_negY; |
241 | 241 |
using T::_preScale; |
242 | 242 |
|
243 | 243 |
// dradnats ++C eht yb deriuqer si ti eveileb t'naC |
244 | 244 |
|
245 | 245 |
typedef typename T::Graph Graph; |
246 | 246 |
typedef typename Graph::Node Node; |
247 | 247 |
typedef typename Graph::NodeIt NodeIt; |
248 | 248 |
typedef typename Graph::Arc Arc; |
249 | 249 |
typedef typename Graph::ArcIt ArcIt; |
250 | 250 |
typedef typename Graph::InArcIt InArcIt; |
251 | 251 |
typedef typename Graph::OutArcIt OutArcIt; |
252 | 252 |
|
253 | 253 |
static const int INTERPOL_PREC; |
254 | 254 |
static const double A4HEIGHT; |
255 | 255 |
static const double A4WIDTH; |
256 | 256 |
static const double A4BORDER; |
257 | 257 |
|
258 | 258 |
bool dontPrint; |
259 | 259 |
|
260 | 260 |
public: |
261 | 261 |
///Node shapes |
262 | 262 |
|
263 | 263 |
///Node shapes. |
264 | 264 |
/// |
265 | 265 |
enum NodeShapes { |
266 | 266 |
/// = 0 |
267 | 267 |
///\image html nodeshape_0.png |
268 | 268 |
///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm |
269 | 269 |
CIRCLE=0, |
270 | 270 |
/// = 1 |
271 | 271 |
///\image html nodeshape_1.png |
272 | 272 |
///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm |
273 | 273 |
/// |
274 | 274 |
SQUARE=1, |
275 | 275 |
/// = 2 |
276 | 276 |
///\image html nodeshape_2.png |
277 | 277 |
///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm |
278 | 278 |
/// |
279 | 279 |
DIAMOND=2, |
280 | 280 |
/// = 3 |
281 | 281 |
///\image html nodeshape_3.png |
282 | 282 |
///\image latex nodeshape_2.eps "MALE shape (4)" width=2cm |
283 | 283 |
/// |
284 | 284 |
MALE=3, |
285 | 285 |
/// = 4 |
286 | 286 |
///\image html nodeshape_4.png |
287 | 287 |
///\image latex nodeshape_2.eps "FEMALE shape (4)" width=2cm |
288 | 288 |
/// |
289 | 289 |
FEMALE=4 |
290 | 290 |
}; |
291 | 291 |
|
292 | 292 |
private: |
293 | 293 |
class arcLess { |
294 | 294 |
const Graph &g; |
295 | 295 |
public: |
296 | 296 |
arcLess(const Graph &_g) : g(_g) {} |
297 | 297 |
bool operator()(Arc a,Arc b) const |
298 | 298 |
{ |
299 | 299 |
Node ai=std::min(g.source(a),g.target(a)); |
300 | 300 |
Node aa=std::max(g.source(a),g.target(a)); |
301 | 301 |
Node bi=std::min(g.source(b),g.target(b)); |
302 | 302 |
Node ba=std::max(g.source(b),g.target(b)); |
303 | 303 |
return ai<bi || |
304 | 304 |
(ai==bi && (aa < ba || |
305 | 305 |
(aa==ba && ai==g.source(a) && bi==g.target(b)))); |
306 | 306 |
} |
307 | 307 |
}; |
308 | 308 |
bool isParallel(Arc e,Arc f) const |
309 | 309 |
{ |
310 | 310 |
return (g.source(e)==g.source(f)&& |
311 | 311 |
g.target(e)==g.target(f)) || |
312 | 312 |
(g.source(e)==g.target(f)&& |
313 | 313 |
g.target(e)==g.source(f)); |
314 | 314 |
} |
315 | 315 |
template<class TT> |
316 | 316 |
static std::string psOut(const dim2::Point<TT> &p) |
317 | 317 |
{ |
318 | 318 |
std::ostringstream os; |
319 | 319 |
os << p.x << ' ' << p.y; |
320 | 320 |
return os.str(); |
321 | 321 |
} |
322 | 322 |
static std::string psOut(const Color &c) |
323 | 323 |
{ |
324 | 324 |
std::ostringstream os; |
325 | 325 |
os << c.red() << ' ' << c.green() << ' ' << c.blue(); |
326 | 326 |
return os.str(); |
327 | 327 |
} |
328 | 328 |
|
329 | 329 |
public: |
330 | 330 |
GraphToEps(const T &t) : T(t), dontPrint(false) {}; |
331 | 331 |
|
332 | 332 |
template<class X> struct CoordsTraits : public T { |
333 | 333 |
typedef X CoordsMapType; |
334 | 334 |
const X &_coords; |
335 | 335 |
CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {} |
336 | 336 |
}; |
337 | 337 |
///Sets the map of the node coordinates |
338 | 338 |
|
339 | 339 |
///Sets the map of the node coordinates. |
340 | 340 |
///\param x must be a node map with \ref dim2::Point "dim2::Point<double>" or |
341 | 341 |
///\ref dim2::Point "dim2::Point<int>" values. |
342 | 342 |
template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) { |
343 | 343 |
dontPrint=true; |
344 | 344 |
return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x)); |
345 | 345 |
} |
346 | 346 |
template<class X> struct NodeSizesTraits : public T { |
347 | 347 |
const X &_nodeSizes; |
348 | 348 |
NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {} |
349 | 349 |
}; |
350 | 350 |
///Sets the map of the node sizes |
351 | 351 |
|
352 | 352 |
///Sets the map of the node sizes. |
353 | 353 |
///\param x must be a node map with \c double (or convertible) values. |
354 | 354 |
template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x) |
355 | 355 |
{ |
356 | 356 |
dontPrint=true; |
357 | 357 |
return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x)); |
358 | 358 |
} |
359 | 359 |
template<class X> struct NodeShapesTraits : public T { |
360 | 360 |
const X &_nodeShapes; |
361 | 361 |
NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {} |
362 | 362 |
}; |
363 | 363 |
///Sets the map of the node shapes |
364 | 364 |
|
365 | 365 |
///Sets the map of the node shapes. |
366 | 366 |
///The available shape values |
367 | 367 |
///can be found in \ref NodeShapes "enum NodeShapes". |
368 | 368 |
///\param x must be a node map with \c int (or convertible) values. |
369 | 369 |
///\sa NodeShapes |
370 | 370 |
template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x) |
371 | 371 |
{ |
372 | 372 |
dontPrint=true; |
373 | 373 |
return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x)); |
374 | 374 |
} |
375 | 375 |
template<class X> struct NodeTextsTraits : public T { |
376 | 376 |
const X &_nodeTexts; |
377 | 377 |
NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {} |
378 | 378 |
}; |
379 | 379 |
///Sets the text printed on the nodes |
380 | 380 |
|
381 | 381 |
///Sets the text printed on the nodes. |
382 | 382 |
///\param x must be a node map with type that can be pushed to a standard |
383 | 383 |
///\c ostream. |
384 | 384 |
template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x) |
385 | 385 |
{ |
386 | 386 |
dontPrint=true; |
387 | 387 |
_showNodeText=true; |
388 | 388 |
return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x)); |
389 | 389 |
} |
390 | 390 |
template<class X> struct NodePsTextsTraits : public T { |
391 | 391 |
const X &_nodePsTexts; |
392 | 392 |
NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {} |
393 | 393 |
}; |
394 | 394 |
///Inserts a PostScript block to the nodes |
395 | 395 |
|
396 | 396 |
///With this command it is possible to insert a verbatim PostScript |
397 | 397 |
///block to the nodes. |
398 | 398 |
///The PS current point will be moved to the center of the node before |
399 | 399 |
///the PostScript block inserted. |
400 | 400 |
/// |
401 | 401 |
///Before and after the block a newline character is inserted so you |
402 | 402 |
///don't have to bother with the separators. |
403 | 403 |
/// |
404 | 404 |
///\param x must be a node map with type that can be pushed to a standard |
405 | 405 |
///\c ostream. |
406 | 406 |
/// |
407 | 407 |
///\sa nodePsTextsPreamble() |
408 | 408 |
template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x) |
409 | 409 |
{ |
410 | 410 |
dontPrint=true; |
411 | 411 |
_showNodePsText=true; |
412 | 412 |
return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x)); |
413 | 413 |
} |
414 | 414 |
template<class X> struct ArcWidthsTraits : public T { |
415 | 415 |
const X &_arcWidths; |
416 | 416 |
ArcWidthsTraits(const T &t,const X &x) : T(t), _arcWidths(x) {} |
417 | 417 |
}; |
418 | 418 |
///Sets the map of the arc widths |
419 | 419 |
|
420 | 420 |
///Sets the map of the arc widths. |
421 | 421 |
///\param x must be an arc map with \c double (or convertible) values. |
422 | 422 |
template<class X> GraphToEps<ArcWidthsTraits<X> > arcWidths(const X &x) |
423 | 423 |
{ |
424 | 424 |
dontPrint=true; |
425 | 425 |
return GraphToEps<ArcWidthsTraits<X> >(ArcWidthsTraits<X>(*this,x)); |
426 | 426 |
} |
427 | 427 |
|
428 | 428 |
template<class X> struct NodeColorsTraits : public T { |
429 | 429 |
const X &_nodeColors; |
430 | 430 |
NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {} |
431 | 431 |
}; |
432 | 432 |
///Sets the map of the node colors |
433 | 433 |
|
434 | 434 |
///Sets the map of the node colors. |
435 | 435 |
///\param x must be a node map with \ref Color values. |
436 | 436 |
/// |
437 | 437 |
///\sa Palette |
438 | 438 |
template<class X> GraphToEps<NodeColorsTraits<X> > |
439 | 439 |
nodeColors(const X &x) |
440 | 440 |
{ |
441 | 441 |
dontPrint=true; |
442 | 442 |
return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x)); |
443 | 443 |
} |
444 | 444 |
template<class X> struct NodeTextColorsTraits : public T { |
445 | 445 |
const X &_nodeTextColors; |
446 | 446 |
NodeTextColorsTraits(const T &t,const X &x) : T(t), _nodeTextColors(x) {} |
447 | 447 |
}; |
448 | 448 |
///Sets the map of the node text colors |
449 | 449 |
|
450 | 450 |
///Sets the map of the node text colors. |
451 | 451 |
///\param x must be a node map with \ref Color values. |
452 | 452 |
/// |
453 | 453 |
///\sa Palette |
454 | 454 |
template<class X> GraphToEps<NodeTextColorsTraits<X> > |
455 | 455 |
nodeTextColors(const X &x) |
456 | 456 |
{ |
457 | 457 |
dontPrint=true; |
458 | 458 |
_nodeTextColorType=CUST_COL; |
459 | 459 |
return GraphToEps<NodeTextColorsTraits<X> > |
460 | 460 |
(NodeTextColorsTraits<X>(*this,x)); |
461 | 461 |
} |
462 | 462 |
template<class X> struct ArcColorsTraits : public T { |
463 | 463 |
const X &_arcColors; |
464 | 464 |
ArcColorsTraits(const T &t,const X &x) : T(t), _arcColors(x) {} |
465 | 465 |
}; |
466 | 466 |
///Sets the map of the arc colors |
467 | 467 |
|
468 | 468 |
///Sets the map of the arc colors. |
469 | 469 |
///\param x must be an arc map with \ref Color values. |
470 | 470 |
/// |
471 | 471 |
///\sa Palette |
472 | 472 |
template<class X> GraphToEps<ArcColorsTraits<X> > |
473 | 473 |
arcColors(const X &x) |
474 | 474 |
{ |
475 | 475 |
dontPrint=true; |
476 | 476 |
return GraphToEps<ArcColorsTraits<X> >(ArcColorsTraits<X>(*this,x)); |
477 | 477 |
} |
478 | 478 |
///Sets a global scale factor for node sizes |
479 | 479 |
|
480 | 480 |
///Sets a global scale factor for node sizes. |
481 | 481 |
/// |
482 | 482 |
/// If nodeSizes() is not given, this function simply sets the node |
483 | 483 |
/// sizes to \c d. If nodeSizes() is given, but |
484 | 484 |
/// autoNodeScale() is not, then the node size given by |
485 | 485 |
/// nodeSizes() will be multiplied by the value \c d. |
486 | 486 |
/// If both nodeSizes() and autoNodeScale() are used, then the |
487 | 487 |
/// node sizes will be scaled in such a way that the greatest size will be |
488 | 488 |
/// equal to \c d. |
489 | 489 |
/// \sa nodeSizes() |
490 | 490 |
/// \sa autoNodeScale() |
491 | 491 |
GraphToEps<T> &nodeScale(double d=.01) {_nodeScale=d;return *this;} |
492 | 492 |
///Turns on/off the automatic node size scaling. |
493 | 493 |
|
494 | 494 |
///Turns on/off the automatic node size scaling. |
495 | 495 |
/// |
496 | 496 |
///\sa nodeScale() |
497 | 497 |
/// |
498 | 498 |
GraphToEps<T> &autoNodeScale(bool b=true) { |
499 | 499 |
_autoNodeScale=b;return *this; |
500 | 500 |
} |
501 | 501 |
|
502 | 502 |
///Turns on/off the absolutematic node size scaling. |
503 | 503 |
|
504 | 504 |
///Turns on/off the absolutematic node size scaling. |
505 | 505 |
/// |
506 | 506 |
///\sa nodeScale() |
507 | 507 |
/// |
508 | 508 |
GraphToEps<T> &absoluteNodeSizes(bool b=true) { |
509 | 509 |
_absoluteNodeSizes=b;return *this; |
510 | 510 |
} |
511 | 511 |
|
512 | 512 |
///Negates the Y coordinates. |
513 | 513 |
GraphToEps<T> &negateY(bool b=true) { |
514 | 514 |
_negY=b;return *this; |
515 | 515 |
} |
516 | 516 |
|
517 | 517 |
///Turn on/off pre-scaling |
518 | 518 |
|
519 | 519 |
///By default graphToEps() rescales the whole image in order to avoid |
520 | 520 |
///very big or very small bounding boxes. |
521 | 521 |
/// |
522 | 522 |
///This (p)rescaling can be turned off with this function. |
523 | 523 |
/// |
524 | 524 |
GraphToEps<T> &preScale(bool b=true) { |
525 | 525 |
_preScale=b;return *this; |
526 | 526 |
} |
527 | 527 |
|
528 | 528 |
///Sets a global scale factor for arc widths |
529 | 529 |
|
530 | 530 |
/// Sets a global scale factor for arc widths. |
531 | 531 |
/// |
532 | 532 |
/// If arcWidths() is not given, this function simply sets the arc |
533 | 533 |
/// widths to \c d. If arcWidths() is given, but |
534 | 534 |
/// autoArcWidthScale() is not, then the arc withs given by |
535 | 535 |
/// arcWidths() will be multiplied by the value \c d. |
536 | 536 |
/// If both arcWidths() and autoArcWidthScale() are used, then the |
537 | 537 |
/// arc withs will be scaled in such a way that the greatest width will be |
538 | 538 |
/// equal to \c d. |
539 | 539 |
GraphToEps<T> &arcWidthScale(double d=.003) {_arcWidthScale=d;return *this;} |
540 | 540 |
///Turns on/off the automatic arc width scaling. |
541 | 541 |
|
542 | 542 |
///Turns on/off the automatic arc width scaling. |
543 | 543 |
/// |
544 | 544 |
///\sa arcWidthScale() |
545 | 545 |
/// |
546 | 546 |
GraphToEps<T> &autoArcWidthScale(bool b=true) { |
547 | 547 |
_autoArcWidthScale=b;return *this; |
548 | 548 |
} |
549 | 549 |
///Turns on/off the absolutematic arc width scaling. |
550 | 550 |
|
551 | 551 |
///Turns on/off the absolutematic arc width scaling. |
552 | 552 |
/// |
553 | 553 |
///\sa arcWidthScale() |
554 | 554 |
/// |
555 | 555 |
GraphToEps<T> &absoluteArcWidths(bool b=true) { |
556 | 556 |
_absoluteArcWidths=b;return *this; |
557 | 557 |
} |
558 | 558 |
///Sets a global scale factor for the whole picture |
559 | 559 |
GraphToEps<T> &scale(double d) {_scale=d;return *this;} |
560 | 560 |
///Sets the width of the border around the picture |
561 | 561 |
GraphToEps<T> &border(double b=10) {_xBorder=_yBorder=b;return *this;} |
562 | 562 |
///Sets the width of the border around the picture |
563 | 563 |
GraphToEps<T> &border(double x, double y) { |
564 | 564 |
_xBorder=x;_yBorder=y;return *this; |
565 | 565 |
} |
566 | 566 |
///Sets whether to draw arrows |
567 | 567 |
GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;} |
568 | 568 |
///Sets the length of the arrowheads |
569 | 569 |
GraphToEps<T> &arrowLength(double d=1.0) {_arrowLength*=d;return *this;} |
570 | 570 |
///Sets the width of the arrowheads |
571 | 571 |
GraphToEps<T> &arrowWidth(double d=.3) {_arrowWidth*=d;return *this;} |
572 | 572 |
|
573 | 573 |
///Scales the drawing to fit to A4 page |
574 | 574 |
GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;} |
575 | 575 |
|
576 | 576 |
///Enables parallel arcs |
577 | 577 |
GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;} |
578 | 578 |
|
579 | 579 |
///Sets the distance between parallel arcs |
580 | 580 |
GraphToEps<T> &parArcDist(double d) {_parArcDist*=d;return *this;} |
581 | 581 |
|
582 | 582 |
///Hides the arcs |
583 | 583 |
GraphToEps<T> &hideArcs(bool b=true) {_showArcs=!b;return *this;} |
584 | 584 |
///Hides the nodes |
585 | 585 |
GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;} |
586 | 586 |
|
587 | 587 |
///Sets the size of the node texts |
588 | 588 |
GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;} |
589 | 589 |
|
590 | 590 |
///Sets the color of the node texts to be different from the node color |
591 | 591 |
|
592 | 592 |
///Sets the color of the node texts to be as different from the node color |
593 | 593 |
///as it is possible. |
594 | 594 |
GraphToEps<T> &distantColorNodeTexts() |
595 | 595 |
{_nodeTextColorType=DIST_COL;return *this;} |
596 | 596 |
///Sets the color of the node texts to be black or white and always visible. |
597 | 597 |
|
598 | 598 |
///Sets the color of the node texts to be black or white according to |
599 | 599 |
///which is more different from the node color. |
600 | 600 |
GraphToEps<T> &distantBWNodeTexts() |
601 | 601 |
{_nodeTextColorType=DIST_BW;return *this;} |
602 | 602 |
|
603 | 603 |
///Gives a preamble block for node Postscript block. |
604 | 604 |
|
605 | 605 |
///Gives a preamble block for node Postscript block. |
606 | 606 |
/// |
607 | 607 |
///\sa nodePsTexts() |
608 | 608 |
GraphToEps<T> & nodePsTextsPreamble(const char *str) { |
609 | 609 |
_nodePsTextsPreamble=str ;return *this; |
610 | 610 |
} |
611 | 611 |
///Sets whether the graph is undirected |
612 | 612 |
|
613 | 613 |
///Sets whether the graph is undirected. |
614 | 614 |
/// |
615 | 615 |
///This setting is the default for undirected graphs. |
616 | 616 |
/// |
617 | 617 |
///\sa directed() |
618 | 618 |
GraphToEps<T> &undirected(bool b=true) {_undirected=b;return *this;} |
619 | 619 |
|
620 | 620 |
///Sets whether the graph is directed |
621 | 621 |
|
622 | 622 |
///Sets whether the graph is directed. |
623 | 623 |
///Use it to show the edges as a pair of directed ones. |
624 | 624 |
/// |
625 | 625 |
///This setting is the default for digraphs. |
626 | 626 |
/// |
627 | 627 |
///\sa undirected() |
628 | 628 |
GraphToEps<T> &directed(bool b=true) {_undirected=!b;return *this;} |
629 | 629 |
|
630 | 630 |
///Sets the title. |
631 | 631 |
|
632 | 632 |
///Sets the title of the generated image, |
633 | 633 |
///namely it inserts a <tt>%%Title:</tt> DSC field to the header of |
634 | 634 |
///the EPS file. |
635 | 635 |
GraphToEps<T> &title(const std::string &t) {_title=t;return *this;} |
636 | 636 |
///Sets the copyright statement. |
637 | 637 |
|
638 | 638 |
///Sets the copyright statement of the generated image, |
639 | 639 |
///namely it inserts a <tt>%%Copyright:</tt> DSC field to the header of |
640 | 640 |
///the EPS file. |
641 | 641 |
GraphToEps<T> ©right(const std::string &t) {_copyright=t;return *this;} |
642 | 642 |
|
643 | 643 |
protected: |
644 | 644 |
bool isInsideNode(dim2::Point<double> p, double r,int t) |
645 | 645 |
{ |
646 | 646 |
switch(t) { |
647 | 647 |
case CIRCLE: |
648 | 648 |
case MALE: |
649 | 649 |
case FEMALE: |
650 | 650 |
return p.normSquare()<=r*r; |
651 | 651 |
case SQUARE: |
652 | 652 |
return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r; |
653 | 653 |
case DIAMOND: |
654 | 654 |
return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r; |
655 | 655 |
} |
656 | 656 |
return false; |
657 | 657 |
} |
658 | 658 |
|
659 | 659 |
public: |
660 | 660 |
~GraphToEps() { } |
661 | 661 |
|
662 | 662 |
///Draws the graph. |
663 | 663 |
|
664 | 664 |
///Like other functions using |
665 | 665 |
///\ref named-templ-func-param "named template parameters", |
666 | 666 |
///this function calls the algorithm itself, i.e. in this case |
667 | 667 |
///it draws the graph. |
668 | 668 |
void run() { |
669 |
//\todo better 'epsilon' would be nice here. |
|
670 | 669 |
const double EPSILON=1e-9; |
671 | 670 |
if(dontPrint) return; |
672 | 671 |
|
673 | 672 |
_graph_to_eps_bits::_NegY<typename T::CoordsMapType> |
674 | 673 |
mycoords(_coords,_negY); |
675 | 674 |
|
676 | 675 |
os << "%!PS-Adobe-2.0 EPSF-2.0\n"; |
677 | 676 |
if(_title.size()>0) os << "%%Title: " << _title << '\n'; |
678 | 677 |
if(_copyright.size()>0) os << "%%Copyright: " << _copyright << '\n'; |
679 | 678 |
os << "%%Creator: LEMON, graphToEps()\n"; |
680 | 679 |
|
681 | 680 |
{ |
682 | 681 |
#ifndef WIN32 |
683 | 682 |
timeval tv; |
684 | 683 |
gettimeofday(&tv, 0); |
685 | 684 |
|
686 | 685 |
char cbuf[26]; |
687 | 686 |
ctime_r(&tv.tv_sec,cbuf); |
688 | 687 |
os << "%%CreationDate: " << cbuf; |
689 | 688 |
#else |
690 | 689 |
SYSTEMTIME time; |
691 | 690 |
char buf1[11], buf2[9], buf3[5]; |
692 | 691 |
|
693 | 692 |
GetSystemTime(&time); |
694 | 693 |
if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &time, |
695 | 694 |
"ddd MMM dd", buf1, 11) && |
696 | 695 |
GetTimeFormat(LOCALE_USER_DEFAULT, 0, &time, |
697 | 696 |
"HH':'mm':'ss", buf2, 9) && |
698 | 697 |
GetDateFormat(LOCALE_USER_DEFAULT, 0, &time, |
699 | 698 |
"yyyy", buf3, 5)) { |
700 | 699 |
os << "%%CreationDate: " << buf1 << ' ' |
701 | 700 |
<< buf2 << ' ' << buf3 << std::endl; |
702 | 701 |
} |
703 | 702 |
#endif |
704 | 703 |
} |
705 | 704 |
|
706 | 705 |
if (_autoArcWidthScale) { |
707 | 706 |
double max_w=0; |
708 | 707 |
for(ArcIt e(g);e!=INVALID;++e) |
709 | 708 |
max_w=std::max(double(_arcWidths[e]),max_w); |
710 |
//\todo better 'epsilon' would be nice here. |
|
711 | 709 |
if(max_w>EPSILON) { |
712 | 710 |
_arcWidthScale/=max_w; |
713 | 711 |
} |
714 | 712 |
} |
715 | 713 |
|
716 | 714 |
if (_autoNodeScale) { |
717 | 715 |
double max_s=0; |
718 | 716 |
for(NodeIt n(g);n!=INVALID;++n) |
719 | 717 |
max_s=std::max(double(_nodeSizes[n]),max_s); |
720 |
//\todo better 'epsilon' would be nice here. |
|
721 | 718 |
if(max_s>EPSILON) { |
722 | 719 |
_nodeScale/=max_s; |
723 | 720 |
} |
724 | 721 |
} |
725 | 722 |
|
726 | 723 |
double diag_len = 1; |
727 | 724 |
if(!(_absoluteNodeSizes&&_absoluteArcWidths)) { |
728 | 725 |
dim2::Box<double> bb; |
729 | 726 |
for(NodeIt n(g);n!=INVALID;++n) bb.add(mycoords[n]); |
730 | 727 |
if (bb.empty()) { |
731 | 728 |
bb = dim2::Box<double>(dim2::Point<double>(0,0)); |
732 | 729 |
} |
733 | 730 |
diag_len = std::sqrt((bb.bottomLeft()-bb.topRight()).normSquare()); |
734 | 731 |
if(diag_len<EPSILON) diag_len = 1; |
735 | 732 |
if(!_absoluteNodeSizes) _nodeScale*=diag_len; |
736 | 733 |
if(!_absoluteArcWidths) _arcWidthScale*=diag_len; |
737 | 734 |
} |
738 | 735 |
|
739 | 736 |
dim2::Box<double> bb; |
740 | 737 |
for(NodeIt n(g);n!=INVALID;++n) { |
741 | 738 |
double ns=_nodeSizes[n]*_nodeScale; |
742 | 739 |
dim2::Point<double> p(ns,ns); |
743 | 740 |
switch(_nodeShapes[n]) { |
744 | 741 |
case CIRCLE: |
745 | 742 |
case SQUARE: |
746 | 743 |
case DIAMOND: |
747 | 744 |
bb.add(p+mycoords[n]); |
748 | 745 |
bb.add(-p+mycoords[n]); |
749 | 746 |
break; |
750 | 747 |
case MALE: |
751 | 748 |
bb.add(-p+mycoords[n]); |
752 | 749 |
bb.add(dim2::Point<double>(1.5*ns,1.5*std::sqrt(3.0)*ns)+mycoords[n]); |
753 | 750 |
break; |
754 | 751 |
case FEMALE: |
755 | 752 |
bb.add(p+mycoords[n]); |
756 | 753 |
bb.add(dim2::Point<double>(-ns,-3.01*ns)+mycoords[n]); |
757 | 754 |
break; |
758 | 755 |
} |
759 | 756 |
} |
760 | 757 |
if (bb.empty()) { |
761 | 758 |
bb = dim2::Box<double>(dim2::Point<double>(0,0)); |
762 | 759 |
} |
763 | 760 |
|
764 | 761 |
if(_scaleToA4) |
765 | 762 |
os <<"%%BoundingBox: 0 0 596 842\n%%DocumentPaperSizes: a4\n"; |
766 | 763 |
else { |
767 | 764 |
if(_preScale) { |
768 | 765 |
//Rescale so that BoundingBox won't be neither to big nor too small. |
769 | 766 |
while(bb.height()*_scale>1000||bb.width()*_scale>1000) _scale/=10; |
770 | 767 |
while(bb.height()*_scale<100||bb.width()*_scale<100) _scale*=10; |
771 | 768 |
} |
772 | 769 |
|
773 | 770 |
os << "%%BoundingBox: " |
774 | 771 |
<< int(floor(bb.left() * _scale - _xBorder)) << ' ' |
775 | 772 |
<< int(floor(bb.bottom() * _scale - _yBorder)) << ' ' |
776 | 773 |
<< int(ceil(bb.right() * _scale + _xBorder)) << ' ' |
777 | 774 |
<< int(ceil(bb.top() * _scale + _yBorder)) << '\n'; |
778 | 775 |
} |
779 | 776 |
|
780 | 777 |
os << "%%EndComments\n"; |
781 | 778 |
|
782 | 779 |
//x1 y1 x2 y2 x3 y3 cr cg cb w |
783 | 780 |
os << "/lb { setlinewidth setrgbcolor newpath moveto\n" |
784 | 781 |
<< " 4 2 roll 1 index 1 index curveto stroke } bind def\n"; |
785 | 782 |
os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke }" |
786 | 783 |
<< " bind def\n"; |
787 | 784 |
//x y r |
788 | 785 |
os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath }" |
789 | 786 |
<< " bind def\n"; |
790 | 787 |
//x y r |
791 | 788 |
os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n" |
792 | 789 |
<< " 2 index 1 index sub 2 index 2 index add lineto\n" |
793 | 790 |
<< " 2 index 1 index sub 2 index 2 index sub lineto\n" |
794 | 791 |
<< " 2 index 1 index add 2 index 2 index sub lineto\n" |
795 | 792 |
<< " closepath pop pop pop} bind def\n"; |
796 | 793 |
//x y r |
797 | 794 |
os << "/di { newpath 2 index 1 index add 2 index moveto\n" |
798 | 795 |
<< " 2 index 2 index 2 index add lineto\n" |
799 | 796 |
<< " 2 index 1 index sub 2 index lineto\n" |
800 | 797 |
<< " 2 index 2 index 2 index sub lineto\n" |
801 | 798 |
<< " closepath pop pop pop} bind def\n"; |
802 | 799 |
// x y r cr cg cb |
803 | 800 |
os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n" |
804 | 801 |
<< " setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n" |
805 | 802 |
<< " } bind def\n"; |
806 | 803 |
os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n" |
807 | 804 |
<< " setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n" |
808 | 805 |
<< " } bind def\n"; |
809 | 806 |
os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n" |
810 | 807 |
<< " setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n" |
811 | 808 |
<< " } bind def\n"; |
812 | 809 |
os << "/nfemale { 0 0 0 setrgbcolor 3 index " |
813 | 810 |
<< _nodeBorderQuotient/(1+_nodeBorderQuotient) |
814 | 811 |
<< " 1.5 mul mul setlinewidth\n" |
815 | 812 |
<< " newpath 5 index 5 index moveto " |
816 | 813 |
<< "5 index 5 index 5 index 3.01 mul sub\n" |
817 | 814 |
<< " lineto 5 index 4 index .7 mul sub 5 index 5 index 2.2 mul sub" |
818 | 815 |
<< " moveto\n" |
819 | 816 |
<< " 5 index 4 index .7 mul add 5 index 5 index 2.2 mul sub lineto " |
820 | 817 |
<< "stroke\n" |
821 | 818 |
<< " 5 index 5 index 5 index c fill\n" |
822 | 819 |
<< " setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n" |
823 | 820 |
<< " } bind def\n"; |
824 | 821 |
os << "/nmale {\n" |
825 | 822 |
<< " 0 0 0 setrgbcolor 3 index " |
826 | 823 |
<< _nodeBorderQuotient/(1+_nodeBorderQuotient) |
827 | 824 |
<<" 1.5 mul mul setlinewidth\n" |
828 | 825 |
<< " newpath 5 index 5 index moveto\n" |
829 | 826 |
<< " 5 index 4 index 1 mul 1.5 mul add\n" |
830 | 827 |
<< " 5 index 5 index 3 sqrt 1.5 mul mul add\n" |
831 | 828 |
<< " 1 index 1 index lineto\n" |
832 | 829 |
<< " 1 index 1 index 7 index sub moveto\n" |
833 | 830 |
<< " 1 index 1 index lineto\n" |
834 | 831 |
<< " exch 5 index 3 sqrt .5 mul mul sub exch 5 index .5 mul sub" |
835 | 832 |
<< " lineto\n" |
836 | 833 |
<< " stroke\n" |
837 | 834 |
<< " 5 index 5 index 5 index c fill\n" |
838 | 835 |
<< " setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n" |
839 | 836 |
<< " } bind def\n"; |
840 | 837 |
|
841 | 838 |
|
842 | 839 |
os << "/arrl " << _arrowLength << " def\n"; |
843 | 840 |
os << "/arrw " << _arrowWidth << " def\n"; |
844 | 841 |
// l dx_norm dy_norm |
845 | 842 |
os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n"; |
846 | 843 |
//len w dx_norm dy_norm x1 y1 cr cg cb |
847 | 844 |
os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx " |
848 | 845 |
<< "exch def\n" |
849 | 846 |
<< " /w exch def /len exch def\n" |
850 | 847 |
//<< "0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke" |
851 | 848 |
<< " newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n" |
852 | 849 |
<< " len w sub arrl sub dx dy lrl\n" |
853 | 850 |
<< " arrw dy dx neg lrl\n" |
854 | 851 |
<< " dx arrl w add mul dy w 2 div arrw add mul sub\n" |
855 | 852 |
<< " dy arrl w add mul dx w 2 div arrw add mul add rlineto\n" |
856 | 853 |
<< " dx arrl w add mul neg dy w 2 div arrw add mul sub\n" |
857 | 854 |
<< " dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n" |
858 | 855 |
<< " arrw dy dx neg lrl\n" |
859 | 856 |
<< " len w sub arrl sub neg dx dy lrl\n" |
860 | 857 |
<< " closepath fill } bind def\n"; |
861 | 858 |
os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n" |
862 | 859 |
<< " neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n"; |
863 | 860 |
|
864 | 861 |
os << "\ngsave\n"; |
865 | 862 |
if(_scaleToA4) |
866 | 863 |
if(bb.height()>bb.width()) { |
867 | 864 |
double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.height(), |
868 | 865 |
(A4WIDTH-2*A4BORDER)/bb.width()); |
869 | 866 |
os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' ' |
870 | 867 |
<< ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER |
871 | 868 |
<< " translate\n" |
872 | 869 |
<< sc << " dup scale\n" |
873 | 870 |
<< -bb.left() << ' ' << -bb.bottom() << " translate\n"; |
874 | 871 |
} |
875 | 872 |
else { |
876 |
//\todo Verify centering |
|
877 | 873 |
double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.width(), |
878 | 874 |
(A4WIDTH-2*A4BORDER)/bb.height()); |
879 | 875 |
os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' ' |
880 | 876 |
<< ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER |
881 | 877 |
<< " translate\n" |
882 | 878 |
<< sc << " dup scale\n90 rotate\n" |
883 | 879 |
<< -bb.left() << ' ' << -bb.top() << " translate\n"; |
884 | 880 |
} |
885 | 881 |
else if(_scale!=1.0) os << _scale << " dup scale\n"; |
886 | 882 |
|
887 | 883 |
if(_showArcs) { |
888 | 884 |
os << "%Arcs:\ngsave\n"; |
889 | 885 |
if(_enableParallel) { |
890 | 886 |
std::vector<Arc> el; |
891 | 887 |
for(ArcIt e(g);e!=INVALID;++e) |
892 | 888 |
if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0 |
893 | 889 |
&&g.source(e)!=g.target(e)) |
894 | 890 |
el.push_back(e); |
895 | 891 |
std::sort(el.begin(),el.end(),arcLess(g)); |
896 | 892 |
|
897 | 893 |
typename std::vector<Arc>::iterator j; |
898 | 894 |
for(typename std::vector<Arc>::iterator i=el.begin();i!=el.end();i=j) { |
899 | 895 |
for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ; |
900 | 896 |
|
901 | 897 |
double sw=0; |
902 | 898 |
for(typename std::vector<Arc>::iterator e=i;e!=j;++e) |
903 | 899 |
sw+=_arcWidths[*e]*_arcWidthScale+_parArcDist; |
904 | 900 |
sw-=_parArcDist; |
905 | 901 |
sw/=-2.0; |
906 | 902 |
dim2::Point<double> |
907 | 903 |
dvec(mycoords[g.target(*i)]-mycoords[g.source(*i)]); |
908 | 904 |
double l=std::sqrt(dvec.normSquare()); |
909 |
//\todo better 'epsilon' would be nice here. |
|
910 | 905 |
dim2::Point<double> d(dvec/std::max(l,EPSILON)); |
911 | 906 |
dim2::Point<double> m; |
912 | 907 |
// m=dim2::Point<double>(mycoords[g.target(*i)]+ |
913 | 908 |
// mycoords[g.source(*i)])/2.0; |
914 | 909 |
|
915 | 910 |
// m=dim2::Point<double>(mycoords[g.source(*i)])+ |
916 | 911 |
// dvec*(double(_nodeSizes[g.source(*i)])/ |
917 | 912 |
// (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)])); |
918 | 913 |
|
919 | 914 |
m=dim2::Point<double>(mycoords[g.source(*i)])+ |
920 | 915 |
d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0; |
921 | 916 |
|
922 | 917 |
for(typename std::vector<Arc>::iterator e=i;e!=j;++e) { |
923 | 918 |
sw+=_arcWidths[*e]*_arcWidthScale/2.0; |
924 | 919 |
dim2::Point<double> mm=m+rot90(d)*sw/.75; |
925 | 920 |
if(_drawArrows) { |
926 | 921 |
int node_shape; |
927 | 922 |
dim2::Point<double> s=mycoords[g.source(*e)]; |
928 | 923 |
dim2::Point<double> t=mycoords[g.target(*e)]; |
929 | 924 |
double rn=_nodeSizes[g.target(*e)]*_nodeScale; |
930 | 925 |
node_shape=_nodeShapes[g.target(*e)]; |
931 | 926 |
dim2::Bezier3 bez(s,mm,mm,t); |
932 | 927 |
double t1=0,t2=1; |
933 | 928 |
for(int ii=0;ii<INTERPOL_PREC;++ii) |
934 | 929 |
if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2; |
935 | 930 |
else t1=(t1+t2)/2; |
936 | 931 |
dim2::Point<double> apoint=bez((t1+t2)/2); |
937 | 932 |
rn = _arrowLength+_arcWidths[*e]*_arcWidthScale; |
938 | 933 |
rn*=rn; |
939 | 934 |
t2=(t1+t2)/2;t1=0; |
940 | 935 |
for(int ii=0;ii<INTERPOL_PREC;++ii) |
941 | 936 |
if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2; |
942 | 937 |
else t2=(t1+t2)/2; |
943 | 938 |
dim2::Point<double> linend=bez((t1+t2)/2); |
944 | 939 |
bez=bez.before((t1+t2)/2); |
945 | 940 |
// rn=_nodeSizes[g.source(*e)]*_nodeScale; |
946 | 941 |
// node_shape=_nodeShapes[g.source(*e)]; |
947 | 942 |
// t1=0;t2=1; |
948 | 943 |
// for(int i=0;i<INTERPOL_PREC;++i) |
949 | 944 |
// if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) |
950 | 945 |
// t1=(t1+t2)/2; |
951 | 946 |
// else t2=(t1+t2)/2; |
952 | 947 |
// bez=bez.after((t1+t2)/2); |
953 | 948 |
os << _arcWidths[*e]*_arcWidthScale << " setlinewidth " |
954 | 949 |
<< _arcColors[*e].red() << ' ' |
955 | 950 |
<< _arcColors[*e].green() << ' ' |
956 | 951 |
<< _arcColors[*e].blue() << " setrgbcolor newpath\n" |
957 | 952 |
<< bez.p1.x << ' ' << bez.p1.y << " moveto\n" |
958 | 953 |
<< bez.p2.x << ' ' << bez.p2.y << ' ' |
959 | 954 |
<< bez.p3.x << ' ' << bez.p3.y << ' ' |
960 | 955 |
<< bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n"; |
961 | 956 |
dim2::Point<double> dd(rot90(linend-apoint)); |
962 | 957 |
dd*=(.5*_arcWidths[*e]*_arcWidthScale+_arrowWidth)/ |
963 | 958 |
std::sqrt(dd.normSquare()); |
964 | 959 |
os << "newpath " << psOut(apoint) << " moveto " |
965 | 960 |
<< psOut(linend+dd) << " lineto " |
966 | 961 |
<< psOut(linend-dd) << " lineto closepath fill\n"; |
967 | 962 |
} |
968 | 963 |
else { |
969 | 964 |
os << mycoords[g.source(*e)].x << ' ' |
970 | 965 |
<< mycoords[g.source(*e)].y << ' ' |
971 | 966 |
<< mm.x << ' ' << mm.y << ' ' |
972 | 967 |
<< mycoords[g.target(*e)].x << ' ' |
973 | 968 |
<< mycoords[g.target(*e)].y << ' ' |
974 | 969 |
<< _arcColors[*e].red() << ' ' |
975 | 970 |
<< _arcColors[*e].green() << ' ' |
976 | 971 |
<< _arcColors[*e].blue() << ' ' |
977 | 972 |
<< _arcWidths[*e]*_arcWidthScale << " lb\n"; |
978 | 973 |
} |
979 | 974 |
sw+=_arcWidths[*e]*_arcWidthScale/2.0+_parArcDist; |
980 | 975 |
} |
981 | 976 |
} |
982 | 977 |
} |
983 | 978 |
else for(ArcIt e(g);e!=INVALID;++e) |
984 | 979 |
if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0 |
985 | 980 |
&&g.source(e)!=g.target(e)) { |
986 | 981 |
if(_drawArrows) { |
987 | 982 |
dim2::Point<double> d(mycoords[g.target(e)]-mycoords[g.source(e)]); |
988 | 983 |
double rn=_nodeSizes[g.target(e)]*_nodeScale; |
989 | 984 |
int node_shape=_nodeShapes[g.target(e)]; |
990 | 985 |
double t1=0,t2=1; |
991 | 986 |
for(int i=0;i<INTERPOL_PREC;++i) |
992 | 987 |
if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2; |
993 | 988 |
else t2=(t1+t2)/2; |
994 | 989 |
double l=std::sqrt(d.normSquare()); |
995 | 990 |
d/=l; |
996 | 991 |
|
997 | 992 |
os << l*(1-(t1+t2)/2) << ' ' |
998 | 993 |
<< _arcWidths[e]*_arcWidthScale << ' ' |
999 | 994 |
<< d.x << ' ' << d.y << ' ' |
1000 | 995 |
<< mycoords[g.source(e)].x << ' ' |
1001 | 996 |
<< mycoords[g.source(e)].y << ' ' |
1002 | 997 |
<< _arcColors[e].red() << ' ' |
1003 | 998 |
<< _arcColors[e].green() << ' ' |
1004 | 999 |
<< _arcColors[e].blue() << " arr\n"; |
1005 | 1000 |
} |
1006 | 1001 |
else os << mycoords[g.source(e)].x << ' ' |
1007 | 1002 |
<< mycoords[g.source(e)].y << ' ' |
1008 | 1003 |
<< mycoords[g.target(e)].x << ' ' |
1009 | 1004 |
<< mycoords[g.target(e)].y << ' ' |
1010 | 1005 |
<< _arcColors[e].red() << ' ' |
1011 | 1006 |
<< _arcColors[e].green() << ' ' |
1012 | 1007 |
<< _arcColors[e].blue() << ' ' |
1013 | 1008 |
<< _arcWidths[e]*_arcWidthScale << " l\n"; |
1014 | 1009 |
} |
1015 | 1010 |
os << "grestore\n"; |
1016 | 1011 |
} |
1017 | 1012 |
if(_showNodes) { |
1018 | 1013 |
os << "%Nodes:\ngsave\n"; |
1019 | 1014 |
for(NodeIt n(g);n!=INVALID;++n) { |
1020 | 1015 |
os << mycoords[n].x << ' ' << mycoords[n].y << ' ' |
1021 | 1016 |
<< _nodeSizes[n]*_nodeScale << ' ' |
1022 | 1017 |
<< _nodeColors[n].red() << ' ' |
1023 | 1018 |
<< _nodeColors[n].green() << ' ' |
1024 | 1019 |
<< _nodeColors[n].blue() << ' '; |
1025 | 1020 |
switch(_nodeShapes[n]) { |
1026 | 1021 |
case CIRCLE: |
1027 | 1022 |
os<< "nc";break; |
1028 | 1023 |
case SQUARE: |
1029 | 1024 |
os<< "nsq";break; |
1030 | 1025 |
case DIAMOND: |
1031 | 1026 |
os<< "ndi";break; |
1032 | 1027 |
case MALE: |
1033 | 1028 |
os<< "nmale";break; |
1034 | 1029 |
case FEMALE: |
1035 | 1030 |
os<< "nfemale";break; |
1036 | 1031 |
} |
1037 | 1032 |
os<<'\n'; |
1038 | 1033 |
} |
1039 | 1034 |
os << "grestore\n"; |
1040 | 1035 |
} |
1041 | 1036 |
if(_showNodeText) { |
1042 | 1037 |
os << "%Node texts:\ngsave\n"; |
1043 | 1038 |
os << "/fosi " << _nodeTextSize << " def\n"; |
1044 | 1039 |
os << "(Helvetica) findfont fosi scalefont setfont\n"; |
1045 | 1040 |
for(NodeIt n(g);n!=INVALID;++n) { |
1046 | 1041 |
switch(_nodeTextColorType) { |
1047 | 1042 |
case DIST_COL: |
1048 | 1043 |
os << psOut(distantColor(_nodeColors[n])) << " setrgbcolor\n"; |
1049 | 1044 |
break; |
1050 | 1045 |
case DIST_BW: |
1051 | 1046 |
os << psOut(distantBW(_nodeColors[n])) << " setrgbcolor\n"; |
1052 | 1047 |
break; |
1053 | 1048 |
case CUST_COL: |
1054 | 1049 |
os << psOut(distantColor(_nodeTextColors[n])) << " setrgbcolor\n"; |
1055 | 1050 |
break; |
1056 | 1051 |
default: |
1057 | 1052 |
os << "0 0 0 setrgbcolor\n"; |
1058 | 1053 |
} |
1059 | 1054 |
os << mycoords[n].x << ' ' << mycoords[n].y |
1060 | 1055 |
<< " (" << _nodeTexts[n] << ") cshow\n"; |
1061 | 1056 |
} |
1062 | 1057 |
os << "grestore\n"; |
1063 | 1058 |
} |
1064 | 1059 |
if(_showNodePsText) { |
1065 | 1060 |
os << "%Node PS blocks:\ngsave\n"; |
1066 | 1061 |
for(NodeIt n(g);n!=INVALID;++n) |
1067 | 1062 |
os << mycoords[n].x << ' ' << mycoords[n].y |
1068 | 1063 |
<< " moveto\n" << _nodePsTexts[n] << "\n"; |
1069 | 1064 |
os << "grestore\n"; |
1070 | 1065 |
} |
1071 | 1066 |
|
1072 | 1067 |
os << "grestore\nshowpage\n"; |
1073 | 1068 |
|
1074 | 1069 |
//CleanUp: |
1075 | 1070 |
if(_pleaseRemoveOsStream) {delete &os;} |
1076 | 1071 |
} |
1077 | 1072 |
|
1078 | 1073 |
///\name Aliases |
1079 | 1074 |
///These are just some aliases to other parameter setting functions. |
1080 | 1075 |
|
1081 | 1076 |
///@{ |
1082 | 1077 |
|
1083 | 1078 |
///An alias for arcWidths() |
1084 | 1079 |
template<class X> GraphToEps<ArcWidthsTraits<X> > edgeWidths(const X &x) |
1085 | 1080 |
{ |
1086 | 1081 |
return arcWidths(x); |
1087 | 1082 |
} |
1088 | 1083 |
|
1089 | 1084 |
///An alias for arcColors() |
1090 | 1085 |
template<class X> GraphToEps<ArcColorsTraits<X> > |
1091 | 1086 |
edgeColors(const X &x) |
1092 | 1087 |
{ |
1093 | 1088 |
return arcColors(x); |
1094 | 1089 |
} |
1095 | 1090 |
|
1096 | 1091 |
///An alias for arcWidthScale() |
1097 | 1092 |
GraphToEps<T> &edgeWidthScale(double d) {return arcWidthScale(d);} |
1098 | 1093 |
|
1099 | 1094 |
///An alias for autoArcWidthScale() |
1100 | 1095 |
GraphToEps<T> &autoEdgeWidthScale(bool b=true) |
1101 | 1096 |
{ |
1102 | 1097 |
return autoArcWidthScale(b); |
1103 | 1098 |
} |
1104 | 1099 |
|
1105 | 1100 |
///An alias for absoluteArcWidths() |
1106 | 1101 |
GraphToEps<T> &absoluteEdgeWidths(bool b=true) |
1107 | 1102 |
{ |
1108 | 1103 |
return absoluteArcWidths(b); |
1109 | 1104 |
} |
1110 | 1105 |
|
1111 | 1106 |
///An alias for parArcDist() |
1112 | 1107 |
GraphToEps<T> &parEdgeDist(double d) {return parArcDist(d);} |
1113 | 1108 |
|
1114 | 1109 |
///An alias for hideArcs() |
1115 | 1110 |
GraphToEps<T> &hideEdges(bool b=true) {return hideArcs(b);} |
1116 | 1111 |
|
1117 | 1112 |
///@} |
1118 | 1113 |
}; |
1119 | 1114 |
|
1120 | 1115 |
template<class T> |
1121 | 1116 |
const int GraphToEps<T>::INTERPOL_PREC = 20; |
1122 | 1117 |
template<class T> |
1123 | 1118 |
const double GraphToEps<T>::A4HEIGHT = 841.8897637795276; |
1124 | 1119 |
template<class T> |
1125 | 1120 |
const double GraphToEps<T>::A4WIDTH = 595.275590551181; |
1126 | 1121 |
template<class T> |
1127 | 1122 |
const double GraphToEps<T>::A4BORDER = 15; |
1128 | 1123 |
|
1129 | 1124 |
|
1130 | 1125 |
///Generates an EPS file from a graph |
1131 | 1126 |
|
1132 | 1127 |
///\ingroup eps_io |
1133 | 1128 |
///Generates an EPS file from a graph. |
1134 | 1129 |
///\param g Reference to the graph to be printed. |
1135 | 1130 |
///\param os Reference to the output stream. |
1136 | 1131 |
///By default it is <tt>std::cout</tt>. |
1137 | 1132 |
/// |
1138 | 1133 |
///This function also has a lot of |
1139 | 1134 |
///\ref named-templ-func-param "named parameters", |
1140 | 1135 |
///they are declared as the members of class \ref GraphToEps. The following |
1141 | 1136 |
///example shows how to use these parameters. |
1142 | 1137 |
///\code |
1143 | 1138 |
/// graphToEps(g,os).scale(10).coords(coords) |
1144 | 1139 |
/// .nodeScale(2).nodeSizes(sizes) |
1145 | 1140 |
/// .arcWidthScale(.4).run(); |
1146 | 1141 |
///\endcode |
1147 | 1142 |
/// |
1148 | 1143 |
///For more detailed examples see the \ref graph_to_eps_demo.cc demo file. |
1149 | 1144 |
/// |
1150 | 1145 |
///\warning Don't forget to put the \ref GraphToEps::run() "run()" |
1151 | 1146 |
///to the end of the parameter list. |
1152 | 1147 |
///\sa GraphToEps |
1153 | 1148 |
///\sa graphToEps(G &g, const char *file_name) |
1154 | 1149 |
template<class G> |
1155 | 1150 |
GraphToEps<DefaultGraphToEpsTraits<G> > |
1156 | 1151 |
graphToEps(G &g, std::ostream& os=std::cout) |
1157 | 1152 |
{ |
1158 | 1153 |
return |
1159 | 1154 |
GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os)); |
1160 | 1155 |
} |
1161 | 1156 |
|
1162 | 1157 |
///Generates an EPS file from a graph |
1163 | 1158 |
|
1164 | 1159 |
///\ingroup eps_io |
1165 | 1160 |
///This function does the same as |
1166 | 1161 |
///\ref graphToEps(G &g,std::ostream& os) |
1167 | 1162 |
///but it writes its output into the file \c file_name |
1168 | 1163 |
///instead of a stream. |
1169 | 1164 |
///\sa graphToEps(G &g, std::ostream& os) |
1170 | 1165 |
template<class G> |
1171 | 1166 |
GraphToEps<DefaultGraphToEpsTraits<G> > |
1172 | 1167 |
graphToEps(G &g,const char *file_name) |
1173 | 1168 |
{ |
1174 | 1169 |
return GraphToEps<DefaultGraphToEpsTraits<G> > |
1175 | 1170 |
(DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true)); |
1176 | 1171 |
} |
1177 | 1172 |
|
1178 | 1173 |
///Generates an EPS file from a graph |
1179 | 1174 |
|
1180 | 1175 |
///\ingroup eps_io |
1181 | 1176 |
///This function does the same as |
1182 | 1177 |
///\ref graphToEps(G &g,std::ostream& os) |
1183 | 1178 |
///but it writes its output into the file \c file_name |
1184 | 1179 |
///instead of a stream. |
1185 | 1180 |
///\sa graphToEps(G &g, std::ostream& os) |
1186 | 1181 |
template<class G> |
1187 | 1182 |
GraphToEps<DefaultGraphToEpsTraits<G> > |
1188 | 1183 |
graphToEps(G &g,const std::string& file_name) |
1189 | 1184 |
{ |
1190 | 1185 |
return GraphToEps<DefaultGraphToEpsTraits<G> > |
1191 | 1186 |
(DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name.c_str()),true)); |
1192 | 1187 |
} |
1193 | 1188 |
|
1194 | 1189 |
} //END OF NAMESPACE LEMON |
1195 | 1190 |
|
1196 | 1191 |
#endif // LEMON_GRAPH_TO_EPS_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-2008 |
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_LIST_GRAPH_H |
20 | 20 |
#define LEMON_LIST_GRAPH_H |
21 | 21 |
|
22 | 22 |
///\ingroup graphs |
23 | 23 |
///\file |
24 | 24 |
///\brief ListDigraph, ListGraph classes. |
25 | 25 |
|
26 | 26 |
#include <lemon/core.h> |
27 | 27 |
#include <lemon/error.h> |
28 | 28 |
#include <lemon/bits/graph_extender.h> |
29 | 29 |
|
30 | 30 |
#include <vector> |
31 | 31 |
#include <list> |
32 | 32 |
|
33 | 33 |
namespace lemon { |
34 | 34 |
|
35 | 35 |
class ListDigraphBase { |
36 | 36 |
|
37 | 37 |
protected: |
38 | 38 |
struct NodeT { |
39 | 39 |
int first_in, first_out; |
40 | 40 |
int prev, next; |
41 | 41 |
}; |
42 | 42 |
|
43 | 43 |
struct ArcT { |
44 | 44 |
int target, source; |
45 | 45 |
int prev_in, prev_out; |
46 | 46 |
int next_in, next_out; |
47 | 47 |
}; |
48 | 48 |
|
49 | 49 |
std::vector<NodeT> nodes; |
50 | 50 |
|
51 | 51 |
int first_node; |
52 | 52 |
|
53 | 53 |
int first_free_node; |
54 | 54 |
|
55 | 55 |
std::vector<ArcT> arcs; |
56 | 56 |
|
57 | 57 |
int first_free_arc; |
58 | 58 |
|
59 | 59 |
public: |
60 | 60 |
|
61 | 61 |
typedef ListDigraphBase Digraph; |
62 | 62 |
|
63 | 63 |
class Node { |
64 | 64 |
friend class ListDigraphBase; |
65 | 65 |
protected: |
66 | 66 |
|
67 | 67 |
int id; |
68 | 68 |
explicit Node(int pid) { id = pid;} |
69 | 69 |
|
70 | 70 |
public: |
71 | 71 |
Node() {} |
72 | 72 |
Node (Invalid) { id = -1; } |
73 | 73 |
bool operator==(const Node& node) const {return id == node.id;} |
74 | 74 |
bool operator!=(const Node& node) const {return id != node.id;} |
75 | 75 |
bool operator<(const Node& node) const {return id < node.id;} |
76 | 76 |
}; |
77 | 77 |
|
78 | 78 |
class Arc { |
79 | 79 |
friend class ListDigraphBase; |
80 | 80 |
protected: |
81 | 81 |
|
82 | 82 |
int id; |
83 | 83 |
explicit Arc(int pid) { id = pid;} |
84 | 84 |
|
85 | 85 |
public: |
86 | 86 |
Arc() {} |
87 | 87 |
Arc (Invalid) { id = -1; } |
88 | 88 |
bool operator==(const Arc& arc) const {return id == arc.id;} |
89 | 89 |
bool operator!=(const Arc& arc) const {return id != arc.id;} |
90 | 90 |
bool operator<(const Arc& arc) const {return id < arc.id;} |
91 | 91 |
}; |
92 | 92 |
|
93 | 93 |
|
94 | 94 |
|
95 | 95 |
ListDigraphBase() |
96 | 96 |
: nodes(), first_node(-1), |
97 | 97 |
first_free_node(-1), arcs(), first_free_arc(-1) {} |
98 | 98 |
|
99 | 99 |
|
100 | 100 |
int maxNodeId() const { return nodes.size()-1; } |
101 | 101 |
int maxArcId() const { return arcs.size()-1; } |
102 | 102 |
|
103 | 103 |
Node source(Arc e) const { return Node(arcs[e.id].source); } |
104 | 104 |
Node target(Arc e) const { return Node(arcs[e.id].target); } |
105 | 105 |
|
106 | 106 |
|
107 | 107 |
void first(Node& node) const { |
108 | 108 |
node.id = first_node; |
109 | 109 |
} |
110 | 110 |
|
111 | 111 |
void next(Node& node) const { |
112 | 112 |
node.id = nodes[node.id].next; |
113 | 113 |
} |
114 | 114 |
|
115 | 115 |
|
116 | 116 |
void first(Arc& arc) const { |
117 | 117 |
int n; |
118 | 118 |
for(n = first_node; |
119 | 119 |
n!=-1 && nodes[n].first_in == -1; |
120 | 120 |
n = nodes[n].next) {} |
121 | 121 |
arc.id = (n == -1) ? -1 : nodes[n].first_in; |
122 | 122 |
} |
123 | 123 |
|
124 | 124 |
void next(Arc& arc) const { |
125 | 125 |
if (arcs[arc.id].next_in != -1) { |
126 | 126 |
arc.id = arcs[arc.id].next_in; |
127 | 127 |
} else { |
128 | 128 |
int n; |
129 | 129 |
for(n = nodes[arcs[arc.id].target].next; |
130 | 130 |
n!=-1 && nodes[n].first_in == -1; |
131 | 131 |
n = nodes[n].next) {} |
132 | 132 |
arc.id = (n == -1) ? -1 : nodes[n].first_in; |
133 | 133 |
} |
134 | 134 |
} |
135 | 135 |
|
136 | 136 |
void firstOut(Arc &e, const Node& v) const { |
137 | 137 |
e.id = nodes[v.id].first_out; |
138 | 138 |
} |
139 | 139 |
void nextOut(Arc &e) const { |
140 | 140 |
e.id=arcs[e.id].next_out; |
141 | 141 |
} |
142 | 142 |
|
143 | 143 |
void firstIn(Arc &e, const Node& v) const { |
144 | 144 |
e.id = nodes[v.id].first_in; |
145 | 145 |
} |
146 | 146 |
void nextIn(Arc &e) const { |
147 | 147 |
e.id=arcs[e.id].next_in; |
148 | 148 |
} |
149 | 149 |
|
150 | 150 |
|
151 | 151 |
static int id(Node v) { return v.id; } |
152 | 152 |
static int id(Arc e) { return e.id; } |
153 | 153 |
|
154 | 154 |
static Node nodeFromId(int id) { return Node(id);} |
155 | 155 |
static Arc arcFromId(int id) { return Arc(id);} |
156 | 156 |
|
157 | 157 |
bool valid(Node n) const { |
158 | 158 |
return n.id >= 0 && n.id < static_cast<int>(nodes.size()) && |
159 | 159 |
nodes[n.id].prev != -2; |
160 | 160 |
} |
161 | 161 |
|
162 | 162 |
bool valid(Arc a) const { |
163 | 163 |
return a.id >= 0 && a.id < static_cast<int>(arcs.size()) && |
164 | 164 |
arcs[a.id].prev_in != -2; |
165 | 165 |
} |
166 | 166 |
|
167 | 167 |
Node addNode() { |
168 | 168 |
int n; |
169 | 169 |
|
170 | 170 |
if(first_free_node==-1) { |
171 | 171 |
n = nodes.size(); |
172 | 172 |
nodes.push_back(NodeT()); |
173 | 173 |
} else { |
174 | 174 |
n = first_free_node; |
175 | 175 |
first_free_node = nodes[n].next; |
176 | 176 |
} |
177 | 177 |
|
178 | 178 |
nodes[n].next = first_node; |
179 | 179 |
if(first_node != -1) nodes[first_node].prev = n; |
180 | 180 |
first_node = n; |
181 | 181 |
nodes[n].prev = -1; |
182 | 182 |
|
183 | 183 |
nodes[n].first_in = nodes[n].first_out = -1; |
184 | 184 |
|
185 | 185 |
return Node(n); |
186 | 186 |
} |
187 | 187 |
|
188 | 188 |
Arc addArc(Node u, Node v) { |
189 | 189 |
int n; |
190 | 190 |
|
191 | 191 |
if (first_free_arc == -1) { |
192 | 192 |
n = arcs.size(); |
193 | 193 |
arcs.push_back(ArcT()); |
194 | 194 |
} else { |
195 | 195 |
n = first_free_arc; |
196 | 196 |
first_free_arc = arcs[n].next_in; |
197 | 197 |
} |
198 | 198 |
|
199 | 199 |
arcs[n].source = u.id; |
200 | 200 |
arcs[n].target = v.id; |
201 | 201 |
|
202 | 202 |
arcs[n].next_out = nodes[u.id].first_out; |
203 | 203 |
if(nodes[u.id].first_out != -1) { |
204 | 204 |
arcs[nodes[u.id].first_out].prev_out = n; |
205 | 205 |
} |
206 | 206 |
|
207 | 207 |
arcs[n].next_in = nodes[v.id].first_in; |
208 | 208 |
if(nodes[v.id].first_in != -1) { |
209 | 209 |
arcs[nodes[v.id].first_in].prev_in = n; |
210 | 210 |
} |
211 | 211 |
|
212 | 212 |
arcs[n].prev_in = arcs[n].prev_out = -1; |
213 | 213 |
|
214 | 214 |
nodes[u.id].first_out = nodes[v.id].first_in = n; |
215 | 215 |
|
216 | 216 |
return Arc(n); |
217 | 217 |
} |
218 | 218 |
|
219 | 219 |
void erase(const Node& node) { |
220 | 220 |
int n = node.id; |
221 | 221 |
|
222 | 222 |
if(nodes[n].next != -1) { |
223 | 223 |
nodes[nodes[n].next].prev = nodes[n].prev; |
224 | 224 |
} |
225 | 225 |
|
226 | 226 |
if(nodes[n].prev != -1) { |
227 | 227 |
nodes[nodes[n].prev].next = nodes[n].next; |
228 | 228 |
} else { |
229 | 229 |
first_node = nodes[n].next; |
230 | 230 |
} |
231 | 231 |
|
232 | 232 |
nodes[n].next = first_free_node; |
233 | 233 |
first_free_node = n; |
234 | 234 |
nodes[n].prev = -2; |
235 | 235 |
|
236 | 236 |
} |
237 | 237 |
|
238 | 238 |
void erase(const Arc& arc) { |
239 | 239 |
int n = arc.id; |
240 | 240 |
|
241 | 241 |
if(arcs[n].next_in!=-1) { |
242 | 242 |
arcs[arcs[n].next_in].prev_in = arcs[n].prev_in; |
243 | 243 |
} |
244 | 244 |
|
245 | 245 |
if(arcs[n].prev_in!=-1) { |
246 | 246 |
arcs[arcs[n].prev_in].next_in = arcs[n].next_in; |
247 | 247 |
} else { |
248 | 248 |
nodes[arcs[n].target].first_in = arcs[n].next_in; |
249 | 249 |
} |
250 | 250 |
|
251 | 251 |
|
252 | 252 |
if(arcs[n].next_out!=-1) { |
253 | 253 |
arcs[arcs[n].next_out].prev_out = arcs[n].prev_out; |
254 | 254 |
} |
255 | 255 |
|
256 | 256 |
if(arcs[n].prev_out!=-1) { |
257 | 257 |
arcs[arcs[n].prev_out].next_out = arcs[n].next_out; |
258 | 258 |
} else { |
259 | 259 |
nodes[arcs[n].source].first_out = arcs[n].next_out; |
260 | 260 |
} |
261 | 261 |
|
262 | 262 |
arcs[n].next_in = first_free_arc; |
263 | 263 |
first_free_arc = n; |
264 | 264 |
arcs[n].prev_in = -2; |
265 | 265 |
} |
266 | 266 |
|
267 | 267 |
void clear() { |
268 | 268 |
arcs.clear(); |
269 | 269 |
nodes.clear(); |
270 | 270 |
first_node = first_free_node = first_free_arc = -1; |
271 | 271 |
} |
272 | 272 |
|
273 | 273 |
protected: |
274 | 274 |
void changeTarget(Arc e, Node n) |
275 | 275 |
{ |
276 | 276 |
if(arcs[e.id].next_in != -1) |
277 | 277 |
arcs[arcs[e.id].next_in].prev_in = arcs[e.id].prev_in; |
278 | 278 |
if(arcs[e.id].prev_in != -1) |
279 | 279 |
arcs[arcs[e.id].prev_in].next_in = arcs[e.id].next_in; |
280 | 280 |
else nodes[arcs[e.id].target].first_in = arcs[e.id].next_in; |
281 | 281 |
if (nodes[n.id].first_in != -1) { |
282 | 282 |
arcs[nodes[n.id].first_in].prev_in = e.id; |
283 | 283 |
} |
284 | 284 |
arcs[e.id].target = n.id; |
285 | 285 |
arcs[e.id].prev_in = -1; |
286 | 286 |
arcs[e.id].next_in = nodes[n.id].first_in; |
287 | 287 |
nodes[n.id].first_in = e.id; |
288 | 288 |
} |
289 | 289 |
void changeSource(Arc e, Node n) |
290 | 290 |
{ |
291 | 291 |
if(arcs[e.id].next_out != -1) |
292 | 292 |
arcs[arcs[e.id].next_out].prev_out = arcs[e.id].prev_out; |
293 | 293 |
if(arcs[e.id].prev_out != -1) |
294 | 294 |
arcs[arcs[e.id].prev_out].next_out = arcs[e.id].next_out; |
295 | 295 |
else nodes[arcs[e.id].source].first_out = arcs[e.id].next_out; |
296 | 296 |
if (nodes[n.id].first_out != -1) { |
297 | 297 |
arcs[nodes[n.id].first_out].prev_out = e.id; |
298 | 298 |
} |
299 | 299 |
arcs[e.id].source = n.id; |
300 | 300 |
arcs[e.id].prev_out = -1; |
301 | 301 |
arcs[e.id].next_out = nodes[n.id].first_out; |
302 | 302 |
nodes[n.id].first_out = e.id; |
303 | 303 |
} |
304 | 304 |
|
305 | 305 |
}; |
306 | 306 |
|
307 | 307 |
typedef DigraphExtender<ListDigraphBase> ExtendedListDigraphBase; |
308 | 308 |
|
309 | 309 |
/// \addtogroup graphs |
310 | 310 |
/// @{ |
311 | 311 |
|
312 | 312 |
///A general directed graph structure. |
313 | 313 |
|
314 | 314 |
///\ref ListDigraph is a simple and fast <em>directed graph</em> |
315 | 315 |
///implementation based on static linked lists that are stored in |
316 | 316 |
///\c std::vector structures. |
317 | 317 |
/// |
318 | 318 |
///It conforms to the \ref concepts::Digraph "Digraph concept" and it |
319 | 319 |
///also provides several useful additional functionalities. |
320 | 320 |
///Most of the member functions and nested classes are documented |
321 | 321 |
///only in the concept class. |
322 | 322 |
/// |
323 | 323 |
///An important extra feature of this digraph implementation is that |
324 | 324 |
///its maps are real \ref concepts::ReferenceMap "reference map"s. |
325 | 325 |
/// |
326 | 326 |
///\sa concepts::Digraph |
327 | 327 |
|
328 | 328 |
class ListDigraph : public ExtendedListDigraphBase { |
329 | 329 |
private: |
330 | 330 |
///ListDigraph is \e not copy constructible. Use copyDigraph() instead. |
331 | 331 |
|
332 | 332 |
///ListDigraph is \e not copy constructible. Use copyDigraph() instead. |
333 | 333 |
/// |
334 | 334 |
ListDigraph(const ListDigraph &) :ExtendedListDigraphBase() {}; |
335 | 335 |
///\brief Assignment of ListDigraph to another one is \e not allowed. |
336 | 336 |
///Use copyDigraph() instead. |
337 | 337 |
|
338 | 338 |
///Assignment of ListDigraph to another one is \e not allowed. |
339 | 339 |
///Use copyDigraph() instead. |
340 | 340 |
void operator=(const ListDigraph &) {} |
341 | 341 |
public: |
342 | 342 |
|
343 | 343 |
typedef ExtendedListDigraphBase Parent; |
344 | 344 |
|
345 | 345 |
/// Constructor |
346 | 346 |
|
347 | 347 |
/// Constructor. |
348 | 348 |
/// |
349 | 349 |
ListDigraph() {} |
350 | 350 |
|
351 | 351 |
///Add a new node to the digraph. |
352 | 352 |
|
353 | 353 |
///Add a new node to the digraph. |
354 | 354 |
///\return the new node. |
355 | 355 |
Node addNode() { return Parent::addNode(); } |
356 | 356 |
|
357 | 357 |
///Add a new arc to the digraph. |
358 | 358 |
|
359 | 359 |
///Add a new arc to the digraph with source node \c s |
360 | 360 |
///and target node \c t. |
361 | 361 |
///\return the new arc. |
362 | 362 |
Arc addArc(const Node& s, const Node& t) { |
363 | 363 |
return Parent::addArc(s, t); |
364 | 364 |
} |
365 | 365 |
|
366 | 366 |
///\brief Erase a node from the digraph. |
367 | 367 |
/// |
368 | 368 |
///Erase a node from the digraph. |
369 | 369 |
/// |
370 | 370 |
void erase(const Node& n) { Parent::erase(n); } |
371 | 371 |
|
372 | 372 |
///\brief Erase an arc from the digraph. |
373 | 373 |
/// |
374 | 374 |
///Erase an arc from the digraph. |
375 | 375 |
/// |
376 | 376 |
void erase(const Arc& a) { Parent::erase(a); } |
377 | 377 |
|
378 | 378 |
/// Node validity check |
379 | 379 |
|
380 | 380 |
/// This function gives back true if the given node is valid, |
381 | 381 |
/// ie. it is a real node of the graph. |
382 | 382 |
/// |
383 | 383 |
/// \warning A Node pointing to a removed item |
384 | 384 |
/// could become valid again later if new nodes are |
385 | 385 |
/// added to the graph. |
386 | 386 |
bool valid(Node n) const { return Parent::valid(n); } |
387 | 387 |
|
388 | 388 |
/// Arc validity check |
389 | 389 |
|
390 | 390 |
/// This function gives back true if the given arc is valid, |
391 | 391 |
/// ie. it is a real arc of the graph. |
392 | 392 |
/// |
393 | 393 |
/// \warning An Arc pointing to a removed item |
394 | 394 |
/// could become valid again later if new nodes are |
395 | 395 |
/// added to the graph. |
396 | 396 |
bool valid(Arc a) const { return Parent::valid(a); } |
397 | 397 |
|
398 | 398 |
/// Change the target of \c a to \c n |
399 | 399 |
|
400 | 400 |
/// Change the target of \c a to \c n |
401 | 401 |
/// |
402 | 402 |
///\note The <tt>ArcIt</tt>s and <tt>OutArcIt</tt>s referencing |
403 | 403 |
///the changed arc remain valid. However <tt>InArcIt</tt>s are |
404 | 404 |
///invalidated. |
405 | 405 |
/// |
406 | 406 |
///\warning This functionality cannot be used together with the Snapshot |
407 | 407 |
///feature. |
408 | 408 |
void changeTarget(Arc a, Node n) { |
409 | 409 |
Parent::changeTarget(a,n); |
410 | 410 |
} |
411 | 411 |
/// Change the source of \c a to \c n |
412 | 412 |
|
413 | 413 |
/// Change the source of \c a to \c n |
414 | 414 |
/// |
415 | 415 |
///\note The <tt>InArcIt</tt>s referencing the changed arc remain |
416 | 416 |
///valid. However the <tt>ArcIt<tt>s and <tt>OutArcIt</tt>s are |
417 | 417 |
///invalidated. |
418 | 418 |
/// |
419 | 419 |
///\warning This functionality cannot be used together with the Snapshot |
420 | 420 |
///feature. |
421 | 421 |
void changeSource(Arc a, Node n) { |
422 | 422 |
Parent::changeSource(a,n); |
423 | 423 |
} |
424 | 424 |
|
425 | 425 |
/// Invert the direction of an arc. |
426 | 426 |
|
427 | 427 |
///\note The <tt>ArcIt</tt>s referencing the changed arc remain |
428 | 428 |
///valid. However <tt>OutArcIt</tt>s and <tt>InArcIt</tt>s are |
429 | 429 |
///invalidated. |
430 | 430 |
/// |
431 | 431 |
///\warning This functionality cannot be used together with the Snapshot |
432 | 432 |
///feature. |
433 | 433 |
void reverseArc(Arc e) { |
434 | 434 |
Node t=target(e); |
435 | 435 |
changeTarget(e,source(e)); |
436 | 436 |
changeSource(e,t); |
437 | 437 |
} |
438 | 438 |
|
439 | 439 |
/// Reserve memory for nodes. |
440 | 440 |
|
441 | 441 |
/// Using this function it is possible to avoid the superfluous memory |
442 | 442 |
/// allocation: if you know that the digraph you want to build will |
443 | 443 |
/// be very large (e.g. it will contain millions of nodes and/or arcs) |
444 | 444 |
/// then it is worth reserving space for this amount before starting |
445 | 445 |
/// to build the digraph. |
446 | 446 |
/// \sa reserveArc |
447 | 447 |
void reserveNode(int n) { nodes.reserve(n); }; |
448 | 448 |
|
449 | 449 |
/// Reserve memory for arcs. |
450 | 450 |
|
451 | 451 |
/// Using this function it is possible to avoid the superfluous memory |
452 | 452 |
/// allocation: if you know that the digraph you want to build will |
453 | 453 |
/// be very large (e.g. it will contain millions of nodes and/or arcs) |
454 | 454 |
/// then it is worth reserving space for this amount before starting |
455 | 455 |
/// to build the digraph. |
456 | 456 |
/// \sa reserveNode |
457 | 457 |
void reserveArc(int m) { arcs.reserve(m); }; |
458 | 458 |
|
459 | 459 |
///Contract two nodes. |
460 | 460 |
|
461 | 461 |
///This function contracts two nodes. |
462 | 462 |
///Node \p b will be removed but instead of deleting |
463 | 463 |
///incident arcs, they will be joined to \p a. |
464 | 464 |
///The last parameter \p r controls whether to remove loops. \c true |
465 | 465 |
///means that loops will be removed. |
466 | 466 |
/// |
467 | 467 |
///\note The <tt>ArcIt</tt>s referencing a moved arc remain |
468 | 468 |
///valid. However <tt>InArcIt</tt>s and <tt>OutArcIt</tt>s |
469 | 469 |
///may be invalidated. |
470 | 470 |
/// |
471 | 471 |
///\warning This functionality cannot be used together with the Snapshot |
472 | 472 |
///feature. |
473 | 473 |
void contract(Node a, Node b, bool r = true) |
474 | 474 |
{ |
475 | 475 |
for(OutArcIt e(*this,b);e!=INVALID;) { |
476 | 476 |
OutArcIt f=e; |
477 | 477 |
++f; |
478 | 478 |
if(r && target(e)==a) erase(e); |
479 | 479 |
else changeSource(e,a); |
480 | 480 |
e=f; |
481 | 481 |
} |
482 | 482 |
for(InArcIt e(*this,b);e!=INVALID;) { |
483 | 483 |
InArcIt f=e; |
484 | 484 |
++f; |
485 | 485 |
if(r && source(e)==a) erase(e); |
486 | 486 |
else changeTarget(e,a); |
487 | 487 |
e=f; |
488 | 488 |
} |
489 | 489 |
erase(b); |
490 | 490 |
} |
491 | 491 |
|
492 | 492 |
///Split a node. |
493 | 493 |
|
494 | 494 |
///This function splits a node. First a new node is added to the digraph, |
495 | 495 |
///then the source of each outgoing arc of \c n is moved to this new node. |
496 | 496 |
///If \c connect is \c true (this is the default value), then a new arc |
497 | 497 |
///from \c n to the newly created node is also added. |
498 | 498 |
///\return The newly created node. |
499 | 499 |
/// |
500 | 500 |
///\note The <tt>ArcIt</tt>s referencing a moved arc remain |
501 | 501 |
///valid. However <tt>InArcIt</tt>s and <tt>OutArcIt</tt>s may |
502 | 502 |
///be invalidated. |
503 | 503 |
/// |
504 |
///\warning This functionality cannot be used |
|
504 |
///\warning This functionality cannot be used in conjunction with the |
|
505 | 505 |
///Snapshot feature. |
506 |
/// |
|
507 |
///\todo It could be implemented in a bit faster way. |
|
508 | 506 |
Node split(Node n, bool connect = true) { |
509 | 507 |
Node b = addNode(); |
510 | 508 |
for(OutArcIt e(*this,n);e!=INVALID;) { |
511 | 509 |
OutArcIt f=e; |
512 | 510 |
++f; |
513 | 511 |
changeSource(e,b); |
514 | 512 |
e=f; |
515 | 513 |
} |
516 | 514 |
if (connect) addArc(n,b); |
517 | 515 |
return b; |
518 | 516 |
} |
519 | 517 |
|
520 | 518 |
///Split an arc. |
521 | 519 |
|
522 | 520 |
///This function splits an arc. First a new node \c b is added to |
523 | 521 |
///the digraph, then the original arc is re-targeted to \c |
524 | 522 |
///b. Finally an arc from \c b to the original target is added. |
525 | 523 |
/// |
526 | 524 |
///\return The newly created node. |
527 | 525 |
/// |
528 | 526 |
///\warning This functionality cannot be used together with the |
529 | 527 |
///Snapshot feature. |
530 | 528 |
Node split(Arc e) { |
531 | 529 |
Node b = addNode(); |
532 | 530 |
addArc(b,target(e)); |
533 | 531 |
changeTarget(e,b); |
534 | 532 |
return b; |
535 | 533 |
} |
536 | 534 |
|
537 | 535 |
/// \brief Class to make a snapshot of the digraph and restore |
538 | 536 |
/// it later. |
539 | 537 |
/// |
540 | 538 |
/// Class to make a snapshot of the digraph and restore it later. |
541 | 539 |
/// |
542 | 540 |
/// The newly added nodes and arcs can be removed using the |
543 | 541 |
/// restore() function. |
544 | 542 |
/// |
545 | 543 |
/// \warning Arc and node deletions and other modifications (e.g. |
546 | 544 |
/// contracting, splitting, reversing arcs or nodes) cannot be |
547 | 545 |
/// restored. These events invalidate the snapshot. |
548 | 546 |
class Snapshot { |
549 | 547 |
protected: |
550 | 548 |
|
551 | 549 |
typedef Parent::NodeNotifier NodeNotifier; |
552 | 550 |
|
553 | 551 |
class NodeObserverProxy : public NodeNotifier::ObserverBase { |
554 | 552 |
public: |
555 | 553 |
|
556 | 554 |
NodeObserverProxy(Snapshot& _snapshot) |
557 | 555 |
: snapshot(_snapshot) {} |
558 | 556 |
|
559 | 557 |
using NodeNotifier::ObserverBase::attach; |
560 | 558 |
using NodeNotifier::ObserverBase::detach; |
561 | 559 |
using NodeNotifier::ObserverBase::attached; |
562 | 560 |
|
563 | 561 |
protected: |
564 | 562 |
|
565 | 563 |
virtual void add(const Node& node) { |
566 | 564 |
snapshot.addNode(node); |
567 | 565 |
} |
568 | 566 |
virtual void add(const std::vector<Node>& nodes) { |
569 | 567 |
for (int i = nodes.size() - 1; i >= 0; ++i) { |
570 | 568 |
snapshot.addNode(nodes[i]); |
571 | 569 |
} |
572 | 570 |
} |
573 | 571 |
virtual void erase(const Node& node) { |
574 | 572 |
snapshot.eraseNode(node); |
575 | 573 |
} |
576 | 574 |
virtual void erase(const std::vector<Node>& nodes) { |
577 | 575 |
for (int i = 0; i < int(nodes.size()); ++i) { |
578 | 576 |
snapshot.eraseNode(nodes[i]); |
579 | 577 |
} |
580 | 578 |
} |
581 | 579 |
virtual void build() { |
582 | 580 |
Node node; |
583 | 581 |
std::vector<Node> nodes; |
584 | 582 |
for (notifier()->first(node); node != INVALID; |
585 | 583 |
notifier()->next(node)) { |
586 | 584 |
nodes.push_back(node); |
587 | 585 |
} |
588 | 586 |
for (int i = nodes.size() - 1; i >= 0; --i) { |
589 | 587 |
snapshot.addNode(nodes[i]); |
590 | 588 |
} |
591 | 589 |
} |
592 | 590 |
virtual void clear() { |
593 | 591 |
Node node; |
594 | 592 |
for (notifier()->first(node); node != INVALID; |
595 | 593 |
notifier()->next(node)) { |
596 | 594 |
snapshot.eraseNode(node); |
597 | 595 |
} |
598 | 596 |
} |
599 | 597 |
|
600 | 598 |
Snapshot& snapshot; |
601 | 599 |
}; |
602 | 600 |
|
603 | 601 |
class ArcObserverProxy : public ArcNotifier::ObserverBase { |
604 | 602 |
public: |
605 | 603 |
|
606 | 604 |
ArcObserverProxy(Snapshot& _snapshot) |
607 | 605 |
: snapshot(_snapshot) {} |
608 | 606 |
|
609 | 607 |
using ArcNotifier::ObserverBase::attach; |
610 | 608 |
using ArcNotifier::ObserverBase::detach; |
611 | 609 |
using ArcNotifier::ObserverBase::attached; |
612 | 610 |
|
613 | 611 |
protected: |
614 | 612 |
|
615 | 613 |
virtual void add(const Arc& arc) { |
616 | 614 |
snapshot.addArc(arc); |
617 | 615 |
} |
618 | 616 |
virtual void add(const std::vector<Arc>& arcs) { |
619 | 617 |
for (int i = arcs.size() - 1; i >= 0; ++i) { |
620 | 618 |
snapshot.addArc(arcs[i]); |
621 | 619 |
} |
622 | 620 |
} |
623 | 621 |
virtual void erase(const Arc& arc) { |
624 | 622 |
snapshot.eraseArc(arc); |
625 | 623 |
} |
626 | 624 |
virtual void erase(const std::vector<Arc>& arcs) { |
627 | 625 |
for (int i = 0; i < int(arcs.size()); ++i) { |
628 | 626 |
snapshot.eraseArc(arcs[i]); |
629 | 627 |
} |
630 | 628 |
} |
631 | 629 |
virtual void build() { |
632 | 630 |
Arc arc; |
633 | 631 |
std::vector<Arc> arcs; |
634 | 632 |
for (notifier()->first(arc); arc != INVALID; |
635 | 633 |
notifier()->next(arc)) { |
636 | 634 |
arcs.push_back(arc); |
637 | 635 |
} |
638 | 636 |
for (int i = arcs.size() - 1; i >= 0; --i) { |
639 | 637 |
snapshot.addArc(arcs[i]); |
640 | 638 |
} |
641 | 639 |
} |
642 | 640 |
virtual void clear() { |
643 | 641 |
Arc arc; |
644 | 642 |
for (notifier()->first(arc); arc != INVALID; |
645 | 643 |
notifier()->next(arc)) { |
646 | 644 |
snapshot.eraseArc(arc); |
647 | 645 |
} |
648 | 646 |
} |
649 | 647 |
|
650 | 648 |
Snapshot& snapshot; |
651 | 649 |
}; |
652 | 650 |
|
653 | 651 |
ListDigraph *digraph; |
654 | 652 |
|
655 | 653 |
NodeObserverProxy node_observer_proxy; |
656 | 654 |
ArcObserverProxy arc_observer_proxy; |
657 | 655 |
|
658 | 656 |
std::list<Node> added_nodes; |
659 | 657 |
std::list<Arc> added_arcs; |
660 | 658 |
|
661 | 659 |
|
662 | 660 |
void addNode(const Node& node) { |
663 | 661 |
added_nodes.push_front(node); |
664 | 662 |
} |
665 | 663 |
void eraseNode(const Node& node) { |
666 | 664 |
std::list<Node>::iterator it = |
667 | 665 |
std::find(added_nodes.begin(), added_nodes.end(), node); |
668 | 666 |
if (it == added_nodes.end()) { |
669 | 667 |
clear(); |
670 | 668 |
arc_observer_proxy.detach(); |
671 | 669 |
throw NodeNotifier::ImmediateDetach(); |
672 | 670 |
} else { |
673 | 671 |
added_nodes.erase(it); |
674 | 672 |
} |
675 | 673 |
} |
676 | 674 |
|
677 | 675 |
void addArc(const Arc& arc) { |
678 | 676 |
added_arcs.push_front(arc); |
679 | 677 |
} |
680 | 678 |
void eraseArc(const Arc& arc) { |
681 | 679 |
std::list<Arc>::iterator it = |
682 | 680 |
std::find(added_arcs.begin(), added_arcs.end(), arc); |
683 | 681 |
if (it == added_arcs.end()) { |
684 | 682 |
clear(); |
685 | 683 |
node_observer_proxy.detach(); |
686 | 684 |
throw ArcNotifier::ImmediateDetach(); |
687 | 685 |
} else { |
688 | 686 |
added_arcs.erase(it); |
689 | 687 |
} |
690 | 688 |
} |
691 | 689 |
|
692 | 690 |
void attach(ListDigraph &_digraph) { |
693 | 691 |
digraph = &_digraph; |
694 | 692 |
node_observer_proxy.attach(digraph->notifier(Node())); |
695 | 693 |
arc_observer_proxy.attach(digraph->notifier(Arc())); |
696 | 694 |
} |
697 | 695 |
|
698 | 696 |
void detach() { |
699 | 697 |
node_observer_proxy.detach(); |
700 | 698 |
arc_observer_proxy.detach(); |
701 | 699 |
} |
702 | 700 |
|
703 | 701 |
bool attached() const { |
704 | 702 |
return node_observer_proxy.attached(); |
705 | 703 |
} |
706 | 704 |
|
707 | 705 |
void clear() { |
708 | 706 |
added_nodes.clear(); |
709 | 707 |
added_arcs.clear(); |
710 | 708 |
} |
711 | 709 |
|
712 | 710 |
public: |
713 | 711 |
|
714 | 712 |
/// \brief Default constructor. |
715 | 713 |
/// |
716 | 714 |
/// Default constructor. |
717 | 715 |
/// To actually make a snapshot you must call save(). |
718 | 716 |
Snapshot() |
719 | 717 |
: digraph(0), node_observer_proxy(*this), |
720 | 718 |
arc_observer_proxy(*this) {} |
721 | 719 |
|
722 | 720 |
/// \brief Constructor that immediately makes a snapshot. |
723 | 721 |
/// |
724 | 722 |
/// This constructor immediately makes a snapshot of the digraph. |
725 | 723 |
/// \param _digraph The digraph we make a snapshot of. |
726 | 724 |
Snapshot(ListDigraph &_digraph) |
727 | 725 |
: node_observer_proxy(*this), |
728 | 726 |
arc_observer_proxy(*this) { |
729 | 727 |
attach(_digraph); |
730 | 728 |
} |
731 | 729 |
|
732 | 730 |
/// \brief Make a snapshot. |
733 | 731 |
/// |
734 | 732 |
/// Make a snapshot of the digraph. |
735 | 733 |
/// |
736 | 734 |
/// This function can be called more than once. In case of a repeated |
737 | 735 |
/// call, the previous snapshot gets lost. |
738 | 736 |
/// \param _digraph The digraph we make the snapshot of. |
739 | 737 |
void save(ListDigraph &_digraph) { |
740 | 738 |
if (attached()) { |
741 | 739 |
detach(); |
742 | 740 |
clear(); |
743 | 741 |
} |
744 | 742 |
attach(_digraph); |
745 | 743 |
} |
746 | 744 |
|
747 | 745 |
/// \brief Undo the changes until the last snapshot. |
748 | 746 |
// |
749 | 747 |
/// Undo the changes until the last snapshot created by save(). |
750 | 748 |
void restore() { |
751 | 749 |
detach(); |
752 | 750 |
for(std::list<Arc>::iterator it = added_arcs.begin(); |
753 | 751 |
it != added_arcs.end(); ++it) { |
754 | 752 |
digraph->erase(*it); |
755 | 753 |
} |
756 | 754 |
for(std::list<Node>::iterator it = added_nodes.begin(); |
757 | 755 |
it != added_nodes.end(); ++it) { |
758 | 756 |
digraph->erase(*it); |
759 | 757 |
} |
760 | 758 |
clear(); |
761 | 759 |
} |
762 | 760 |
|
763 | 761 |
/// \brief Gives back true when the snapshot is valid. |
764 | 762 |
/// |
765 | 763 |
/// Gives back true when the snapshot is valid. |
766 | 764 |
bool valid() const { |
767 | 765 |
return attached(); |
768 | 766 |
} |
769 | 767 |
}; |
770 | 768 |
|
771 | 769 |
}; |
772 | 770 |
|
773 | 771 |
///@} |
774 | 772 |
|
775 | 773 |
class ListGraphBase { |
776 | 774 |
|
777 | 775 |
protected: |
778 | 776 |
|
779 | 777 |
struct NodeT { |
780 | 778 |
int first_out; |
781 | 779 |
int prev, next; |
782 | 780 |
}; |
783 | 781 |
|
784 | 782 |
struct ArcT { |
785 | 783 |
int target; |
786 | 784 |
int prev_out, next_out; |
787 | 785 |
}; |
788 | 786 |
|
789 | 787 |
std::vector<NodeT> nodes; |
790 | 788 |
|
791 | 789 |
int first_node; |
792 | 790 |
|
793 | 791 |
int first_free_node; |
794 | 792 |
|
795 | 793 |
std::vector<ArcT> arcs; |
796 | 794 |
|
797 | 795 |
int first_free_arc; |
798 | 796 |
|
799 | 797 |
public: |
800 | 798 |
|
801 | 799 |
typedef ListGraphBase Digraph; |
802 | 800 |
|
803 | 801 |
class Node; |
804 | 802 |
class Arc; |
805 | 803 |
class Edge; |
806 | 804 |
|
807 | 805 |
class Node { |
808 | 806 |
friend class ListGraphBase; |
809 | 807 |
protected: |
810 | 808 |
|
811 | 809 |
int id; |
812 | 810 |
explicit Node(int pid) { id = pid;} |
813 | 811 |
|
814 | 812 |
public: |
815 | 813 |
Node() {} |
816 | 814 |
Node (Invalid) { id = -1; } |
817 | 815 |
bool operator==(const Node& node) const {return id == node.id;} |
818 | 816 |
bool operator!=(const Node& node) const {return id != node.id;} |
819 | 817 |
bool operator<(const Node& node) const {return id < node.id;} |
820 | 818 |
}; |
821 | 819 |
|
822 | 820 |
class Edge { |
823 | 821 |
friend class ListGraphBase; |
824 | 822 |
protected: |
825 | 823 |
|
826 | 824 |
int id; |
827 | 825 |
explicit Edge(int pid) { id = pid;} |
828 | 826 |
|
829 | 827 |
public: |
830 | 828 |
Edge() {} |
831 | 829 |
Edge (Invalid) { id = -1; } |
832 | 830 |
bool operator==(const Edge& edge) const {return id == edge.id;} |
833 | 831 |
bool operator!=(const Edge& edge) const {return id != edge.id;} |
834 | 832 |
bool operator<(const Edge& edge) const {return id < edge.id;} |
835 | 833 |
}; |
836 | 834 |
|
837 | 835 |
class Arc { |
838 | 836 |
friend class ListGraphBase; |
839 | 837 |
protected: |
840 | 838 |
|
841 | 839 |
int id; |
842 | 840 |
explicit Arc(int pid) { id = pid;} |
843 | 841 |
|
844 | 842 |
public: |
845 | 843 |
operator Edge() const { |
846 | 844 |
return id != -1 ? edgeFromId(id / 2) : INVALID; |
847 | 845 |
} |
848 | 846 |
|
849 | 847 |
Arc() {} |
850 | 848 |
Arc (Invalid) { id = -1; } |
851 | 849 |
bool operator==(const Arc& arc) const {return id == arc.id;} |
852 | 850 |
bool operator!=(const Arc& arc) const {return id != arc.id;} |
853 | 851 |
bool operator<(const Arc& arc) const {return id < arc.id;} |
854 | 852 |
}; |
855 | 853 |
|
856 | 854 |
|
857 | 855 |
|
858 | 856 |
ListGraphBase() |
859 | 857 |
: nodes(), first_node(-1), |
860 | 858 |
first_free_node(-1), arcs(), first_free_arc(-1) {} |
861 | 859 |
|
862 | 860 |
|
863 | 861 |
int maxNodeId() const { return nodes.size()-1; } |
864 | 862 |
int maxEdgeId() const { return arcs.size() / 2 - 1; } |
865 | 863 |
int maxArcId() const { return arcs.size()-1; } |
866 | 864 |
|
867 | 865 |
Node source(Arc e) const { return Node(arcs[e.id ^ 1].target); } |
868 | 866 |
Node target(Arc e) const { return Node(arcs[e.id].target); } |
869 | 867 |
|
870 | 868 |
Node u(Edge e) const { return Node(arcs[2 * e.id].target); } |
871 | 869 |
Node v(Edge e) const { return Node(arcs[2 * e.id + 1].target); } |
872 | 870 |
|
873 | 871 |
static bool direction(Arc e) { |
874 | 872 |
return (e.id & 1) == 1; |
875 | 873 |
} |
876 | 874 |
|
877 | 875 |
static Arc direct(Edge e, bool d) { |
878 | 876 |
return Arc(e.id * 2 + (d ? 1 : 0)); |
879 | 877 |
} |
880 | 878 |
|
881 | 879 |
void first(Node& node) const { |
882 | 880 |
node.id = first_node; |
883 | 881 |
} |
884 | 882 |
|
885 | 883 |
void next(Node& node) const { |
886 | 884 |
node.id = nodes[node.id].next; |
887 | 885 |
} |
888 | 886 |
|
889 | 887 |
void first(Arc& e) const { |
890 | 888 |
int n = first_node; |
891 | 889 |
while (n != -1 && nodes[n].first_out == -1) { |
892 | 890 |
n = nodes[n].next; |
893 | 891 |
} |
894 | 892 |
e.id = (n == -1) ? -1 : nodes[n].first_out; |
895 | 893 |
} |
896 | 894 |
|
897 | 895 |
void next(Arc& e) const { |
898 | 896 |
if (arcs[e.id].next_out != -1) { |
899 | 897 |
e.id = arcs[e.id].next_out; |
900 | 898 |
} else { |
901 | 899 |
int n = nodes[arcs[e.id ^ 1].target].next; |
902 | 900 |
while(n != -1 && nodes[n].first_out == -1) { |
903 | 901 |
n = nodes[n].next; |
904 | 902 |
} |
905 | 903 |
e.id = (n == -1) ? -1 : nodes[n].first_out; |
906 | 904 |
} |
907 | 905 |
} |
908 | 906 |
|
909 | 907 |
void first(Edge& e) const { |
910 | 908 |
int n = first_node; |
911 | 909 |
while (n != -1) { |
912 | 910 |
e.id = nodes[n].first_out; |
913 | 911 |
while ((e.id & 1) != 1) { |
914 | 912 |
e.id = arcs[e.id].next_out; |
915 | 913 |
} |
916 | 914 |
if (e.id != -1) { |
917 | 915 |
e.id /= 2; |
918 | 916 |
return; |
919 | 917 |
} |
920 | 918 |
n = nodes[n].next; |
921 | 919 |
} |
922 | 920 |
e.id = -1; |
923 | 921 |
} |
924 | 922 |
|
925 | 923 |
void next(Edge& e) const { |
926 | 924 |
int n = arcs[e.id * 2].target; |
927 | 925 |
e.id = arcs[(e.id * 2) | 1].next_out; |
928 | 926 |
while ((e.id & 1) != 1) { |
929 | 927 |
e.id = arcs[e.id].next_out; |
930 | 928 |
} |
931 | 929 |
if (e.id != -1) { |
932 | 930 |
e.id /= 2; |
933 | 931 |
return; |
934 | 932 |
} |
935 | 933 |
n = nodes[n].next; |
936 | 934 |
while (n != -1) { |
937 | 935 |
e.id = nodes[n].first_out; |
938 | 936 |
while ((e.id & 1) != 1) { |
939 | 937 |
e.id = arcs[e.id].next_out; |
940 | 938 |
} |
941 | 939 |
if (e.id != -1) { |
942 | 940 |
e.id /= 2; |
943 | 941 |
return; |
944 | 942 |
} |
945 | 943 |
n = nodes[n].next; |
946 | 944 |
} |
947 | 945 |
e.id = -1; |
948 | 946 |
} |
949 | 947 |
|
950 | 948 |
void firstOut(Arc &e, const Node& v) const { |
951 | 949 |
e.id = nodes[v.id].first_out; |
952 | 950 |
} |
953 | 951 |
void nextOut(Arc &e) const { |
954 | 952 |
e.id = arcs[e.id].next_out; |
955 | 953 |
} |
956 | 954 |
|
957 | 955 |
void firstIn(Arc &e, const Node& v) const { |
958 | 956 |
e.id = ((nodes[v.id].first_out) ^ 1); |
959 | 957 |
if (e.id == -2) e.id = -1; |
960 | 958 |
} |
961 | 959 |
void nextIn(Arc &e) const { |
962 | 960 |
e.id = ((arcs[e.id ^ 1].next_out) ^ 1); |
963 | 961 |
if (e.id == -2) e.id = -1; |
964 | 962 |
} |
965 | 963 |
|
966 | 964 |
void firstInc(Edge &e, bool& d, const Node& v) const { |
967 | 965 |
int a = nodes[v.id].first_out; |
968 | 966 |
if (a != -1 ) { |
969 | 967 |
e.id = a / 2; |
970 | 968 |
d = ((a & 1) == 1); |
971 | 969 |
} else { |
972 | 970 |
e.id = -1; |
973 | 971 |
d = true; |
974 | 972 |
} |
975 | 973 |
} |
976 | 974 |
void nextInc(Edge &e, bool& d) const { |
977 | 975 |
int a = (arcs[(e.id * 2) | (d ? 1 : 0)].next_out); |
978 | 976 |
if (a != -1 ) { |
979 | 977 |
e.id = a / 2; |
980 | 978 |
d = ((a & 1) == 1); |
981 | 979 |
} else { |
982 | 980 |
e.id = -1; |
983 | 981 |
d = true; |
984 | 982 |
} |
985 | 983 |
} |
986 | 984 |
|
987 | 985 |
static int id(Node v) { return v.id; } |
988 | 986 |
static int id(Arc e) { return e.id; } |
989 | 987 |
static int id(Edge e) { return e.id; } |
990 | 988 |
|
991 | 989 |
static Node nodeFromId(int id) { return Node(id);} |
992 | 990 |
static Arc arcFromId(int id) { return Arc(id);} |
993 | 991 |
static Edge edgeFromId(int id) { return Edge(id);} |
994 | 992 |
|
995 | 993 |
bool valid(Node n) const { |
996 | 994 |
return n.id >= 0 && n.id < static_cast<int>(nodes.size()) && |
997 | 995 |
nodes[n.id].prev != -2; |
998 | 996 |
} |
999 | 997 |
|
1000 | 998 |
bool valid(Arc a) const { |
1001 | 999 |
return a.id >= 0 && a.id < static_cast<int>(arcs.size()) && |
1002 | 1000 |
arcs[a.id].prev_out != -2; |
1003 | 1001 |
} |
1004 | 1002 |
|
1005 | 1003 |
bool valid(Edge e) const { |
1006 | 1004 |
return e.id >= 0 && 2 * e.id < static_cast<int>(arcs.size()) && |
1007 | 1005 |
arcs[2 * e.id].prev_out != -2; |
1008 | 1006 |
} |
1009 | 1007 |
|
1010 | 1008 |
Node addNode() { |
1011 | 1009 |
int n; |
1012 | 1010 |
|
1013 | 1011 |
if(first_free_node==-1) { |
1014 | 1012 |
n = nodes.size(); |
1015 | 1013 |
nodes.push_back(NodeT()); |
1016 | 1014 |
} else { |
1017 | 1015 |
n = first_free_node; |
1018 | 1016 |
first_free_node = nodes[n].next; |
1019 | 1017 |
} |
1020 | 1018 |
|
1021 | 1019 |
nodes[n].next = first_node; |
1022 | 1020 |
if (first_node != -1) nodes[first_node].prev = n; |
1023 | 1021 |
first_node = n; |
1024 | 1022 |
nodes[n].prev = -1; |
1025 | 1023 |
|
1026 | 1024 |
nodes[n].first_out = -1; |
1027 | 1025 |
|
1028 | 1026 |
return Node(n); |
1029 | 1027 |
} |
1030 | 1028 |
|
1031 | 1029 |
Edge addEdge(Node u, Node v) { |
1032 | 1030 |
int n; |
1033 | 1031 |
|
1034 | 1032 |
if (first_free_arc == -1) { |
1035 | 1033 |
n = arcs.size(); |
1036 | 1034 |
arcs.push_back(ArcT()); |
1037 | 1035 |
arcs.push_back(ArcT()); |
1038 | 1036 |
} else { |
1039 | 1037 |
n = first_free_arc; |
1040 | 1038 |
first_free_arc = arcs[n].next_out; |
1041 | 1039 |
} |
1042 | 1040 |
|
1043 | 1041 |
arcs[n].target = u.id; |
1044 | 1042 |
arcs[n | 1].target = v.id; |
1045 | 1043 |
|
1046 | 1044 |
arcs[n].next_out = nodes[v.id].first_out; |
1047 | 1045 |
if (nodes[v.id].first_out != -1) { |
1048 | 1046 |
arcs[nodes[v.id].first_out].prev_out = n; |
1049 | 1047 |
} |
1050 | 1048 |
arcs[n].prev_out = -1; |
1051 | 1049 |
nodes[v.id].first_out = n; |
1052 | 1050 |
|
1053 | 1051 |
arcs[n | 1].next_out = nodes[u.id].first_out; |
1054 | 1052 |
if (nodes[u.id].first_out != -1) { |
1055 | 1053 |
arcs[nodes[u.id].first_out].prev_out = (n | 1); |
1056 | 1054 |
} |
1057 | 1055 |
arcs[n | 1].prev_out = -1; |
1058 | 1056 |
nodes[u.id].first_out = (n | 1); |
1059 | 1057 |
|
1060 | 1058 |
return Edge(n / 2); |
1061 | 1059 |
} |
1062 | 1060 |
|
1063 | 1061 |
void erase(const Node& node) { |
1064 | 1062 |
int n = node.id; |
1065 | 1063 |
|
1066 | 1064 |
if(nodes[n].next != -1) { |
1067 | 1065 |
nodes[nodes[n].next].prev = nodes[n].prev; |
1068 | 1066 |
} |
1069 | 1067 |
|
1070 | 1068 |
if(nodes[n].prev != -1) { |
1071 | 1069 |
nodes[nodes[n].prev].next = nodes[n].next; |
1072 | 1070 |
} else { |
1073 | 1071 |
first_node = nodes[n].next; |
1074 | 1072 |
} |
1075 | 1073 |
|
1076 | 1074 |
nodes[n].next = first_free_node; |
1077 | 1075 |
first_free_node = n; |
1078 | 1076 |
nodes[n].prev = -2; |
1079 | 1077 |
} |
1080 | 1078 |
|
1081 | 1079 |
void erase(const Edge& edge) { |
1082 | 1080 |
int n = edge.id * 2; |
1083 | 1081 |
|
1084 | 1082 |
if (arcs[n].next_out != -1) { |
1085 | 1083 |
arcs[arcs[n].next_out].prev_out = arcs[n].prev_out; |
1086 | 1084 |
} |
1087 | 1085 |
|
1088 | 1086 |
if (arcs[n].prev_out != -1) { |
1089 | 1087 |
arcs[arcs[n].prev_out].next_out = arcs[n].next_out; |
1090 | 1088 |
} else { |
1091 | 1089 |
nodes[arcs[n | 1].target].first_out = arcs[n].next_out; |
1092 | 1090 |
} |
1093 | 1091 |
|
1094 | 1092 |
if (arcs[n | 1].next_out != -1) { |
1095 | 1093 |
arcs[arcs[n | 1].next_out].prev_out = arcs[n | 1].prev_out; |
1096 | 1094 |
} |
1097 | 1095 |
|
1098 | 1096 |
if (arcs[n | 1].prev_out != -1) { |
1099 | 1097 |
arcs[arcs[n | 1].prev_out].next_out = arcs[n | 1].next_out; |
1100 | 1098 |
} else { |
1101 | 1099 |
nodes[arcs[n].target].first_out = arcs[n | 1].next_out; |
1102 | 1100 |
} |
1103 | 1101 |
|
1104 | 1102 |
arcs[n].next_out = first_free_arc; |
1105 | 1103 |
first_free_arc = n; |
1106 | 1104 |
arcs[n].prev_out = -2; |
1107 | 1105 |
arcs[n | 1].prev_out = -2; |
1108 | 1106 |
|
1109 | 1107 |
} |
1110 | 1108 |
|
1111 | 1109 |
void clear() { |
1112 | 1110 |
arcs.clear(); |
1113 | 1111 |
nodes.clear(); |
1114 | 1112 |
first_node = first_free_node = first_free_arc = -1; |
1115 | 1113 |
} |
1116 | 1114 |
|
1117 | 1115 |
protected: |
1118 | 1116 |
|
1119 | 1117 |
void changeV(Edge e, Node n) { |
1120 | 1118 |
if(arcs[2 * e.id].next_out != -1) { |
1121 | 1119 |
arcs[arcs[2 * e.id].next_out].prev_out = arcs[2 * e.id].prev_out; |
1122 | 1120 |
} |
1123 | 1121 |
if(arcs[2 * e.id].prev_out != -1) { |
1124 | 1122 |
arcs[arcs[2 * e.id].prev_out].next_out = |
1125 | 1123 |
arcs[2 * e.id].next_out; |
1126 | 1124 |
} else { |
1127 | 1125 |
nodes[arcs[(2 * e.id) | 1].target].first_out = |
1128 | 1126 |
arcs[2 * e.id].next_out; |
1129 | 1127 |
} |
1130 | 1128 |
|
1131 | 1129 |
if (nodes[n.id].first_out != -1) { |
1132 | 1130 |
arcs[nodes[n.id].first_out].prev_out = 2 * e.id; |
1133 | 1131 |
} |
1134 | 1132 |
arcs[(2 * e.id) | 1].target = n.id; |
1135 | 1133 |
arcs[2 * e.id].prev_out = -1; |
1136 | 1134 |
arcs[2 * e.id].next_out = nodes[n.id].first_out; |
1137 | 1135 |
nodes[n.id].first_out = 2 * e.id; |
1138 | 1136 |
} |
1139 | 1137 |
|
1140 | 1138 |
void changeU(Edge e, Node n) { |
1141 | 1139 |
if(arcs[(2 * e.id) | 1].next_out != -1) { |
1142 | 1140 |
arcs[arcs[(2 * e.id) | 1].next_out].prev_out = |
1143 | 1141 |
arcs[(2 * e.id) | 1].prev_out; |
1144 | 1142 |
} |
1145 | 1143 |
if(arcs[(2 * e.id) | 1].prev_out != -1) { |
1146 | 1144 |
arcs[arcs[(2 * e.id) | 1].prev_out].next_out = |
1147 | 1145 |
arcs[(2 * e.id) | 1].next_out; |
1148 | 1146 |
} else { |
1149 | 1147 |
nodes[arcs[2 * e.id].target].first_out = |
1150 | 1148 |
arcs[(2 * e.id) | 1].next_out; |
1151 | 1149 |
} |
1152 | 1150 |
|
1153 | 1151 |
if (nodes[n.id].first_out != -1) { |
1154 | 1152 |
arcs[nodes[n.id].first_out].prev_out = ((2 * e.id) | 1); |
1155 | 1153 |
} |
1156 | 1154 |
arcs[2 * e.id].target = n.id; |
1157 | 1155 |
arcs[(2 * e.id) | 1].prev_out = -1; |
1158 | 1156 |
arcs[(2 * e.id) | 1].next_out = nodes[n.id].first_out; |
1159 | 1157 |
nodes[n.id].first_out = ((2 * e.id) | 1); |
1160 | 1158 |
} |
1161 | 1159 |
|
1162 | 1160 |
}; |
1163 | 1161 |
|
1164 | 1162 |
typedef GraphExtender<ListGraphBase> ExtendedListGraphBase; |
1165 | 1163 |
|
1166 | 1164 |
|
1167 | 1165 |
/// \addtogroup graphs |
1168 | 1166 |
/// @{ |
1169 | 1167 |
|
1170 | 1168 |
///A general undirected graph structure. |
1171 | 1169 |
|
1172 | 1170 |
///\ref ListGraph is a simple and fast <em>undirected graph</em> |
1173 | 1171 |
///implementation based on static linked lists that are stored in |
1174 | 1172 |
///\c std::vector structures. |
1175 | 1173 |
/// |
1176 | 1174 |
///It conforms to the \ref concepts::Graph "Graph concept" and it |
1177 | 1175 |
///also provides several useful additional functionalities. |
1178 | 1176 |
///Most of the member functions and nested classes are documented |
1179 | 1177 |
///only in the concept class. |
1180 | 1178 |
/// |
1181 | 1179 |
///An important extra feature of this graph implementation is that |
1182 | 1180 |
///its maps are real \ref concepts::ReferenceMap "reference map"s. |
1183 | 1181 |
/// |
1184 | 1182 |
///\sa concepts::Graph |
1185 | 1183 |
|
1186 | 1184 |
class ListGraph : public ExtendedListGraphBase { |
1187 | 1185 |
private: |
1188 | 1186 |
///ListGraph is \e not copy constructible. Use copyGraph() instead. |
1189 | 1187 |
|
1190 | 1188 |
///ListGraph is \e not copy constructible. Use copyGraph() instead. |
1191 | 1189 |
/// |
1192 | 1190 |
ListGraph(const ListGraph &) :ExtendedListGraphBase() {}; |
1193 | 1191 |
///\brief Assignment of ListGraph to another one is \e not allowed. |
1194 | 1192 |
///Use copyGraph() instead. |
1195 | 1193 |
|
1196 | 1194 |
///Assignment of ListGraph to another one is \e not allowed. |
1197 | 1195 |
///Use copyGraph() instead. |
1198 | 1196 |
void operator=(const ListGraph &) {} |
1199 | 1197 |
public: |
1200 | 1198 |
/// Constructor |
1201 | 1199 |
|
1202 | 1200 |
/// Constructor. |
1203 | 1201 |
/// |
1204 | 1202 |
ListGraph() {} |
1205 | 1203 |
|
1206 | 1204 |
typedef ExtendedListGraphBase Parent; |
1207 | 1205 |
|
1208 | 1206 |
typedef Parent::OutArcIt IncEdgeIt; |
1209 | 1207 |
|
1210 | 1208 |
/// \brief Add a new node to the graph. |
1211 | 1209 |
/// |
1212 | 1210 |
/// Add a new node to the graph. |
1213 | 1211 |
/// \return the new node. |
1214 | 1212 |
Node addNode() { return Parent::addNode(); } |
1215 | 1213 |
|
1216 | 1214 |
/// \brief Add a new edge to the graph. |
1217 | 1215 |
/// |
1218 | 1216 |
/// Add a new edge to the graph with source node \c s |
1219 | 1217 |
/// and target node \c t. |
1220 | 1218 |
/// \return the new edge. |
1221 | 1219 |
Edge addEdge(const Node& s, const Node& t) { |
1222 | 1220 |
return Parent::addEdge(s, t); |
1223 | 1221 |
} |
1224 | 1222 |
|
1225 | 1223 |
/// \brief Erase a node from the graph. |
1226 | 1224 |
/// |
1227 | 1225 |
/// Erase a node from the graph. |
1228 | 1226 |
/// |
1229 | 1227 |
void erase(const Node& n) { Parent::erase(n); } |
1230 | 1228 |
|
1231 | 1229 |
/// \brief Erase an edge from the graph. |
1232 | 1230 |
/// |
1233 | 1231 |
/// Erase an edge from the graph. |
1234 | 1232 |
/// |
1235 | 1233 |
void erase(const Edge& e) { Parent::erase(e); } |
1236 | 1234 |
/// Node validity check |
1237 | 1235 |
|
1238 | 1236 |
/// This function gives back true if the given node is valid, |
1239 | 1237 |
/// ie. it is a real node of the graph. |
1240 | 1238 |
/// |
1241 | 1239 |
/// \warning A Node pointing to a removed item |
1242 | 1240 |
/// could become valid again later if new nodes are |
1243 | 1241 |
/// added to the graph. |
1244 | 1242 |
bool valid(Node n) const { return Parent::valid(n); } |
1245 | 1243 |
/// Arc validity check |
1246 | 1244 |
|
1247 | 1245 |
/// This function gives back true if the given arc is valid, |
1248 | 1246 |
/// ie. it is a real arc of the graph. |
1249 | 1247 |
/// |
1250 | 1248 |
/// \warning An Arc pointing to a removed item |
1251 | 1249 |
/// could become valid again later if new edges are |
1252 | 1250 |
/// added to the graph. |
1253 | 1251 |
bool valid(Arc a) const { return Parent::valid(a); } |
1254 | 1252 |
/// Edge validity check |
1255 | 1253 |
|
1256 | 1254 |
/// This function gives back true if the given edge is valid, |
1257 | 1255 |
/// ie. it is a real arc of the graph. |
1258 | 1256 |
/// |
1259 | 1257 |
/// \warning A Edge pointing to a removed item |
1260 | 1258 |
/// could become valid again later if new edges are |
1261 | 1259 |
/// added to the graph. |
1262 | 1260 |
bool valid(Edge e) const { return Parent::valid(e); } |
1263 | 1261 |
/// \brief Change the end \c u of \c e to \c n |
1264 | 1262 |
/// |
1265 | 1263 |
/// This function changes the end \c u of \c e to node \c n. |
1266 | 1264 |
/// |
1267 | 1265 |
///\note The <tt>EdgeIt</tt>s and <tt>ArcIt</tt>s referencing the |
1268 | 1266 |
///changed edge are invalidated and if the changed node is the |
1269 | 1267 |
///base node of an iterator then this iterator is also |
1270 | 1268 |
///invalidated. |
1271 | 1269 |
/// |
1272 | 1270 |
///\warning This functionality cannot be used together with the |
1273 | 1271 |
///Snapshot feature. |
1274 | 1272 |
void changeU(Edge e, Node n) { |
1275 | 1273 |
Parent::changeU(e,n); |
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-2008 |
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_MAPS_H |
20 | 20 |
#define LEMON_MAPS_H |
21 | 21 |
|
22 | 22 |
#include <iterator> |
23 | 23 |
#include <functional> |
24 | 24 |
#include <vector> |
25 | 25 |
|
26 | 26 |
#include <lemon/core.h> |
27 | 27 |
|
28 | 28 |
///\file |
29 | 29 |
///\ingroup maps |
30 | 30 |
///\brief Miscellaneous property maps |
31 | 31 |
|
32 | 32 |
#include <map> |
33 | 33 |
|
34 | 34 |
namespace lemon { |
35 | 35 |
|
36 | 36 |
/// \addtogroup maps |
37 | 37 |
/// @{ |
38 | 38 |
|
39 | 39 |
/// Base class of maps. |
40 | 40 |
|
41 | 41 |
/// Base class of maps. It provides the necessary type definitions |
42 | 42 |
/// required by the map %concepts. |
43 | 43 |
template<typename K, typename V> |
44 | 44 |
class MapBase { |
45 | 45 |
public: |
46 | 46 |
/// \biref The key type of the map. |
47 | 47 |
typedef K Key; |
48 | 48 |
/// \brief The value type of the map. |
49 | 49 |
/// (The type of objects associated with the keys). |
50 | 50 |
typedef V Value; |
51 | 51 |
}; |
52 | 52 |
|
53 | 53 |
|
54 | 54 |
/// Null map. (a.k.a. DoNothingMap) |
55 | 55 |
|
56 | 56 |
/// This map can be used if you have to provide a map only for |
57 | 57 |
/// its type definitions, or if you have to provide a writable map, |
58 | 58 |
/// but data written to it is not required (i.e. it will be sent to |
59 | 59 |
/// <tt>/dev/null</tt>). |
60 | 60 |
/// It conforms the \ref concepts::ReadWriteMap "ReadWriteMap" concept. |
61 | 61 |
/// |
62 | 62 |
/// \sa ConstMap |
63 | 63 |
template<typename K, typename V> |
64 | 64 |
class NullMap : public MapBase<K, V> { |
65 | 65 |
public: |
66 | 66 |
typedef MapBase<K, V> Parent; |
67 | 67 |
typedef typename Parent::Key Key; |
68 | 68 |
typedef typename Parent::Value Value; |
69 | 69 |
|
70 | 70 |
/// Gives back a default constructed element. |
71 | 71 |
Value operator[](const Key&) const { return Value(); } |
72 | 72 |
/// Absorbs the value. |
73 | 73 |
void set(const Key&, const Value&) {} |
74 | 74 |
}; |
75 | 75 |
|
76 | 76 |
/// Returns a \ref NullMap class |
77 | 77 |
|
78 | 78 |
/// This function just returns a \ref NullMap class. |
79 | 79 |
/// \relates NullMap |
80 | 80 |
template <typename K, typename V> |
81 | 81 |
NullMap<K, V> nullMap() { |
82 | 82 |
return NullMap<K, V>(); |
83 | 83 |
} |
84 | 84 |
|
85 | 85 |
|
86 | 86 |
/// Constant map. |
87 | 87 |
|
88 | 88 |
/// This \ref concepts::ReadMap "readable map" assigns a specified |
89 | 89 |
/// value to each key. |
90 | 90 |
/// |
91 | 91 |
/// In other aspects it is equivalent to \ref NullMap. |
92 | 92 |
/// So it conforms the \ref concepts::ReadWriteMap "ReadWriteMap" |
93 | 93 |
/// concept, but it absorbs the data written to it. |
94 | 94 |
/// |
95 | 95 |
/// The simplest way of using this map is through the constMap() |
96 | 96 |
/// function. |
97 | 97 |
/// |
98 | 98 |
/// \sa NullMap |
99 | 99 |
/// \sa IdentityMap |
100 | 100 |
template<typename K, typename V> |
101 | 101 |
class ConstMap : public MapBase<K, V> { |
102 | 102 |
private: |
103 | 103 |
V _value; |
104 | 104 |
public: |
105 | 105 |
typedef MapBase<K, V> Parent; |
106 | 106 |
typedef typename Parent::Key Key; |
107 | 107 |
typedef typename Parent::Value Value; |
108 | 108 |
|
109 | 109 |
/// Default constructor |
110 | 110 |
|
111 | 111 |
/// Default constructor. |
112 | 112 |
/// The value of the map will be default constructed. |
113 | 113 |
ConstMap() {} |
114 | 114 |
|
115 | 115 |
/// Constructor with specified initial value |
116 | 116 |
|
117 | 117 |
/// Constructor with specified initial value. |
118 | 118 |
/// \param v The initial value of the map. |
119 | 119 |
ConstMap(const Value &v) : _value(v) {} |
120 | 120 |
|
121 | 121 |
/// Gives back the specified value. |
122 | 122 |
Value operator[](const Key&) const { return _value; } |
123 | 123 |
|
124 | 124 |
/// Absorbs the value. |
125 | 125 |
void set(const Key&, const Value&) {} |
126 | 126 |
|
127 | 127 |
/// Sets the value that is assigned to each key. |
128 | 128 |
void setAll(const Value &v) { |
129 | 129 |
_value = v; |
130 | 130 |
} |
131 | 131 |
|
132 | 132 |
template<typename V1> |
133 | 133 |
ConstMap(const ConstMap<K, V1> &, const Value &v) : _value(v) {} |
134 | 134 |
}; |
135 | 135 |
|
136 | 136 |
/// Returns a \ref ConstMap class |
137 | 137 |
|
138 | 138 |
/// This function just returns a \ref ConstMap class. |
139 | 139 |
/// \relates ConstMap |
140 | 140 |
template<typename K, typename V> |
141 | 141 |
inline ConstMap<K, V> constMap(const V &v) { |
142 | 142 |
return ConstMap<K, V>(v); |
143 | 143 |
} |
144 | 144 |
|
145 | 145 |
template<typename K, typename V> |
146 | 146 |
inline ConstMap<K, V> constMap() { |
147 | 147 |
return ConstMap<K, V>(); |
148 | 148 |
} |
149 | 149 |
|
150 | 150 |
|
151 | 151 |
template<typename T, T v> |
152 | 152 |
struct Const {}; |
153 | 153 |
|
154 | 154 |
/// Constant map with inlined constant value. |
155 | 155 |
|
156 | 156 |
/// This \ref concepts::ReadMap "readable map" assigns a specified |
157 | 157 |
/// value to each key. |
158 | 158 |
/// |
159 | 159 |
/// In other aspects it is equivalent to \ref NullMap. |
160 | 160 |
/// So it conforms the \ref concepts::ReadWriteMap "ReadWriteMap" |
161 | 161 |
/// concept, but it absorbs the data written to it. |
162 | 162 |
/// |
163 | 163 |
/// The simplest way of using this map is through the constMap() |
164 | 164 |
/// function. |
165 | 165 |
/// |
166 | 166 |
/// \sa NullMap |
167 | 167 |
/// \sa IdentityMap |
168 | 168 |
template<typename K, typename V, V v> |
169 | 169 |
class ConstMap<K, Const<V, v> > : public MapBase<K, V> { |
170 | 170 |
public: |
171 | 171 |
typedef MapBase<K, V> Parent; |
172 | 172 |
typedef typename Parent::Key Key; |
173 | 173 |
typedef typename Parent::Value Value; |
174 | 174 |
|
175 | 175 |
/// Constructor. |
176 | 176 |
ConstMap() {} |
177 | 177 |
|
178 | 178 |
/// Gives back the specified value. |
179 | 179 |
Value operator[](const Key&) const { return v; } |
180 | 180 |
|
181 | 181 |
/// Absorbs the value. |
182 | 182 |
void set(const Key&, const Value&) {} |
183 | 183 |
}; |
184 | 184 |
|
185 | 185 |
/// Returns a \ref ConstMap class with inlined constant value |
186 | 186 |
|
187 | 187 |
/// This function just returns a \ref ConstMap class with inlined |
188 | 188 |
/// constant value. |
189 | 189 |
/// \relates ConstMap |
190 | 190 |
template<typename K, typename V, V v> |
191 | 191 |
inline ConstMap<K, Const<V, v> > constMap() { |
192 | 192 |
return ConstMap<K, Const<V, v> >(); |
193 | 193 |
} |
194 | 194 |
|
195 | 195 |
|
196 | 196 |
/// Identity map. |
197 | 197 |
|
198 | 198 |
/// This \ref concepts::ReadMap "read-only map" gives back the given |
199 | 199 |
/// key as value without any modification. |
200 | 200 |
/// |
201 | 201 |
/// \sa ConstMap |
202 | 202 |
template <typename T> |
203 | 203 |
class IdentityMap : public MapBase<T, T> { |
204 | 204 |
public: |
205 | 205 |
typedef MapBase<T, T> Parent; |
206 | 206 |
typedef typename Parent::Key Key; |
207 | 207 |
typedef typename Parent::Value Value; |
208 | 208 |
|
209 | 209 |
/// Gives back the given value without any modification. |
210 | 210 |
Value operator[](const Key &k) const { |
211 | 211 |
return k; |
212 | 212 |
} |
213 | 213 |
}; |
214 | 214 |
|
215 | 215 |
/// Returns an \ref IdentityMap class |
216 | 216 |
|
217 | 217 |
/// This function just returns an \ref IdentityMap class. |
218 | 218 |
/// \relates IdentityMap |
219 | 219 |
template<typename T> |
220 | 220 |
inline IdentityMap<T> identityMap() { |
221 | 221 |
return IdentityMap<T>(); |
222 | 222 |
} |
223 | 223 |
|
224 | 224 |
|
225 | 225 |
/// \brief Map for storing values for integer keys from the range |
226 | 226 |
/// <tt>[0..size-1]</tt>. |
227 | 227 |
/// |
228 | 228 |
/// This map is essentially a wrapper for \c std::vector. It assigns |
229 | 229 |
/// values to integer keys from the range <tt>[0..size-1]</tt>. |
230 | 230 |
/// It can be used with some data structures, for example |
231 | 231 |
/// \ref UnionFind, \ref BinHeap, when the used items are small |
232 | 232 |
/// integers. This map conforms the \ref concepts::ReferenceMap |
233 | 233 |
/// "ReferenceMap" concept. |
234 | 234 |
/// |
235 | 235 |
/// The simplest way of using this map is through the rangeMap() |
236 | 236 |
/// function. |
237 | 237 |
template <typename V> |
238 | 238 |
class RangeMap : public MapBase<int, V> { |
239 | 239 |
template <typename V1> |
240 | 240 |
friend class RangeMap; |
241 | 241 |
private: |
242 | 242 |
|
243 | 243 |
typedef std::vector<V> Vector; |
244 | 244 |
Vector _vector; |
245 | 245 |
|
246 | 246 |
public: |
247 | 247 |
|
248 | 248 |
typedef MapBase<int, V> Parent; |
249 | 249 |
/// Key type |
250 | 250 |
typedef typename Parent::Key Key; |
251 | 251 |
/// Value type |
252 | 252 |
typedef typename Parent::Value Value; |
253 | 253 |
/// Reference type |
254 | 254 |
typedef typename Vector::reference Reference; |
255 | 255 |
/// Const reference type |
256 | 256 |
typedef typename Vector::const_reference ConstReference; |
257 | 257 |
|
258 | 258 |
typedef True ReferenceMapTag; |
259 | 259 |
|
260 | 260 |
public: |
261 | 261 |
|
262 | 262 |
/// Constructor with specified default value. |
263 | 263 |
RangeMap(int size = 0, const Value &value = Value()) |
264 | 264 |
: _vector(size, value) {} |
265 | 265 |
|
266 | 266 |
/// Constructs the map from an appropriate \c std::vector. |
267 | 267 |
template <typename V1> |
268 | 268 |
RangeMap(const std::vector<V1>& vector) |
269 | 269 |
: _vector(vector.begin(), vector.end()) {} |
270 | 270 |
|
271 | 271 |
/// Constructs the map from another \ref RangeMap. |
272 | 272 |
template <typename V1> |
273 | 273 |
RangeMap(const RangeMap<V1> &c) |
274 | 274 |
: _vector(c._vector.begin(), c._vector.end()) {} |
275 | 275 |
|
276 | 276 |
/// Returns the size of the map. |
277 | 277 |
int size() { |
278 | 278 |
return _vector.size(); |
279 | 279 |
} |
280 | 280 |
|
281 | 281 |
/// Resizes the map. |
282 | 282 |
|
283 | 283 |
/// Resizes the underlying \c std::vector container, so changes the |
284 | 284 |
/// keyset of the map. |
285 | 285 |
/// \param size The new size of the map. The new keyset will be the |
286 | 286 |
/// range <tt>[0..size-1]</tt>. |
287 | 287 |
/// \param value The default value to assign to the new keys. |
288 | 288 |
void resize(int size, const Value &value = Value()) { |
289 | 289 |
_vector.resize(size, value); |
290 | 290 |
} |
291 | 291 |
|
292 | 292 |
private: |
293 | 293 |
|
294 | 294 |
RangeMap& operator=(const RangeMap&); |
295 | 295 |
|
296 | 296 |
public: |
297 | 297 |
|
298 | 298 |
///\e |
299 | 299 |
Reference operator[](const Key &k) { |
300 | 300 |
return _vector[k]; |
301 | 301 |
} |
302 | 302 |
|
303 | 303 |
///\e |
304 | 304 |
ConstReference operator[](const Key &k) const { |
305 | 305 |
return _vector[k]; |
306 | 306 |
} |
307 | 307 |
|
308 | 308 |
///\e |
309 | 309 |
void set(const Key &k, const Value &v) { |
310 | 310 |
_vector[k] = v; |
311 | 311 |
} |
312 | 312 |
}; |
313 | 313 |
|
314 | 314 |
/// Returns a \ref RangeMap class |
315 | 315 |
|
316 | 316 |
/// This function just returns a \ref RangeMap class. |
317 | 317 |
/// \relates RangeMap |
318 | 318 |
template<typename V> |
319 | 319 |
inline RangeMap<V> rangeMap(int size = 0, const V &value = V()) { |
320 | 320 |
return RangeMap<V>(size, value); |
321 | 321 |
} |
322 | 322 |
|
323 | 323 |
/// \brief Returns a \ref RangeMap class created from an appropriate |
324 | 324 |
/// \c std::vector |
325 | 325 |
|
326 | 326 |
/// This function just returns a \ref RangeMap class created from an |
327 | 327 |
/// appropriate \c std::vector. |
328 | 328 |
/// \relates RangeMap |
329 | 329 |
template<typename V> |
330 | 330 |
inline RangeMap<V> rangeMap(const std::vector<V> &vector) { |
331 | 331 |
return RangeMap<V>(vector); |
332 | 332 |
} |
333 | 333 |
|
334 | 334 |
|
335 | 335 |
/// Map type based on \c std::map |
336 | 336 |
|
337 | 337 |
/// This map is essentially a wrapper for \c std::map with addition |
338 | 338 |
/// that you can specify a default value for the keys that are not |
339 | 339 |
/// stored actually. This value can be different from the default |
340 | 340 |
/// contructed value (i.e. \c %Value()). |
341 | 341 |
/// This type conforms the \ref concepts::ReferenceMap "ReferenceMap" |
342 | 342 |
/// concept. |
343 | 343 |
/// |
344 | 344 |
/// This map is useful if a default value should be assigned to most of |
345 | 345 |
/// the keys and different values should be assigned only to a few |
346 | 346 |
/// keys (i.e. the map is "sparse"). |
347 | 347 |
/// The name of this type also refers to this important usage. |
348 | 348 |
/// |
349 | 349 |
/// Apart form that this map can be used in many other cases since it |
350 | 350 |
/// is based on \c std::map, which is a general associative container. |
351 | 351 |
/// However keep in mind that it is usually not as efficient as other |
352 | 352 |
/// maps. |
353 | 353 |
/// |
354 | 354 |
/// The simplest way of using this map is through the sparseMap() |
355 | 355 |
/// function. |
356 | 356 |
template <typename K, typename V, typename Compare = std::less<K> > |
357 | 357 |
class SparseMap : public MapBase<K, V> { |
358 | 358 |
template <typename K1, typename V1, typename C1> |
359 | 359 |
friend class SparseMap; |
360 | 360 |
public: |
361 | 361 |
|
362 | 362 |
typedef MapBase<K, V> Parent; |
363 | 363 |
/// Key type |
364 | 364 |
typedef typename Parent::Key Key; |
365 | 365 |
/// Value type |
366 | 366 |
typedef typename Parent::Value Value; |
367 | 367 |
/// Reference type |
368 | 368 |
typedef Value& Reference; |
369 | 369 |
/// Const reference type |
370 | 370 |
typedef const Value& ConstReference; |
371 | 371 |
|
372 | 372 |
typedef True ReferenceMapTag; |
373 | 373 |
|
374 | 374 |
private: |
375 | 375 |
|
376 | 376 |
typedef std::map<K, V, Compare> Map; |
377 | 377 |
Map _map; |
378 | 378 |
Value _value; |
379 | 379 |
|
380 | 380 |
public: |
381 | 381 |
|
382 | 382 |
/// \brief Constructor with specified default value. |
383 | 383 |
SparseMap(const Value &value = Value()) : _value(value) {} |
384 | 384 |
/// \brief Constructs the map from an appropriate \c std::map, and |
385 | 385 |
/// explicitly specifies a default value. |
386 | 386 |
template <typename V1, typename Comp1> |
387 | 387 |
SparseMap(const std::map<Key, V1, Comp1> &map, |
388 | 388 |
const Value &value = Value()) |
389 | 389 |
: _map(map.begin(), map.end()), _value(value) {} |
390 | 390 |
|
391 | 391 |
/// \brief Constructs the map from another \ref SparseMap. |
392 | 392 |
template<typename V1, typename Comp1> |
393 | 393 |
SparseMap(const SparseMap<Key, V1, Comp1> &c) |
394 | 394 |
: _map(c._map.begin(), c._map.end()), _value(c._value) {} |
395 | 395 |
|
396 | 396 |
private: |
397 | 397 |
|
398 | 398 |
SparseMap& operator=(const SparseMap&); |
399 | 399 |
|
400 | 400 |
public: |
401 | 401 |
|
402 | 402 |
///\e |
403 | 403 |
Reference operator[](const Key &k) { |
404 | 404 |
typename Map::iterator it = _map.lower_bound(k); |
405 | 405 |
if (it != _map.end() && !_map.key_comp()(k, it->first)) |
406 | 406 |
return it->second; |
407 | 407 |
else |
408 | 408 |
return _map.insert(it, std::make_pair(k, _value))->second; |
409 | 409 |
} |
410 | 410 |
|
411 | 411 |
///\e |
412 | 412 |
ConstReference operator[](const Key &k) const { |
413 | 413 |
typename Map::const_iterator it = _map.find(k); |
414 | 414 |
if (it != _map.end()) |
415 | 415 |
return it->second; |
416 | 416 |
else |
417 | 417 |
return _value; |
418 | 418 |
} |
419 | 419 |
|
420 | 420 |
///\e |
421 | 421 |
void set(const Key &k, const Value &v) { |
422 | 422 |
typename Map::iterator it = _map.lower_bound(k); |
423 | 423 |
if (it != _map.end() && !_map.key_comp()(k, it->first)) |
424 | 424 |
it->second = v; |
425 | 425 |
else |
426 | 426 |
_map.insert(it, std::make_pair(k, v)); |
427 | 427 |
} |
428 | 428 |
|
429 | 429 |
///\e |
430 | 430 |
void setAll(const Value &v) { |
431 | 431 |
_value = v; |
432 | 432 |
_map.clear(); |
433 | 433 |
} |
434 | 434 |
}; |
435 | 435 |
|
436 | 436 |
/// Returns a \ref SparseMap class |
437 | 437 |
|
438 | 438 |
/// This function just returns a \ref SparseMap class with specified |
439 | 439 |
/// default value. |
440 | 440 |
/// \relates SparseMap |
441 | 441 |
template<typename K, typename V, typename Compare> |
442 | 442 |
inline SparseMap<K, V, Compare> sparseMap(const V& value = V()) { |
443 | 443 |
return SparseMap<K, V, Compare>(value); |
444 | 444 |
} |
445 | 445 |
|
446 | 446 |
template<typename K, typename V> |
447 | 447 |
inline SparseMap<K, V, std::less<K> > sparseMap(const V& value = V()) { |
448 | 448 |
return SparseMap<K, V, std::less<K> >(value); |
449 | 449 |
} |
450 | 450 |
|
451 | 451 |
/// \brief Returns a \ref SparseMap class created from an appropriate |
452 | 452 |
/// \c std::map |
453 | 453 |
|
454 | 454 |
/// This function just returns a \ref SparseMap class created from an |
455 | 455 |
/// appropriate \c std::map. |
456 | 456 |
/// \relates SparseMap |
457 | 457 |
template<typename K, typename V, typename Compare> |
458 | 458 |
inline SparseMap<K, V, Compare> |
459 | 459 |
sparseMap(const std::map<K, V, Compare> &map, const V& value = V()) |
460 | 460 |
{ |
461 | 461 |
return SparseMap<K, V, Compare>(map, value); |
462 | 462 |
} |
463 | 463 |
|
464 | 464 |
/// @} |
465 | 465 |
|
466 | 466 |
/// \addtogroup map_adaptors |
467 | 467 |
/// @{ |
468 | 468 |
|
469 | 469 |
/// Composition of two maps |
470 | 470 |
|
471 | 471 |
/// This \ref concepts::ReadMap "read-only map" returns the |
472 | 472 |
/// composition of two given maps. That is to say, if \c m1 is of |
473 | 473 |
/// type \c M1 and \c m2 is of \c M2, then for |
474 | 474 |
/// \code |
475 | 475 |
/// ComposeMap<M1, M2> cm(m1,m2); |
476 | 476 |
/// \endcode |
477 | 477 |
/// <tt>cm[x]</tt> will be equal to <tt>m1[m2[x]]</tt>. |
478 | 478 |
/// |
479 | 479 |
/// The \c Key type of the map is inherited from \c M2 and the |
480 | 480 |
/// \c Value type is from \c M1. |
481 | 481 |
/// \c M2::Value must be convertible to \c M1::Key. |
482 | 482 |
/// |
483 | 483 |
/// The simplest way of using this map is through the composeMap() |
484 | 484 |
/// function. |
485 | 485 |
/// |
486 | 486 |
/// \sa CombineMap |
487 |
/// |
|
488 |
/// \todo Check the requirements. |
|
489 | 487 |
template <typename M1, typename M2> |
490 | 488 |
class ComposeMap : public MapBase<typename M2::Key, typename M1::Value> { |
491 | 489 |
const M1 &_m1; |
492 | 490 |
const M2 &_m2; |
493 | 491 |
public: |
494 | 492 |
typedef MapBase<typename M2::Key, typename M1::Value> Parent; |
495 | 493 |
typedef typename Parent::Key Key; |
496 | 494 |
typedef typename Parent::Value Value; |
497 | 495 |
|
498 | 496 |
/// Constructor |
499 | 497 |
ComposeMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {} |
500 | 498 |
|
501 | 499 |
/// \e |
502 | 500 |
typename MapTraits<M1>::ConstReturnValue |
503 | 501 |
operator[](const Key &k) const { return _m1[_m2[k]]; } |
504 | 502 |
}; |
505 | 503 |
|
506 | 504 |
/// Returns a \ref ComposeMap class |
507 | 505 |
|
508 | 506 |
/// This function just returns a \ref ComposeMap class. |
509 | 507 |
/// |
510 | 508 |
/// If \c m1 and \c m2 are maps and the \c Value type of \c m2 is |
511 | 509 |
/// convertible to the \c Key of \c m1, then <tt>composeMap(m1,m2)[x]</tt> |
512 | 510 |
/// will be equal to <tt>m1[m2[x]]</tt>. |
513 | 511 |
/// |
514 | 512 |
/// \relates ComposeMap |
515 | 513 |
template <typename M1, typename M2> |
516 | 514 |
inline ComposeMap<M1, M2> composeMap(const M1 &m1, const M2 &m2) { |
517 | 515 |
return ComposeMap<M1, M2>(m1, m2); |
518 | 516 |
} |
519 | 517 |
|
520 | 518 |
|
521 | 519 |
/// Combination of two maps using an STL (binary) functor. |
522 | 520 |
|
523 | 521 |
/// This \ref concepts::ReadMap "read-only map" takes two maps and a |
524 | 522 |
/// binary functor and returns the combination of the two given maps |
525 | 523 |
/// using the functor. |
526 | 524 |
/// That is to say, if \c m1 is of type \c M1 and \c m2 is of \c M2 |
527 | 525 |
/// and \c f is of \c F, then for |
528 | 526 |
/// \code |
529 | 527 |
/// CombineMap<M1,M2,F,V> cm(m1,m2,f); |
530 | 528 |
/// \endcode |
531 | 529 |
/// <tt>cm[x]</tt> will be equal to <tt>f(m1[x],m2[x])</tt>. |
532 | 530 |
/// |
533 | 531 |
/// The \c Key type of the map is inherited from \c M1 (\c M1::Key |
534 | 532 |
/// must be convertible to \c M2::Key) and the \c Value type is \c V. |
535 | 533 |
/// \c M2::Value and \c M1::Value must be convertible to the |
536 | 534 |
/// corresponding input parameter of \c F and the return type of \c F |
537 | 535 |
/// must be convertible to \c V. |
538 | 536 |
/// |
539 | 537 |
/// The simplest way of using this map is through the combineMap() |
540 | 538 |
/// function. |
541 | 539 |
/// |
542 | 540 |
/// \sa ComposeMap |
543 |
/// |
|
544 |
/// \todo Check the requirements. |
|
545 | 541 |
template<typename M1, typename M2, typename F, |
546 | 542 |
typename V = typename F::result_type> |
547 | 543 |
class CombineMap : public MapBase<typename M1::Key, V> { |
548 | 544 |
const M1 &_m1; |
549 | 545 |
const M2 &_m2; |
550 | 546 |
F _f; |
551 | 547 |
public: |
552 | 548 |
typedef MapBase<typename M1::Key, V> Parent; |
553 | 549 |
typedef typename Parent::Key Key; |
554 | 550 |
typedef typename Parent::Value Value; |
555 | 551 |
|
556 | 552 |
/// Constructor |
557 | 553 |
CombineMap(const M1 &m1, const M2 &m2, const F &f = F()) |
558 | 554 |
: _m1(m1), _m2(m2), _f(f) {} |
559 | 555 |
/// \e |
560 | 556 |
Value operator[](const Key &k) const { return _f(_m1[k],_m2[k]); } |
561 | 557 |
}; |
562 | 558 |
|
563 | 559 |
/// Returns a \ref CombineMap class |
564 | 560 |
|
565 | 561 |
/// This function just returns a \ref CombineMap class. |
566 | 562 |
/// |
567 | 563 |
/// For example, if \c m1 and \c m2 are both maps with \c double |
568 | 564 |
/// values, then |
569 | 565 |
/// \code |
570 | 566 |
/// combineMap(m1,m2,std::plus<double>()) |
571 | 567 |
/// \endcode |
572 | 568 |
/// is equivalent to |
573 | 569 |
/// \code |
574 | 570 |
/// addMap(m1,m2) |
575 | 571 |
/// \endcode |
576 | 572 |
/// |
577 | 573 |
/// This function is specialized for adaptable binary function |
578 | 574 |
/// classes and C++ functions. |
579 | 575 |
/// |
580 | 576 |
/// \relates CombineMap |
581 | 577 |
template<typename M1, typename M2, typename F, typename V> |
582 | 578 |
inline CombineMap<M1, M2, F, V> |
583 | 579 |
combineMap(const M1 &m1, const M2 &m2, const F &f) { |
584 | 580 |
return CombineMap<M1, M2, F, V>(m1,m2,f); |
585 | 581 |
} |
586 | 582 |
|
587 | 583 |
template<typename M1, typename M2, typename F> |
588 | 584 |
inline CombineMap<M1, M2, F, typename F::result_type> |
589 | 585 |
combineMap(const M1 &m1, const M2 &m2, const F &f) { |
590 | 586 |
return combineMap<M1, M2, F, typename F::result_type>(m1,m2,f); |
591 | 587 |
} |
592 | 588 |
|
593 | 589 |
template<typename M1, typename M2, typename K1, typename K2, typename V> |
594 | 590 |
inline CombineMap<M1, M2, V (*)(K1, K2), V> |
595 | 591 |
combineMap(const M1 &m1, const M2 &m2, V (*f)(K1, K2)) { |
596 | 592 |
return combineMap<M1, M2, V (*)(K1, K2), V>(m1,m2,f); |
597 | 593 |
} |
598 | 594 |
|
599 | 595 |
|
600 | 596 |
/// Converts an STL style (unary) functor to a map |
601 | 597 |
|
602 | 598 |
/// This \ref concepts::ReadMap "read-only map" returns the value |
603 | 599 |
/// of a given functor. Actually, it just wraps the functor and |
604 | 600 |
/// provides the \c Key and \c Value typedefs. |
605 | 601 |
/// |
606 | 602 |
/// Template parameters \c K and \c V will become its \c Key and |
607 | 603 |
/// \c Value. In most cases they have to be given explicitly because |
608 | 604 |
/// a functor typically does not provide \c argument_type and |
609 | 605 |
/// \c result_type typedefs. |
610 | 606 |
/// Parameter \c F is the type of the used functor. |
611 | 607 |
/// |
612 | 608 |
/// The simplest way of using this map is through the functorToMap() |
613 | 609 |
/// function. |
614 | 610 |
/// |
615 | 611 |
/// \sa MapToFunctor |
616 | 612 |
template<typename F, |
617 | 613 |
typename K = typename F::argument_type, |
618 | 614 |
typename V = typename F::result_type> |
619 | 615 |
class FunctorToMap : public MapBase<K, V> { |
620 | 616 |
F _f; |
621 | 617 |
public: |
622 | 618 |
typedef MapBase<K, V> Parent; |
623 | 619 |
typedef typename Parent::Key Key; |
624 | 620 |
typedef typename Parent::Value Value; |
625 | 621 |
|
626 | 622 |
/// Constructor |
627 | 623 |
FunctorToMap(const F &f = F()) : _f(f) {} |
628 | 624 |
/// \e |
629 | 625 |
Value operator[](const Key &k) const { return _f(k); } |
630 | 626 |
}; |
631 | 627 |
|
632 | 628 |
/// Returns a \ref FunctorToMap class |
633 | 629 |
|
634 | 630 |
/// This function just returns a \ref FunctorToMap class. |
635 | 631 |
/// |
636 | 632 |
/// This function is specialized for adaptable binary function |
637 | 633 |
/// classes and C++ functions. |
638 | 634 |
/// |
639 | 635 |
/// \relates FunctorToMap |
640 | 636 |
template<typename K, typename V, typename F> |
641 | 637 |
inline FunctorToMap<F, K, V> functorToMap(const F &f) { |
642 | 638 |
return FunctorToMap<F, K, V>(f); |
643 | 639 |
} |
644 | 640 |
|
645 | 641 |
template <typename F> |
646 | 642 |
inline FunctorToMap<F, typename F::argument_type, typename F::result_type> |
647 | 643 |
functorToMap(const F &f) |
648 | 644 |
{ |
649 | 645 |
return FunctorToMap<F, typename F::argument_type, |
650 | 646 |
typename F::result_type>(f); |
651 | 647 |
} |
652 | 648 |
|
653 | 649 |
template <typename K, typename V> |
654 | 650 |
inline FunctorToMap<V (*)(K), K, V> functorToMap(V (*f)(K)) { |
655 | 651 |
return FunctorToMap<V (*)(K), K, V>(f); |
656 | 652 |
} |
657 | 653 |
|
658 | 654 |
|
659 | 655 |
/// Converts a map to an STL style (unary) functor |
660 | 656 |
|
661 | 657 |
/// This class converts a map to an STL style (unary) functor. |
662 | 658 |
/// That is it provides an <tt>operator()</tt> to read its values. |
663 | 659 |
/// |
664 | 660 |
/// For the sake of convenience it also works as a usual |
665 | 661 |
/// \ref concepts::ReadMap "readable map", i.e. <tt>operator[]</tt> |
666 | 662 |
/// and the \c Key and \c Value typedefs also exist. |
667 | 663 |
/// |
668 | 664 |
/// The simplest way of using this map is through the mapToFunctor() |
669 | 665 |
/// function. |
670 | 666 |
/// |
671 | 667 |
///\sa FunctorToMap |
672 | 668 |
template <typename M> |
673 | 669 |
class MapToFunctor : public MapBase<typename M::Key, typename M::Value> { |
674 | 670 |
const M &_m; |
675 | 671 |
public: |
676 | 672 |
typedef MapBase<typename M::Key, typename M::Value> Parent; |
677 | 673 |
typedef typename Parent::Key Key; |
678 | 674 |
typedef typename Parent::Value Value; |
679 | 675 |
|
680 | 676 |
typedef typename Parent::Key argument_type; |
681 | 677 |
typedef typename Parent::Value result_type; |
682 | 678 |
|
683 | 679 |
/// Constructor |
684 | 680 |
MapToFunctor(const M &m) : _m(m) {} |
685 | 681 |
/// \e |
686 | 682 |
Value operator()(const Key &k) const { return _m[k]; } |
687 | 683 |
/// \e |
688 | 684 |
Value operator[](const Key &k) const { return _m[k]; } |
689 | 685 |
}; |
690 | 686 |
|
691 | 687 |
/// Returns a \ref MapToFunctor class |
692 | 688 |
|
693 | 689 |
/// This function just returns a \ref MapToFunctor class. |
694 | 690 |
/// \relates MapToFunctor |
695 | 691 |
template<typename M> |
696 | 692 |
inline MapToFunctor<M> mapToFunctor(const M &m) { |
697 | 693 |
return MapToFunctor<M>(m); |
698 | 694 |
} |
699 | 695 |
|
700 | 696 |
|
701 | 697 |
/// \brief Map adaptor to convert the \c Value type of a map to |
702 | 698 |
/// another type using the default conversion. |
703 | 699 |
|
704 | 700 |
/// Map adaptor to convert the \c Value type of a \ref concepts::ReadMap |
705 | 701 |
/// "readable map" to another type using the default conversion. |
706 | 702 |
/// The \c Key type of it is inherited from \c M and the \c Value |
707 | 703 |
/// type is \c V. |
708 | 704 |
/// This type conforms the \ref concepts::ReadMap "ReadMap" concept. |
709 | 705 |
/// |
710 | 706 |
/// The simplest way of using this map is through the convertMap() |
711 | 707 |
/// function. |
712 | 708 |
template <typename M, typename V> |
713 | 709 |
class ConvertMap : public MapBase<typename M::Key, V> { |
714 | 710 |
const M &_m; |
715 | 711 |
public: |
716 | 712 |
typedef MapBase<typename M::Key, V> Parent; |
717 | 713 |
typedef typename Parent::Key Key; |
718 | 714 |
typedef typename Parent::Value Value; |
719 | 715 |
|
720 | 716 |
/// Constructor |
721 | 717 |
|
722 | 718 |
/// Constructor. |
723 | 719 |
/// \param m The underlying map. |
724 | 720 |
ConvertMap(const M &m) : _m(m) {} |
725 | 721 |
|
726 | 722 |
/// \e |
727 | 723 |
Value operator[](const Key &k) const { return _m[k]; } |
728 | 724 |
}; |
729 | 725 |
|
730 | 726 |
/// Returns a \ref ConvertMap class |
731 | 727 |
|
732 | 728 |
/// This function just returns a \ref ConvertMap class. |
733 | 729 |
/// \relates ConvertMap |
734 | 730 |
template<typename V, typename M> |
735 | 731 |
inline ConvertMap<M, V> convertMap(const M &map) { |
736 | 732 |
return ConvertMap<M, V>(map); |
737 | 733 |
} |
738 | 734 |
|
739 | 735 |
|
740 | 736 |
/// Applies all map setting operations to two maps |
741 | 737 |
|
742 | 738 |
/// This map has two \ref concepts::WriteMap "writable map" parameters |
743 | 739 |
/// and each write request will be passed to both of them. |
744 | 740 |
/// If \c M1 is also \ref concepts::ReadMap "readable", then the read |
745 | 741 |
/// operations will return the corresponding values of \c M1. |
746 | 742 |
/// |
747 | 743 |
/// The \c Key and \c Value types are inherited from \c M1. |
748 | 744 |
/// The \c Key and \c Value of \c M2 must be convertible from those |
749 | 745 |
/// of \c M1. |
750 | 746 |
/// |
751 | 747 |
/// The simplest way of using this map is through the forkMap() |
752 | 748 |
/// function. |
753 | 749 |
template<typename M1, typename M2> |
754 | 750 |
class ForkMap : public MapBase<typename M1::Key, typename M1::Value> { |
755 | 751 |
M1 &_m1; |
756 | 752 |
M2 &_m2; |
757 | 753 |
public: |
758 | 754 |
typedef MapBase<typename M1::Key, typename M1::Value> Parent; |
759 | 755 |
typedef typename Parent::Key Key; |
760 | 756 |
typedef typename Parent::Value Value; |
761 | 757 |
|
762 | 758 |
/// Constructor |
763 | 759 |
ForkMap(M1 &m1, M2 &m2) : _m1(m1), _m2(m2) {} |
764 | 760 |
/// Returns the value associated with the given key in the first map. |
765 | 761 |
Value operator[](const Key &k) const { return _m1[k]; } |
766 | 762 |
/// Sets the value associated with the given key in both maps. |
767 | 763 |
void set(const Key &k, const Value &v) { _m1.set(k,v); _m2.set(k,v); } |
768 | 764 |
}; |
769 | 765 |
|
770 | 766 |
/// Returns a \ref ForkMap class |
771 | 767 |
|
772 | 768 |
/// This function just returns a \ref ForkMap class. |
773 | 769 |
/// \relates ForkMap |
774 | 770 |
template <typename M1, typename M2> |
775 | 771 |
inline ForkMap<M1,M2> forkMap(M1 &m1, M2 &m2) { |
776 | 772 |
return ForkMap<M1,M2>(m1,m2); |
777 | 773 |
} |
778 | 774 |
|
779 | 775 |
|
780 | 776 |
/// Sum of two maps |
781 | 777 |
|
782 | 778 |
/// This \ref concepts::ReadMap "read-only map" returns the sum |
783 | 779 |
/// of the values of the two given maps. |
784 | 780 |
/// Its \c Key and \c Value types are inherited from \c M1. |
785 | 781 |
/// The \c Key and \c Value of \c M2 must be convertible to those of |
786 | 782 |
/// \c M1. |
787 | 783 |
/// |
788 | 784 |
/// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for |
789 | 785 |
/// \code |
790 | 786 |
/// AddMap<M1,M2> am(m1,m2); |
791 | 787 |
/// \endcode |
792 | 788 |
/// <tt>am[x]</tt> will be equal to <tt>m1[x]+m2[x]</tt>. |
793 | 789 |
/// |
794 | 790 |
/// The simplest way of using this map is through the addMap() |
795 | 791 |
/// function. |
796 | 792 |
/// |
797 | 793 |
/// \sa SubMap, MulMap, DivMap |
798 | 794 |
/// \sa ShiftMap, ShiftWriteMap |
799 | 795 |
template<typename M1, typename M2> |
800 | 796 |
class AddMap : public MapBase<typename M1::Key, typename M1::Value> { |
801 | 797 |
const M1 &_m1; |
802 | 798 |
const M2 &_m2; |
803 | 799 |
public: |
804 | 800 |
typedef MapBase<typename M1::Key, typename M1::Value> Parent; |
805 | 801 |
typedef typename Parent::Key Key; |
806 | 802 |
typedef typename Parent::Value Value; |
807 | 803 |
|
808 | 804 |
/// Constructor |
809 | 805 |
AddMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {} |
810 | 806 |
/// \e |
811 | 807 |
Value operator[](const Key &k) const { return _m1[k]+_m2[k]; } |
812 | 808 |
}; |
813 | 809 |
|
814 | 810 |
/// Returns an \ref AddMap class |
815 | 811 |
|
816 | 812 |
/// This function just returns an \ref AddMap class. |
817 | 813 |
/// |
818 | 814 |
/// For example, if \c m1 and \c m2 are both maps with \c double |
819 | 815 |
/// values, then <tt>addMap(m1,m2)[x]</tt> will be equal to |
820 | 816 |
/// <tt>m1[x]+m2[x]</tt>. |
821 | 817 |
/// |
822 | 818 |
/// \relates AddMap |
823 | 819 |
template<typename M1, typename M2> |
824 | 820 |
inline AddMap<M1, M2> addMap(const M1 &m1, const M2 &m2) { |
825 | 821 |
return AddMap<M1, M2>(m1,m2); |
826 | 822 |
} |
827 | 823 |
|
828 | 824 |
|
829 | 825 |
/// Difference of two maps |
830 | 826 |
|
831 | 827 |
/// This \ref concepts::ReadMap "read-only map" returns the difference |
832 | 828 |
/// of the values of the two given maps. |
833 | 829 |
/// Its \c Key and \c Value types are inherited from \c M1. |
834 | 830 |
/// The \c Key and \c Value of \c M2 must be convertible to those of |
835 | 831 |
/// \c M1. |
836 | 832 |
/// |
837 | 833 |
/// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for |
838 | 834 |
/// \code |
839 | 835 |
/// SubMap<M1,M2> sm(m1,m2); |
840 | 836 |
/// \endcode |
841 | 837 |
/// <tt>sm[x]</tt> will be equal to <tt>m1[x]-m2[x]</tt>. |
842 | 838 |
/// |
843 | 839 |
/// The simplest way of using this map is through the subMap() |
844 | 840 |
/// function. |
845 | 841 |
/// |
846 | 842 |
/// \sa AddMap, MulMap, DivMap |
847 | 843 |
template<typename M1, typename M2> |
848 | 844 |
class SubMap : public MapBase<typename M1::Key, typename M1::Value> { |
849 | 845 |
const M1 &_m1; |
850 | 846 |
const M2 &_m2; |
851 | 847 |
public: |
852 | 848 |
typedef MapBase<typename M1::Key, typename M1::Value> Parent; |
853 | 849 |
typedef typename Parent::Key Key; |
854 | 850 |
typedef typename Parent::Value Value; |
855 | 851 |
|
856 | 852 |
/// Constructor |
857 | 853 |
SubMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {} |
858 | 854 |
/// \e |
859 | 855 |
Value operator[](const Key &k) const { return _m1[k]-_m2[k]; } |
860 | 856 |
}; |
861 | 857 |
|
862 | 858 |
/// Returns a \ref SubMap class |
863 | 859 |
|
864 | 860 |
/// This function just returns a \ref SubMap class. |
865 | 861 |
/// |
866 | 862 |
/// For example, if \c m1 and \c m2 are both maps with \c double |
867 | 863 |
/// values, then <tt>subMap(m1,m2)[x]</tt> will be equal to |
868 | 864 |
/// <tt>m1[x]-m2[x]</tt>. |
869 | 865 |
/// |
870 | 866 |
/// \relates SubMap |
871 | 867 |
template<typename M1, typename M2> |
872 | 868 |
inline SubMap<M1, M2> subMap(const M1 &m1, const M2 &m2) { |
873 | 869 |
return SubMap<M1, M2>(m1,m2); |
874 | 870 |
} |
875 | 871 |
|
876 | 872 |
|
877 | 873 |
/// Product of two maps |
878 | 874 |
|
879 | 875 |
/// This \ref concepts::ReadMap "read-only map" returns the product |
880 | 876 |
/// of the values of the two given maps. |
881 | 877 |
/// Its \c Key and \c Value types are inherited from \c M1. |
882 | 878 |
/// The \c Key and \c Value of \c M2 must be convertible to those of |
883 | 879 |
/// \c M1. |
884 | 880 |
/// |
885 | 881 |
/// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for |
886 | 882 |
/// \code |
887 | 883 |
/// MulMap<M1,M2> mm(m1,m2); |
888 | 884 |
/// \endcode |
889 | 885 |
/// <tt>mm[x]</tt> will be equal to <tt>m1[x]*m2[x]</tt>. |
890 | 886 |
/// |
891 | 887 |
/// The simplest way of using this map is through the mulMap() |
892 | 888 |
/// function. |
893 | 889 |
/// |
894 | 890 |
/// \sa AddMap, SubMap, DivMap |
895 | 891 |
/// \sa ScaleMap, ScaleWriteMap |
896 | 892 |
template<typename M1, typename M2> |
897 | 893 |
class MulMap : public MapBase<typename M1::Key, typename M1::Value> { |
898 | 894 |
const M1 &_m1; |
899 | 895 |
const M2 &_m2; |
900 | 896 |
public: |
901 | 897 |
typedef MapBase<typename M1::Key, typename M1::Value> Parent; |
902 | 898 |
typedef typename Parent::Key Key; |
903 | 899 |
typedef typename Parent::Value Value; |
904 | 900 |
|
905 | 901 |
/// Constructor |
906 | 902 |
MulMap(const M1 &m1,const M2 &m2) : _m1(m1), _m2(m2) {} |
907 | 903 |
/// \e |
908 | 904 |
Value operator[](const Key &k) const { return _m1[k]*_m2[k]; } |
909 | 905 |
}; |
910 | 906 |
|
911 | 907 |
/// Returns a \ref MulMap class |
912 | 908 |
|
913 | 909 |
/// This function just returns a \ref MulMap class. |
914 | 910 |
/// |
915 | 911 |
/// For example, if \c m1 and \c m2 are both maps with \c double |
916 | 912 |
/// values, then <tt>mulMap(m1,m2)[x]</tt> will be equal to |
917 | 913 |
/// <tt>m1[x]*m2[x]</tt>. |
918 | 914 |
/// |
919 | 915 |
/// \relates MulMap |
920 | 916 |
template<typename M1, typename M2> |
921 | 917 |
inline MulMap<M1, M2> mulMap(const M1 &m1,const M2 &m2) { |
922 | 918 |
return MulMap<M1, M2>(m1,m2); |
923 | 919 |
} |
924 | 920 |
|
925 | 921 |
|
926 | 922 |
/// Quotient of two maps |
927 | 923 |
|
928 | 924 |
/// This \ref concepts::ReadMap "read-only map" returns the quotient |
929 | 925 |
/// of the values of the two given maps. |
930 | 926 |
/// Its \c Key and \c Value types are inherited from \c M1. |
931 | 927 |
/// The \c Key and \c Value of \c M2 must be convertible to those of |
932 | 928 |
/// \c M1. |
933 | 929 |
/// |
934 | 930 |
/// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for |
935 | 931 |
/// \code |
936 | 932 |
/// DivMap<M1,M2> dm(m1,m2); |
937 | 933 |
/// \endcode |
938 | 934 |
/// <tt>dm[x]</tt> will be equal to <tt>m1[x]/m2[x]</tt>. |
939 | 935 |
/// |
940 | 936 |
/// The simplest way of using this map is through the divMap() |
941 | 937 |
/// function. |
942 | 938 |
/// |
943 | 939 |
/// \sa AddMap, SubMap, MulMap |
944 | 940 |
template<typename M1, typename M2> |
945 | 941 |
class DivMap : public MapBase<typename M1::Key, typename M1::Value> { |
946 | 942 |
const M1 &_m1; |
947 | 943 |
const M2 &_m2; |
948 | 944 |
public: |
949 | 945 |
typedef MapBase<typename M1::Key, typename M1::Value> Parent; |
950 | 946 |
typedef typename Parent::Key Key; |
951 | 947 |
typedef typename Parent::Value Value; |
952 | 948 |
|
953 | 949 |
/// Constructor |
954 | 950 |
DivMap(const M1 &m1,const M2 &m2) : _m1(m1), _m2(m2) {} |
955 | 951 |
/// \e |
956 | 952 |
Value operator[](const Key &k) const { return _m1[k]/_m2[k]; } |
957 | 953 |
}; |
958 | 954 |
|
959 | 955 |
/// Returns a \ref DivMap class |
960 | 956 |
|
961 | 957 |
/// This function just returns a \ref DivMap class. |
962 | 958 |
/// |
963 | 959 |
/// For example, if \c m1 and \c m2 are both maps with \c double |
964 | 960 |
/// values, then <tt>divMap(m1,m2)[x]</tt> will be equal to |
965 | 961 |
/// <tt>m1[x]/m2[x]</tt>. |
966 | 962 |
/// |
967 | 963 |
/// \relates DivMap |
968 | 964 |
template<typename M1, typename M2> |
969 | 965 |
inline DivMap<M1, M2> divMap(const M1 &m1,const M2 &m2) { |
970 | 966 |
return DivMap<M1, M2>(m1,m2); |
971 | 967 |
} |
972 | 968 |
|
973 | 969 |
|
974 | 970 |
/// Shifts a map with a constant. |
975 | 971 |
|
976 | 972 |
/// This \ref concepts::ReadMap "read-only map" returns the sum of |
977 | 973 |
/// the given map and a constant value (i.e. it shifts the map with |
978 | 974 |
/// the constant). Its \c Key and \c Value are inherited from \c M. |
979 | 975 |
/// |
980 | 976 |
/// Actually, |
981 | 977 |
/// \code |
982 | 978 |
/// ShiftMap<M> sh(m,v); |
983 | 979 |
/// \endcode |
984 | 980 |
/// is equivalent to |
985 | 981 |
/// \code |
986 | 982 |
/// ConstMap<M::Key, M::Value> cm(v); |
987 | 983 |
/// AddMap<M, ConstMap<M::Key, M::Value> > sh(m,cm); |
988 | 984 |
/// \endcode |
989 | 985 |
/// |
990 | 986 |
/// The simplest way of using this map is through the shiftMap() |
991 | 987 |
/// function. |
992 | 988 |
/// |
993 | 989 |
/// \sa ShiftWriteMap |
994 | 990 |
template<typename M, typename C = typename M::Value> |
995 | 991 |
class ShiftMap : public MapBase<typename M::Key, typename M::Value> { |
996 | 992 |
const M &_m; |
997 | 993 |
C _v; |
998 | 994 |
public: |
999 | 995 |
typedef MapBase<typename M::Key, typename M::Value> Parent; |
1000 | 996 |
typedef typename Parent::Key Key; |
1001 | 997 |
typedef typename Parent::Value Value; |
1002 | 998 |
|
1003 | 999 |
/// Constructor |
1004 | 1000 |
|
1005 | 1001 |
/// Constructor. |
1006 | 1002 |
/// \param m The undelying map. |
1007 | 1003 |
/// \param v The constant value. |
1008 | 1004 |
ShiftMap(const M &m, const C &v) : _m(m), _v(v) {} |
1009 | 1005 |
/// \e |
1010 | 1006 |
Value operator[](const Key &k) const { return _m[k]+_v; } |
1011 | 1007 |
}; |
1012 | 1008 |
|
1013 | 1009 |
/// Shifts a map with a constant (read-write version). |
1014 | 1010 |
|
1015 | 1011 |
/// This \ref concepts::ReadWriteMap "read-write map" returns the sum |
1016 | 1012 |
/// of the given map and a constant value (i.e. it shifts the map with |
1017 | 1013 |
/// the constant). Its \c Key and \c Value are inherited from \c M. |
1018 | 1014 |
/// It makes also possible to write the map. |
1019 | 1015 |
/// |
1020 | 1016 |
/// The simplest way of using this map is through the shiftWriteMap() |
1021 | 1017 |
/// function. |
1022 | 1018 |
/// |
1023 | 1019 |
/// \sa ShiftMap |
1024 | 1020 |
template<typename M, typename C = typename M::Value> |
1025 | 1021 |
class ShiftWriteMap : public MapBase<typename M::Key, typename M::Value> { |
1026 | 1022 |
M &_m; |
1027 | 1023 |
C _v; |
1028 | 1024 |
public: |
1029 | 1025 |
typedef MapBase<typename M::Key, typename M::Value> Parent; |
1030 | 1026 |
typedef typename Parent::Key Key; |
1031 | 1027 |
typedef typename Parent::Value Value; |
1032 | 1028 |
|
1033 | 1029 |
/// Constructor |
1034 | 1030 |
|
1035 | 1031 |
/// Constructor. |
1036 | 1032 |
/// \param m The undelying map. |
1037 | 1033 |
/// \param v The constant value. |
1038 | 1034 |
ShiftWriteMap(M &m, const C &v) : _m(m), _v(v) {} |
1039 | 1035 |
/// \e |
1040 | 1036 |
Value operator[](const Key &k) const { return _m[k]+_v; } |
1041 | 1037 |
/// \e |
1042 | 1038 |
void set(const Key &k, const Value &v) { _m.set(k, v-_v); } |
1043 | 1039 |
}; |
1044 | 1040 |
|
1045 | 1041 |
/// Returns a \ref ShiftMap class |
1046 | 1042 |
|
1047 | 1043 |
/// This function just returns a \ref ShiftMap class. |
1048 | 1044 |
/// |
1049 | 1045 |
/// For example, if \c m is a map with \c double values and \c v is |
1050 | 1046 |
/// \c double, then <tt>shiftMap(m,v)[x]</tt> will be equal to |
1051 | 1047 |
/// <tt>m[x]+v</tt>. |
1052 | 1048 |
/// |
1053 | 1049 |
/// \relates ShiftMap |
1054 | 1050 |
template<typename M, typename C> |
1055 | 1051 |
inline ShiftMap<M, C> shiftMap(const M &m, const C &v) { |
1056 | 1052 |
return ShiftMap<M, C>(m,v); |
1057 | 1053 |
} |
1058 | 1054 |
|
1059 | 1055 |
/// Returns a \ref ShiftWriteMap class |
1060 | 1056 |
|
1061 | 1057 |
/// This function just returns a \ref ShiftWriteMap class. |
1062 | 1058 |
/// |
1063 | 1059 |
/// For example, if \c m is a map with \c double values and \c v is |
1064 | 1060 |
/// \c double, then <tt>shiftWriteMap(m,v)[x]</tt> will be equal to |
1065 | 1061 |
/// <tt>m[x]+v</tt>. |
1066 | 1062 |
/// Moreover it makes also possible to write the map. |
1067 | 1063 |
/// |
1068 | 1064 |
/// \relates ShiftWriteMap |
1069 | 1065 |
template<typename M, typename C> |
1070 | 1066 |
inline ShiftWriteMap<M, C> shiftWriteMap(M &m, const C &v) { |
1071 | 1067 |
return ShiftWriteMap<M, C>(m,v); |
1072 | 1068 |
} |
1073 | 1069 |
|
1074 | 1070 |
|
1075 | 1071 |
/// Scales a map with a constant. |
1076 | 1072 |
|
1077 | 1073 |
/// This \ref concepts::ReadMap "read-only map" returns the value of |
1078 | 1074 |
/// the given map multiplied from the left side with a constant value. |
1079 | 1075 |
/// Its \c Key and \c Value are inherited from \c M. |
1080 | 1076 |
/// |
1081 | 1077 |
/// Actually, |
1082 | 1078 |
/// \code |
1083 | 1079 |
/// ScaleMap<M> sc(m,v); |
1084 | 1080 |
/// \endcode |
1085 | 1081 |
/// is equivalent to |
1086 | 1082 |
/// \code |
1087 | 1083 |
/// ConstMap<M::Key, M::Value> cm(v); |
1088 | 1084 |
/// MulMap<ConstMap<M::Key, M::Value>, M> sc(cm,m); |
1089 | 1085 |
/// \endcode |
1090 | 1086 |
/// |
1091 | 1087 |
/// The simplest way of using this map is through the scaleMap() |
1092 | 1088 |
/// function. |
1093 | 1089 |
/// |
1094 | 1090 |
/// \sa ScaleWriteMap |
1095 | 1091 |
template<typename M, typename C = typename M::Value> |
1096 | 1092 |
class ScaleMap : public MapBase<typename M::Key, typename M::Value> { |
1097 | 1093 |
const M &_m; |
1098 | 1094 |
C _v; |
1099 | 1095 |
public: |
1100 | 1096 |
typedef MapBase<typename M::Key, typename M::Value> Parent; |
1101 | 1097 |
typedef typename Parent::Key Key; |
1102 | 1098 |
typedef typename Parent::Value Value; |
1103 | 1099 |
|
1104 | 1100 |
/// Constructor |
1105 | 1101 |
|
1106 | 1102 |
/// Constructor. |
1107 | 1103 |
/// \param m The undelying map. |
1108 | 1104 |
/// \param v The constant value. |
1109 | 1105 |
ScaleMap(const M &m, const C &v) : _m(m), _v(v) {} |
1110 | 1106 |
/// \e |
1111 | 1107 |
Value operator[](const Key &k) const { return _v*_m[k]; } |
1112 | 1108 |
}; |
1113 | 1109 |
|
1114 | 1110 |
/// Scales a map with a constant (read-write version). |
1115 | 1111 |
|
1116 | 1112 |
/// This \ref concepts::ReadWriteMap "read-write map" returns the value of |
1117 | 1113 |
/// the given map multiplied from the left side with a constant value. |
1118 | 1114 |
/// Its \c Key and \c Value are inherited from \c M. |
1119 | 1115 |
/// It can also be used as write map if the \c / operator is defined |
1120 | 1116 |
/// between \c Value and \c C and the given multiplier is not zero. |
1121 | 1117 |
/// |
1122 | 1118 |
/// The simplest way of using this map is through the scaleWriteMap() |
1123 | 1119 |
/// function. |
1124 | 1120 |
/// |
1125 | 1121 |
/// \sa ScaleMap |
1126 | 1122 |
template<typename M, typename C = typename M::Value> |
1127 | 1123 |
class ScaleWriteMap : public MapBase<typename M::Key, typename M::Value> { |
1128 | 1124 |
M &_m; |
1129 | 1125 |
C _v; |
1130 | 1126 |
public: |
1131 | 1127 |
typedef MapBase<typename M::Key, typename M::Value> Parent; |
1132 | 1128 |
typedef typename Parent::Key Key; |
1133 | 1129 |
typedef typename Parent::Value Value; |
1134 | 1130 |
|
1135 | 1131 |
/// Constructor |
1136 | 1132 |
|
1137 | 1133 |
/// Constructor. |
1138 | 1134 |
/// \param m The undelying map. |
1139 | 1135 |
/// \param v The constant value. |
1140 | 1136 |
ScaleWriteMap(M &m, const C &v) : _m(m), _v(v) {} |
1141 | 1137 |
/// \e |
1142 | 1138 |
Value operator[](const Key &k) const { return _v*_m[k]; } |
1143 | 1139 |
/// \e |
1144 | 1140 |
void set(const Key &k, const Value &v) { _m.set(k, v/_v); } |
1145 | 1141 |
}; |
1146 | 1142 |
|
1147 | 1143 |
/// Returns a \ref ScaleMap class |
1148 | 1144 |
|
1149 | 1145 |
/// This function just returns a \ref ScaleMap class. |
1150 | 1146 |
/// |
1151 | 1147 |
/// For example, if \c m is a map with \c double values and \c v is |
1152 | 1148 |
/// \c double, then <tt>scaleMap(m,v)[x]</tt> will be equal to |
1153 | 1149 |
/// <tt>v*m[x]</tt>. |
1154 | 1150 |
/// |
1155 | 1151 |
/// \relates ScaleMap |
1156 | 1152 |
template<typename M, typename C> |
1157 | 1153 |
inline ScaleMap<M, C> scaleMap(const M &m, const C &v) { |
1158 | 1154 |
return ScaleMap<M, C>(m,v); |
1159 | 1155 |
} |
1160 | 1156 |
|
1161 | 1157 |
/// Returns a \ref ScaleWriteMap class |
1162 | 1158 |
|
1163 | 1159 |
/// This function just returns a \ref ScaleWriteMap class. |
1164 | 1160 |
/// |
1165 | 1161 |
/// For example, if \c m is a map with \c double values and \c v is |
1166 | 1162 |
/// \c double, then <tt>scaleWriteMap(m,v)[x]</tt> will be equal to |
1167 | 1163 |
/// <tt>v*m[x]</tt>. |
1168 | 1164 |
/// Moreover it makes also possible to write the map. |
1169 | 1165 |
/// |
1170 | 1166 |
/// \relates ScaleWriteMap |
1171 | 1167 |
template<typename M, typename C> |
1172 | 1168 |
inline ScaleWriteMap<M, C> scaleWriteMap(M &m, const C &v) { |
1173 | 1169 |
return ScaleWriteMap<M, C>(m,v); |
1174 | 1170 |
} |
1175 | 1171 |
|
1176 | 1172 |
|
1177 | 1173 |
/// Negative of a map |
1178 | 1174 |
|
1179 | 1175 |
/// This \ref concepts::ReadMap "read-only map" returns the negative |
1180 | 1176 |
/// of the values of the given map (using the unary \c - operator). |
1181 | 1177 |
/// Its \c Key and \c Value are inherited from \c M. |
1182 | 1178 |
/// |
1183 | 1179 |
/// If M::Value is \c int, \c double etc., then |
1184 | 1180 |
/// \code |
1185 | 1181 |
/// NegMap<M> neg(m); |
1186 | 1182 |
/// \endcode |
1187 | 1183 |
/// is equivalent to |
1188 | 1184 |
/// \code |
1189 | 1185 |
/// ScaleMap<M> neg(m,-1); |
1190 | 1186 |
/// \endcode |
1191 | 1187 |
/// |
1192 | 1188 |
/// The simplest way of using this map is through the negMap() |
1193 | 1189 |
/// function. |
1194 | 1190 |
/// |
1195 | 1191 |
/// \sa NegWriteMap |
1196 | 1192 |
template<typename M> |
1197 | 1193 |
class NegMap : public MapBase<typename M::Key, typename M::Value> { |
1198 | 1194 |
const M& _m; |
1199 | 1195 |
public: |
1200 | 1196 |
typedef MapBase<typename M::Key, typename M::Value> Parent; |
1201 | 1197 |
typedef typename Parent::Key Key; |
1202 | 1198 |
typedef typename Parent::Value Value; |
1203 | 1199 |
|
1204 | 1200 |
/// Constructor |
1205 | 1201 |
NegMap(const M &m) : _m(m) {} |
1206 | 1202 |
/// \e |
1207 | 1203 |
Value operator[](const Key &k) const { return -_m[k]; } |
1208 | 1204 |
}; |
1209 | 1205 |
|
1210 | 1206 |
/// Negative of a map (read-write version) |
1211 | 1207 |
|
1212 | 1208 |
/// This \ref concepts::ReadWriteMap "read-write map" returns the |
1213 | 1209 |
/// negative of the values of the given map (using the unary \c - |
1214 | 1210 |
/// operator). |
1215 | 1211 |
/// Its \c Key and \c Value are inherited from \c M. |
1216 | 1212 |
/// It makes also possible to write the map. |
1217 | 1213 |
/// |
1218 | 1214 |
/// If M::Value is \c int, \c double etc., then |
1219 | 1215 |
/// \code |
1220 | 1216 |
/// NegWriteMap<M> neg(m); |
1221 | 1217 |
/// \endcode |
1222 | 1218 |
/// is equivalent to |
1223 | 1219 |
/// \code |
1224 | 1220 |
/// ScaleWriteMap<M> neg(m,-1); |
1225 | 1221 |
/// \endcode |
1226 | 1222 |
/// |
1227 | 1223 |
/// The simplest way of using this map is through the negWriteMap() |
1228 | 1224 |
/// function. |
1229 | 1225 |
/// |
1230 | 1226 |
/// \sa NegMap |
1231 | 1227 |
template<typename M> |
1232 | 1228 |
class NegWriteMap : public MapBase<typename M::Key, typename M::Value> { |
1233 | 1229 |
M &_m; |
1234 | 1230 |
public: |
1235 | 1231 |
typedef MapBase<typename M::Key, typename M::Value> Parent; |
1236 | 1232 |
typedef typename Parent::Key Key; |
1237 | 1233 |
typedef typename Parent::Value Value; |
1238 | 1234 |
|
1239 | 1235 |
/// Constructor |
1240 | 1236 |
NegWriteMap(M &m) : _m(m) {} |
1241 | 1237 |
/// \e |
1242 | 1238 |
Value operator[](const Key &k) const { return -_m[k]; } |
1243 | 1239 |
/// \e |
1244 | 1240 |
void set(const Key &k, const Value &v) { _m.set(k, -v); } |
1245 | 1241 |
}; |
1246 | 1242 |
|
1247 | 1243 |
/// Returns a \ref NegMap class |
1248 | 1244 |
|
1249 | 1245 |
/// This function just returns a \ref NegMap class. |
1250 | 1246 |
/// |
1251 | 1247 |
/// For example, if \c m is a map with \c double values, then |
1252 | 1248 |
/// <tt>negMap(m)[x]</tt> will be equal to <tt>-m[x]</tt>. |
1253 | 1249 |
/// |
1254 | 1250 |
/// \relates NegMap |
1255 | 1251 |
template <typename M> |
1256 | 1252 |
inline NegMap<M> negMap(const M &m) { |
1257 | 1253 |
return NegMap<M>(m); |
1258 | 1254 |
} |
1259 | 1255 |
|
1260 | 1256 |
/// Returns a \ref NegWriteMap class |
1261 | 1257 |
|
1262 | 1258 |
/// This function just returns a \ref NegWriteMap class. |
1263 | 1259 |
/// |
1264 | 1260 |
/// For example, if \c m is a map with \c double values, then |
1265 | 1261 |
/// <tt>negWriteMap(m)[x]</tt> will be equal to <tt>-m[x]</tt>. |
1266 | 1262 |
/// Moreover it makes also possible to write the map. |
1267 | 1263 |
/// |
1268 | 1264 |
/// \relates NegWriteMap |
1269 | 1265 |
template <typename M> |
1270 | 1266 |
inline NegWriteMap<M> negWriteMap(M &m) { |
1271 | 1267 |
return NegWriteMap<M>(m); |
1272 | 1268 |
} |
1273 | 1269 |
|
1274 | 1270 |
|
1275 | 1271 |
/// Absolute value of a map |
1276 | 1272 |
|
1277 | 1273 |
/// This \ref concepts::ReadMap "read-only map" returns the absolute |
1278 | 1274 |
/// value of the values of the given map. |
1279 | 1275 |
/// Its \c Key and \c Value are inherited from \c M. |
1280 | 1276 |
/// \c Value must be comparable to \c 0 and the unary \c - |
1281 | 1277 |
/// operator must be defined for it, of course. |
1282 | 1278 |
/// |
1283 | 1279 |
/// The simplest way of using this map is through the absMap() |
1284 | 1280 |
/// function. |
1285 | 1281 |
template<typename M> |
1286 | 1282 |
class AbsMap : public MapBase<typename M::Key, typename M::Value> { |
1287 | 1283 |
const M &_m; |
1288 | 1284 |
public: |
1289 | 1285 |
typedef MapBase<typename M::Key, typename M::Value> Parent; |
1290 | 1286 |
typedef typename Parent::Key Key; |
1291 | 1287 |
typedef typename Parent::Value Value; |
1292 | 1288 |
|
1293 | 1289 |
/// Constructor |
1294 | 1290 |
AbsMap(const M &m) : _m(m) {} |
1295 | 1291 |
/// \e |
1296 | 1292 |
Value operator[](const Key &k) const { |
1297 | 1293 |
Value tmp = _m[k]; |
1298 | 1294 |
return tmp >= 0 ? tmp : -tmp; |
1299 | 1295 |
} |
1300 | 1296 |
|
1301 | 1297 |
}; |
1302 | 1298 |
|
1303 | 1299 |
/// Returns an \ref AbsMap class |
1304 | 1300 |
|
1305 | 1301 |
/// This function just returns an \ref AbsMap class. |
1306 | 1302 |
/// |
1307 | 1303 |
/// For example, if \c m is a map with \c double values, then |
1308 | 1304 |
/// <tt>absMap(m)[x]</tt> will be equal to <tt>m[x]</tt> if |
1309 | 1305 |
/// it is positive or zero and <tt>-m[x]</tt> if <tt>m[x]</tt> is |
1310 | 1306 |
/// negative. |
1311 | 1307 |
/// |
1312 | 1308 |
/// \relates AbsMap |
... | ... |
@@ -56,955 +56,954 @@ |
56 | 56 |
* |
57 | 57 |
* Any feedback is very welcome. |
58 | 58 |
* http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html |
59 | 59 |
* email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) |
60 | 60 |
*/ |
61 | 61 |
|
62 | 62 |
#ifndef LEMON_RANDOM_H |
63 | 63 |
#define LEMON_RANDOM_H |
64 | 64 |
|
65 | 65 |
#include <algorithm> |
66 | 66 |
#include <iterator> |
67 | 67 |
#include <vector> |
68 | 68 |
#include <limits> |
69 | 69 |
#include <fstream> |
70 | 70 |
|
71 | 71 |
#include <lemon/math.h> |
72 | 72 |
#include <lemon/dim2.h> |
73 | 73 |
|
74 | 74 |
#ifndef WIN32 |
75 | 75 |
#include <sys/time.h> |
76 | 76 |
#include <ctime> |
77 | 77 |
#include <sys/types.h> |
78 | 78 |
#include <unistd.h> |
79 | 79 |
#else |
80 | 80 |
#include <windows.h> |
81 | 81 |
#endif |
82 | 82 |
|
83 | 83 |
///\ingroup misc |
84 | 84 |
///\file |
85 | 85 |
///\brief Mersenne Twister random number generator |
86 | 86 |
|
87 | 87 |
namespace lemon { |
88 | 88 |
|
89 | 89 |
namespace _random_bits { |
90 | 90 |
|
91 | 91 |
template <typename _Word, int _bits = std::numeric_limits<_Word>::digits> |
92 | 92 |
struct RandomTraits {}; |
93 | 93 |
|
94 | 94 |
template <typename _Word> |
95 | 95 |
struct RandomTraits<_Word, 32> { |
96 | 96 |
|
97 | 97 |
typedef _Word Word; |
98 | 98 |
static const int bits = 32; |
99 | 99 |
|
100 | 100 |
static const int length = 624; |
101 | 101 |
static const int shift = 397; |
102 | 102 |
|
103 | 103 |
static const Word mul = 0x6c078965u; |
104 | 104 |
static const Word arrayInit = 0x012BD6AAu; |
105 | 105 |
static const Word arrayMul1 = 0x0019660Du; |
106 | 106 |
static const Word arrayMul2 = 0x5D588B65u; |
107 | 107 |
|
108 | 108 |
static const Word mask = 0x9908B0DFu; |
109 | 109 |
static const Word loMask = (1u << 31) - 1; |
110 | 110 |
static const Word hiMask = ~loMask; |
111 | 111 |
|
112 | 112 |
|
113 | 113 |
static Word tempering(Word rnd) { |
114 | 114 |
rnd ^= (rnd >> 11); |
115 | 115 |
rnd ^= (rnd << 7) & 0x9D2C5680u; |
116 | 116 |
rnd ^= (rnd << 15) & 0xEFC60000u; |
117 | 117 |
rnd ^= (rnd >> 18); |
118 | 118 |
return rnd; |
119 | 119 |
} |
120 | 120 |
|
121 | 121 |
}; |
122 | 122 |
|
123 | 123 |
template <typename _Word> |
124 | 124 |
struct RandomTraits<_Word, 64> { |
125 | 125 |
|
126 | 126 |
typedef _Word Word; |
127 | 127 |
static const int bits = 64; |
128 | 128 |
|
129 | 129 |
static const int length = 312; |
130 | 130 |
static const int shift = 156; |
131 | 131 |
|
132 | 132 |
static const Word mul = Word(0x5851F42Du) << 32 | Word(0x4C957F2Du); |
133 | 133 |
static const Word arrayInit = Word(0x00000000u) << 32 |Word(0x012BD6AAu); |
134 | 134 |
static const Word arrayMul1 = Word(0x369DEA0Fu) << 32 |Word(0x31A53F85u); |
135 | 135 |
static const Word arrayMul2 = Word(0x27BB2EE6u) << 32 |Word(0x87B0B0FDu); |
136 | 136 |
|
137 | 137 |
static const Word mask = Word(0xB5026F5Au) << 32 | Word(0xA96619E9u); |
138 | 138 |
static const Word loMask = (Word(1u) << 31) - 1; |
139 | 139 |
static const Word hiMask = ~loMask; |
140 | 140 |
|
141 | 141 |
static Word tempering(Word rnd) { |
142 | 142 |
rnd ^= (rnd >> 29) & (Word(0x55555555u) << 32 | Word(0x55555555u)); |
143 | 143 |
rnd ^= (rnd << 17) & (Word(0x71D67FFFu) << 32 | Word(0xEDA60000u)); |
144 | 144 |
rnd ^= (rnd << 37) & (Word(0xFFF7EEE0u) << 32 | Word(0x00000000u)); |
145 | 145 |
rnd ^= (rnd >> 43); |
146 | 146 |
return rnd; |
147 | 147 |
} |
148 | 148 |
|
149 | 149 |
}; |
150 | 150 |
|
151 | 151 |
template <typename _Word> |
152 | 152 |
class RandomCore { |
153 | 153 |
public: |
154 | 154 |
|
155 | 155 |
typedef _Word Word; |
156 | 156 |
|
157 | 157 |
private: |
158 | 158 |
|
159 | 159 |
static const int bits = RandomTraits<Word>::bits; |
160 | 160 |
|
161 | 161 |
static const int length = RandomTraits<Word>::length; |
162 | 162 |
static const int shift = RandomTraits<Word>::shift; |
163 | 163 |
|
164 | 164 |
public: |
165 | 165 |
|
166 | 166 |
void initState() { |
167 | 167 |
static const Word seedArray[4] = { |
168 | 168 |
0x12345u, 0x23456u, 0x34567u, 0x45678u |
169 | 169 |
}; |
170 | 170 |
|
171 | 171 |
initState(seedArray, seedArray + 4); |
172 | 172 |
} |
173 | 173 |
|
174 | 174 |
void initState(Word seed) { |
175 | 175 |
|
176 | 176 |
static const Word mul = RandomTraits<Word>::mul; |
177 | 177 |
|
178 | 178 |
current = state; |
179 | 179 |
|
180 | 180 |
Word *curr = state + length - 1; |
181 | 181 |
curr[0] = seed; --curr; |
182 | 182 |
for (int i = 1; i < length; ++i) { |
183 | 183 |
curr[0] = (mul * ( curr[1] ^ (curr[1] >> (bits - 2)) ) + i); |
184 | 184 |
--curr; |
185 | 185 |
} |
186 | 186 |
} |
187 | 187 |
|
188 | 188 |
template <typename Iterator> |
189 | 189 |
void initState(Iterator begin, Iterator end) { |
190 | 190 |
|
191 | 191 |
static const Word init = RandomTraits<Word>::arrayInit; |
192 | 192 |
static const Word mul1 = RandomTraits<Word>::arrayMul1; |
193 | 193 |
static const Word mul2 = RandomTraits<Word>::arrayMul2; |
194 | 194 |
|
195 | 195 |
|
196 | 196 |
Word *curr = state + length - 1; --curr; |
197 | 197 |
Iterator it = begin; int cnt = 0; |
198 | 198 |
int num; |
199 | 199 |
|
200 | 200 |
initState(init); |
201 | 201 |
|
202 | 202 |
num = length > end - begin ? length : end - begin; |
203 | 203 |
while (num--) { |
204 | 204 |
curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1)) |
205 | 205 |
+ *it + cnt; |
206 | 206 |
++it; ++cnt; |
207 | 207 |
if (it == end) { |
208 | 208 |
it = begin; cnt = 0; |
209 | 209 |
} |
210 | 210 |
if (curr == state) { |
211 | 211 |
curr = state + length - 1; curr[0] = state[0]; |
212 | 212 |
} |
213 | 213 |
--curr; |
214 | 214 |
} |
215 | 215 |
|
216 | 216 |
num = length - 1; cnt = length - (curr - state) - 1; |
217 | 217 |
while (num--) { |
218 | 218 |
curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2)) |
219 | 219 |
- cnt; |
220 | 220 |
--curr; ++cnt; |
221 | 221 |
if (curr == state) { |
222 | 222 |
curr = state + length - 1; curr[0] = state[0]; --curr; |
223 | 223 |
cnt = 1; |
224 | 224 |
} |
225 | 225 |
} |
226 | 226 |
|
227 | 227 |
state[length - 1] = Word(1) << (bits - 1); |
228 | 228 |
} |
229 | 229 |
|
230 | 230 |
void copyState(const RandomCore& other) { |
231 | 231 |
std::copy(other.state, other.state + length, state); |
232 | 232 |
current = state + (other.current - other.state); |
233 | 233 |
} |
234 | 234 |
|
235 | 235 |
Word operator()() { |
236 | 236 |
if (current == state) fillState(); |
237 | 237 |
--current; |
238 | 238 |
Word rnd = *current; |
239 | 239 |
return RandomTraits<Word>::tempering(rnd); |
240 | 240 |
} |
241 | 241 |
|
242 | 242 |
private: |
243 | 243 |
|
244 | 244 |
|
245 | 245 |
void fillState() { |
246 | 246 |
static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask }; |
247 | 247 |
static const Word loMask = RandomTraits<Word>::loMask; |
248 | 248 |
static const Word hiMask = RandomTraits<Word>::hiMask; |
249 | 249 |
|
250 | 250 |
current = state + length; |
251 | 251 |
|
252 | 252 |
register Word *curr = state + length - 1; |
253 | 253 |
register long num; |
254 | 254 |
|
255 | 255 |
num = length - shift; |
256 | 256 |
while (num--) { |
257 | 257 |
curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^ |
258 | 258 |
curr[- shift] ^ mask[curr[-1] & 1ul]; |
259 | 259 |
--curr; |
260 | 260 |
} |
261 | 261 |
num = shift - 1; |
262 | 262 |
while (num--) { |
263 | 263 |
curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^ |
264 | 264 |
curr[length - shift] ^ mask[curr[-1] & 1ul]; |
265 | 265 |
--curr; |
266 | 266 |
} |
267 | 267 |
state[0] = (((state[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^ |
268 | 268 |
curr[length - shift] ^ mask[curr[length - 1] & 1ul]; |
269 | 269 |
|
270 | 270 |
} |
271 | 271 |
|
272 | 272 |
|
273 | 273 |
Word *current; |
274 | 274 |
Word state[length]; |
275 | 275 |
|
276 | 276 |
}; |
277 | 277 |
|
278 | 278 |
|
279 | 279 |
template <typename Result, |
280 | 280 |
int shift = (std::numeric_limits<Result>::digits + 1) / 2> |
281 | 281 |
struct Masker { |
282 | 282 |
static Result mask(const Result& result) { |
283 | 283 |
return Masker<Result, (shift + 1) / 2>:: |
284 | 284 |
mask(static_cast<Result>(result | (result >> shift))); |
285 | 285 |
} |
286 | 286 |
}; |
287 | 287 |
|
288 | 288 |
template <typename Result> |
289 | 289 |
struct Masker<Result, 1> { |
290 | 290 |
static Result mask(const Result& result) { |
291 | 291 |
return static_cast<Result>(result | (result >> 1)); |
292 | 292 |
} |
293 | 293 |
}; |
294 | 294 |
|
295 | 295 |
template <typename Result, typename Word, |
296 | 296 |
int rest = std::numeric_limits<Result>::digits, int shift = 0, |
297 | 297 |
bool last = rest <= std::numeric_limits<Word>::digits> |
298 | 298 |
struct IntConversion { |
299 | 299 |
static const int bits = std::numeric_limits<Word>::digits; |
300 | 300 |
|
301 | 301 |
static Result convert(RandomCore<Word>& rnd) { |
302 | 302 |
return static_cast<Result>(rnd() >> (bits - rest)) << shift; |
303 | 303 |
} |
304 | 304 |
|
305 | 305 |
}; |
306 | 306 |
|
307 | 307 |
template <typename Result, typename Word, int rest, int shift> |
308 | 308 |
struct IntConversion<Result, Word, rest, shift, false> { |
309 | 309 |
static const int bits = std::numeric_limits<Word>::digits; |
310 | 310 |
|
311 | 311 |
static Result convert(RandomCore<Word>& rnd) { |
312 | 312 |
return (static_cast<Result>(rnd()) << shift) | |
313 | 313 |
IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd); |
314 | 314 |
} |
315 | 315 |
}; |
316 | 316 |
|
317 | 317 |
|
318 | 318 |
template <typename Result, typename Word, |
319 | 319 |
bool one_word = (std::numeric_limits<Word>::digits < |
320 | 320 |
std::numeric_limits<Result>::digits) > |
321 | 321 |
struct Mapping { |
322 | 322 |
static Result map(RandomCore<Word>& rnd, const Result& bound) { |
323 | 323 |
Word max = Word(bound - 1); |
324 | 324 |
Result mask = Masker<Result>::mask(bound - 1); |
325 | 325 |
Result num; |
326 | 326 |
do { |
327 | 327 |
num = IntConversion<Result, Word>::convert(rnd) & mask; |
328 | 328 |
} while (num > max); |
329 | 329 |
return num; |
330 | 330 |
} |
331 | 331 |
}; |
332 | 332 |
|
333 | 333 |
template <typename Result, typename Word> |
334 | 334 |
struct Mapping<Result, Word, false> { |
335 | 335 |
static Result map(RandomCore<Word>& rnd, const Result& bound) { |
336 | 336 |
Word max = Word(bound - 1); |
337 | 337 |
Word mask = Masker<Word, (std::numeric_limits<Result>::digits + 1) / 2> |
338 | 338 |
::mask(max); |
339 | 339 |
Word num; |
340 | 340 |
do { |
341 | 341 |
num = rnd() & mask; |
342 | 342 |
} while (num > max); |
343 | 343 |
return num; |
344 | 344 |
} |
345 | 345 |
}; |
346 | 346 |
|
347 | 347 |
template <typename Result, int exp, bool pos = (exp >= 0)> |
348 | 348 |
struct ShiftMultiplier { |
349 | 349 |
static const Result multiplier() { |
350 | 350 |
Result res = ShiftMultiplier<Result, exp / 2>::multiplier(); |
351 | 351 |
res *= res; |
352 | 352 |
if ((exp & 1) == 1) res *= static_cast<Result>(2.0); |
353 | 353 |
return res; |
354 | 354 |
} |
355 | 355 |
}; |
356 | 356 |
|
357 | 357 |
template <typename Result, int exp> |
358 | 358 |
struct ShiftMultiplier<Result, exp, false> { |
359 | 359 |
static const Result multiplier() { |
360 | 360 |
Result res = ShiftMultiplier<Result, exp / 2>::multiplier(); |
361 | 361 |
res *= res; |
362 | 362 |
if ((exp & 1) == 1) res *= static_cast<Result>(0.5); |
363 | 363 |
return res; |
364 | 364 |
} |
365 | 365 |
}; |
366 | 366 |
|
367 | 367 |
template <typename Result> |
368 | 368 |
struct ShiftMultiplier<Result, 0, true> { |
369 | 369 |
static const Result multiplier() { |
370 | 370 |
return static_cast<Result>(1.0); |
371 | 371 |
} |
372 | 372 |
}; |
373 | 373 |
|
374 | 374 |
template <typename Result> |
375 | 375 |
struct ShiftMultiplier<Result, -20, true> { |
376 | 376 |
static const Result multiplier() { |
377 | 377 |
return static_cast<Result>(1.0/1048576.0); |
378 | 378 |
} |
379 | 379 |
}; |
380 | 380 |
|
381 | 381 |
template <typename Result> |
382 | 382 |
struct ShiftMultiplier<Result, -32, true> { |
383 | 383 |
static const Result multiplier() { |
384 | 384 |
return static_cast<Result>(1.0/424967296.0); |
385 | 385 |
} |
386 | 386 |
}; |
387 | 387 |
|
388 | 388 |
template <typename Result> |
389 | 389 |
struct ShiftMultiplier<Result, -53, true> { |
390 | 390 |
static const Result multiplier() { |
391 | 391 |
return static_cast<Result>(1.0/9007199254740992.0); |
392 | 392 |
} |
393 | 393 |
}; |
394 | 394 |
|
395 | 395 |
template <typename Result> |
396 | 396 |
struct ShiftMultiplier<Result, -64, true> { |
397 | 397 |
static const Result multiplier() { |
398 | 398 |
return static_cast<Result>(1.0/18446744073709551616.0); |
399 | 399 |
} |
400 | 400 |
}; |
401 | 401 |
|
402 | 402 |
template <typename Result, int exp> |
403 | 403 |
struct Shifting { |
404 | 404 |
static Result shift(const Result& result) { |
405 | 405 |
return result * ShiftMultiplier<Result, exp>::multiplier(); |
406 | 406 |
} |
407 | 407 |
}; |
408 | 408 |
|
409 | 409 |
template <typename Result, typename Word, |
410 | 410 |
int rest = std::numeric_limits<Result>::digits, int shift = 0, |
411 | 411 |
bool last = rest <= std::numeric_limits<Word>::digits> |
412 | 412 |
struct RealConversion{ |
413 | 413 |
static const int bits = std::numeric_limits<Word>::digits; |
414 | 414 |
|
415 | 415 |
static Result convert(RandomCore<Word>& rnd) { |
416 | 416 |
return Shifting<Result, - shift - rest>:: |
417 | 417 |
shift(static_cast<Result>(rnd() >> (bits - rest))); |
418 | 418 |
} |
419 | 419 |
}; |
420 | 420 |
|
421 | 421 |
template <typename Result, typename Word, int rest, int shift> |
422 | 422 |
struct RealConversion<Result, Word, rest, shift, false> { |
423 | 423 |
static const int bits = std::numeric_limits<Word>::digits; |
424 | 424 |
|
425 | 425 |
static Result convert(RandomCore<Word>& rnd) { |
426 | 426 |
return Shifting<Result, - shift - bits>:: |
427 | 427 |
shift(static_cast<Result>(rnd())) + |
428 | 428 |
RealConversion<Result, Word, rest-bits, shift + bits>:: |
429 | 429 |
convert(rnd); |
430 | 430 |
} |
431 | 431 |
}; |
432 | 432 |
|
433 | 433 |
template <typename Result, typename Word> |
434 | 434 |
struct Initializer { |
435 | 435 |
|
436 | 436 |
template <typename Iterator> |
437 | 437 |
static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) { |
438 | 438 |
std::vector<Word> ws; |
439 | 439 |
for (Iterator it = begin; it != end; ++it) { |
440 | 440 |
ws.push_back(Word(*it)); |
441 | 441 |
} |
442 | 442 |
rnd.initState(ws.begin(), ws.end()); |
443 | 443 |
} |
444 | 444 |
|
445 | 445 |
static void init(RandomCore<Word>& rnd, Result seed) { |
446 | 446 |
rnd.initState(seed); |
447 | 447 |
} |
448 | 448 |
}; |
449 | 449 |
|
450 | 450 |
template <typename Word> |
451 | 451 |
struct BoolConversion { |
452 | 452 |
static bool convert(RandomCore<Word>& rnd) { |
453 | 453 |
return (rnd() & 1) == 1; |
454 | 454 |
} |
455 | 455 |
}; |
456 | 456 |
|
457 | 457 |
template <typename Word> |
458 | 458 |
struct BoolProducer { |
459 | 459 |
Word buffer; |
460 | 460 |
int num; |
461 | 461 |
|
462 | 462 |
BoolProducer() : num(0) {} |
463 | 463 |
|
464 | 464 |
bool convert(RandomCore<Word>& rnd) { |
465 | 465 |
if (num == 0) { |
466 | 466 |
buffer = rnd(); |
467 | 467 |
num = RandomTraits<Word>::bits; |
468 | 468 |
} |
469 | 469 |
bool r = (buffer & 1); |
470 | 470 |
buffer >>= 1; |
471 | 471 |
--num; |
472 | 472 |
return r; |
473 | 473 |
} |
474 | 474 |
}; |
475 | 475 |
|
476 | 476 |
} |
477 | 477 |
|
478 | 478 |
/// \ingroup misc |
479 | 479 |
/// |
480 | 480 |
/// \brief Mersenne Twister random number generator |
481 | 481 |
/// |
482 | 482 |
/// The Mersenne Twister is a twisted generalized feedback |
483 | 483 |
/// shift-register generator of Matsumoto and Nishimura. The period |
484 | 484 |
/// of this generator is \f$ 2^{19937} - 1 \f$ and it is |
485 | 485 |
/// equi-distributed in 623 dimensions for 32-bit numbers. The time |
486 | 486 |
/// performance of this generator is comparable to the commonly used |
487 | 487 |
/// generators. |
488 | 488 |
/// |
489 | 489 |
/// This implementation is specialized for both 32-bit and 64-bit |
490 | 490 |
/// architectures. The generators differ sligthly in the |
491 | 491 |
/// initialization and generation phase so they produce two |
492 | 492 |
/// completly different sequences. |
493 | 493 |
/// |
494 | 494 |
/// The generator gives back random numbers of serveral types. To |
495 | 495 |
/// get a random number from a range of a floating point type you |
496 | 496 |
/// can use one form of the \c operator() or the \c real() member |
497 | 497 |
/// function. If you want to get random number from the {0, 1, ..., |
498 | 498 |
/// n-1} integer range use the \c operator[] or the \c integer() |
499 | 499 |
/// method. And to get random number from the whole range of an |
500 | 500 |
/// integer type you can use the argumentless \c integer() or \c |
501 | 501 |
/// uinteger() functions. After all you can get random bool with |
502 | 502 |
/// equal chance of true and false or given probability of true |
503 | 503 |
/// result with the \c boolean() member functions. |
504 | 504 |
/// |
505 | 505 |
///\code |
506 | 506 |
/// // The commented code is identical to the other |
507 | 507 |
/// double a = rnd(); // [0.0, 1.0) |
508 | 508 |
/// // double a = rnd.real(); // [0.0, 1.0) |
509 | 509 |
/// double b = rnd(100.0); // [0.0, 100.0) |
510 | 510 |
/// // double b = rnd.real(100.0); // [0.0, 100.0) |
511 | 511 |
/// double c = rnd(1.0, 2.0); // [1.0, 2.0) |
512 | 512 |
/// // double c = rnd.real(1.0, 2.0); // [1.0, 2.0) |
513 | 513 |
/// int d = rnd[100000]; // 0..99999 |
514 | 514 |
/// // int d = rnd.integer(100000); // 0..99999 |
515 | 515 |
/// int e = rnd[6] + 1; // 1..6 |
516 | 516 |
/// // int e = rnd.integer(1, 1 + 6); // 1..6 |
517 | 517 |
/// int b = rnd.uinteger<int>(); // 0 .. 2^31 - 1 |
518 | 518 |
/// int c = rnd.integer<int>(); // - 2^31 .. 2^31 - 1 |
519 | 519 |
/// bool g = rnd.boolean(); // P(g = true) = 0.5 |
520 | 520 |
/// bool h = rnd.boolean(0.8); // P(h = true) = 0.8 |
521 | 521 |
///\endcode |
522 | 522 |
/// |
523 | 523 |
/// LEMON provides a global instance of the random number |
524 | 524 |
/// generator which name is \ref lemon::rnd "rnd". Usually it is a |
525 | 525 |
/// good programming convenience to use this global generator to get |
526 | 526 |
/// random numbers. |
527 | 527 |
class Random { |
528 | 528 |
private: |
529 | 529 |
|
530 | 530 |
// Architecture word |
531 | 531 |
typedef unsigned long Word; |
532 | 532 |
|
533 | 533 |
_random_bits::RandomCore<Word> core; |
534 | 534 |
_random_bits::BoolProducer<Word> bool_producer; |
535 | 535 |
|
536 | 536 |
|
537 | 537 |
public: |
538 | 538 |
|
539 | 539 |
///\name Initialization |
540 | 540 |
/// |
541 | 541 |
/// @{ |
542 | 542 |
|
543 | 543 |
///\name Initialization |
544 | 544 |
/// |
545 | 545 |
/// @{ |
546 | 546 |
|
547 | 547 |
/// \brief Default constructor |
548 | 548 |
/// |
549 | 549 |
/// Constructor with constant seeding. |
550 | 550 |
Random() { core.initState(); } |
551 | 551 |
|
552 | 552 |
/// \brief Constructor with seed |
553 | 553 |
/// |
554 | 554 |
/// Constructor with seed. The current number type will be converted |
555 | 555 |
/// to the architecture word type. |
556 | 556 |
template <typename Number> |
557 | 557 |
Random(Number seed) { |
558 | 558 |
_random_bits::Initializer<Number, Word>::init(core, seed); |
559 | 559 |
} |
560 | 560 |
|
561 | 561 |
/// \brief Constructor with array seeding |
562 | 562 |
/// |
563 | 563 |
/// Constructor with array seeding. The given range should contain |
564 | 564 |
/// any number type and the numbers will be converted to the |
565 | 565 |
/// architecture word type. |
566 | 566 |
template <typename Iterator> |
567 | 567 |
Random(Iterator begin, Iterator end) { |
568 | 568 |
typedef typename std::iterator_traits<Iterator>::value_type Number; |
569 | 569 |
_random_bits::Initializer<Number, Word>::init(core, begin, end); |
570 | 570 |
} |
571 | 571 |
|
572 | 572 |
/// \brief Copy constructor |
573 | 573 |
/// |
574 | 574 |
/// Copy constructor. The generated sequence will be identical to |
575 | 575 |
/// the other sequence. It can be used to save the current state |
576 | 576 |
/// of the generator and later use it to generate the same |
577 | 577 |
/// sequence. |
578 | 578 |
Random(const Random& other) { |
579 | 579 |
core.copyState(other.core); |
580 | 580 |
} |
581 | 581 |
|
582 | 582 |
/// \brief Assign operator |
583 | 583 |
/// |
584 | 584 |
/// Assign operator. The generated sequence will be identical to |
585 | 585 |
/// the other sequence. It can be used to save the current state |
586 | 586 |
/// of the generator and later use it to generate the same |
587 | 587 |
/// sequence. |
588 | 588 |
Random& operator=(const Random& other) { |
589 | 589 |
if (&other != this) { |
590 | 590 |
core.copyState(other.core); |
591 | 591 |
} |
592 | 592 |
return *this; |
593 | 593 |
} |
594 | 594 |
|
595 | 595 |
/// \brief Seeding random sequence |
596 | 596 |
/// |
597 | 597 |
/// Seeding the random sequence. The current number type will be |
598 | 598 |
/// converted to the architecture word type. |
599 | 599 |
template <typename Number> |
600 | 600 |
void seed(Number seed) { |
601 | 601 |
_random_bits::Initializer<Number, Word>::init(core, seed); |
602 | 602 |
} |
603 | 603 |
|
604 | 604 |
/// \brief Seeding random sequence |
605 | 605 |
/// |
606 | 606 |
/// Seeding the random sequence. The given range should contain |
607 | 607 |
/// any number type and the numbers will be converted to the |
608 | 608 |
/// architecture word type. |
609 | 609 |
template <typename Iterator> |
610 | 610 |
void seed(Iterator begin, Iterator end) { |
611 | 611 |
typedef typename std::iterator_traits<Iterator>::value_type Number; |
612 | 612 |
_random_bits::Initializer<Number, Word>::init(core, begin, end); |
613 | 613 |
} |
614 | 614 |
|
615 | 615 |
/// \brief Seeding from file or from process id and time |
616 | 616 |
/// |
617 | 617 |
/// By default, this function calls the \c seedFromFile() member |
618 | 618 |
/// function with the <tt>/dev/urandom</tt> file. If it does not success, |
619 | 619 |
/// it uses the \c seedFromTime(). |
620 | 620 |
/// \return Currently always true. |
621 | 621 |
bool seed() { |
622 | 622 |
#ifndef WIN32 |
623 | 623 |
if (seedFromFile("/dev/urandom", 0)) return true; |
624 | 624 |
#endif |
625 | 625 |
if (seedFromTime()) return true; |
626 | 626 |
return false; |
627 | 627 |
} |
628 | 628 |
|
629 | 629 |
/// \brief Seeding from file |
630 | 630 |
/// |
631 | 631 |
/// Seeding the random sequence from file. The linux kernel has two |
632 | 632 |
/// devices, <tt>/dev/random</tt> and <tt>/dev/urandom</tt> which |
633 | 633 |
/// could give good seed values for pseudo random generators (The |
634 | 634 |
/// difference between two devices is that the <tt>random</tt> may |
635 | 635 |
/// block the reading operation while the kernel can give good |
636 | 636 |
/// source of randomness, while the <tt>urandom</tt> does not |
637 | 637 |
/// block the input, but it could give back bytes with worse |
638 | 638 |
/// entropy). |
639 | 639 |
/// \param file The source file |
640 | 640 |
/// \param offset The offset, from the file read. |
641 | 641 |
/// \return True when the seeding successes. |
642 | 642 |
#ifndef WIN32 |
643 | 643 |
bool seedFromFile(const std::string& file = "/dev/urandom", int offset = 0) |
644 | 644 |
#else |
645 | 645 |
bool seedFromFile(const std::string& file = "", int offset = 0) |
646 | 646 |
#endif |
647 | 647 |
{ |
648 | 648 |
std::ifstream rs(file.c_str()); |
649 | 649 |
const int size = 4; |
650 | 650 |
Word buf[size]; |
651 | 651 |
if (offset != 0 && !rs.seekg(offset)) return false; |
652 | 652 |
if (!rs.read(reinterpret_cast<char*>(buf), sizeof(buf))) return false; |
653 | 653 |
seed(buf, buf + size); |
654 | 654 |
return true; |
655 | 655 |
} |
656 | 656 |
|
657 | 657 |
/// \brief Seding from process id and time |
658 | 658 |
/// |
659 | 659 |
/// Seding from process id and time. This function uses the |
660 | 660 |
/// current process id and the current time for initialize the |
661 | 661 |
/// random sequence. |
662 | 662 |
/// \return Currently always true. |
663 | 663 |
bool seedFromTime() { |
664 | 664 |
#ifndef WIN32 |
665 | 665 |
timeval tv; |
666 | 666 |
gettimeofday(&tv, 0); |
667 | 667 |
seed(getpid() + tv.tv_sec + tv.tv_usec); |
668 | 668 |
#else |
669 | 669 |
FILETIME time; |
670 | 670 |
GetSystemTimeAsFileTime(&time); |
671 | 671 |
seed(GetCurrentProcessId() + time.dwHighDateTime + time.dwLowDateTime); |
672 | 672 |
#endif |
673 | 673 |
return true; |
674 | 674 |
} |
675 | 675 |
|
676 | 676 |
/// @} |
677 | 677 |
|
678 | 678 |
///\name Uniform distributions |
679 | 679 |
/// |
680 | 680 |
/// @{ |
681 | 681 |
|
682 | 682 |
/// \brief Returns a random real number from the range [0, 1) |
683 | 683 |
/// |
684 | 684 |
/// It returns a random real number from the range [0, 1). The |
685 | 685 |
/// default Number type is \c double. |
686 | 686 |
template <typename Number> |
687 | 687 |
Number real() { |
688 | 688 |
return _random_bits::RealConversion<Number, Word>::convert(core); |
689 | 689 |
} |
690 | 690 |
|
691 | 691 |
double real() { |
692 | 692 |
return real<double>(); |
693 | 693 |
} |
694 | 694 |
|
695 | 695 |
/// \brief Returns a random real number the range [0, b) |
696 | 696 |
/// |
697 | 697 |
/// It returns a random real number from the range [0, b). |
698 | 698 |
template <typename Number> |
699 | 699 |
Number real(Number b) { |
700 | 700 |
return real<Number>() * b; |
701 | 701 |
} |
702 | 702 |
|
703 | 703 |
/// \brief Returns a random real number from the range [a, b) |
704 | 704 |
/// |
705 | 705 |
/// It returns a random real number from the range [a, b). |
706 | 706 |
template <typename Number> |
707 | 707 |
Number real(Number a, Number b) { |
708 | 708 |
return real<Number>() * (b - a) + a; |
709 | 709 |
} |
710 | 710 |
|
711 | 711 |
/// @} |
712 | 712 |
|
713 | 713 |
///\name Uniform distributions |
714 | 714 |
/// |
715 | 715 |
/// @{ |
716 | 716 |
|
717 | 717 |
/// \brief Returns a random real number from the range [0, 1) |
718 | 718 |
/// |
719 | 719 |
/// It returns a random double from the range [0, 1). |
720 | 720 |
double operator()() { |
721 | 721 |
return real<double>(); |
722 | 722 |
} |
723 | 723 |
|
724 | 724 |
/// \brief Returns a random real number from the range [0, b) |
725 | 725 |
/// |
726 | 726 |
/// It returns a random real number from the range [0, b). |
727 | 727 |
template <typename Number> |
728 | 728 |
Number operator()(Number b) { |
729 | 729 |
return real<Number>() * b; |
730 | 730 |
} |
731 | 731 |
|
732 | 732 |
/// \brief Returns a random real number from the range [a, b) |
733 | 733 |
/// |
734 | 734 |
/// It returns a random real number from the range [a, b). |
735 | 735 |
template <typename Number> |
736 | 736 |
Number operator()(Number a, Number b) { |
737 | 737 |
return real<Number>() * (b - a) + a; |
738 | 738 |
} |
739 | 739 |
|
740 | 740 |
/// \brief Returns a random integer from a range |
741 | 741 |
/// |
742 | 742 |
/// It returns a random integer from the range {0, 1, ..., b - 1}. |
743 | 743 |
template <typename Number> |
744 | 744 |
Number integer(Number b) { |
745 | 745 |
return _random_bits::Mapping<Number, Word>::map(core, b); |
746 | 746 |
} |
747 | 747 |
|
748 | 748 |
/// \brief Returns a random integer from a range |
749 | 749 |
/// |
750 | 750 |
/// It returns a random integer from the range {a, a + 1, ..., b - 1}. |
751 | 751 |
template <typename Number> |
752 | 752 |
Number integer(Number a, Number b) { |
753 | 753 |
return _random_bits::Mapping<Number, Word>::map(core, b - a) + a; |
754 | 754 |
} |
755 | 755 |
|
756 | 756 |
/// \brief Returns a random integer from a range |
757 | 757 |
/// |
758 | 758 |
/// It returns a random integer from the range {0, 1, ..., b - 1}. |
759 | 759 |
template <typename Number> |
760 | 760 |
Number operator[](Number b) { |
761 | 761 |
return _random_bits::Mapping<Number, Word>::map(core, b); |
762 | 762 |
} |
763 | 763 |
|
764 | 764 |
/// \brief Returns a random non-negative integer |
765 | 765 |
/// |
766 | 766 |
/// It returns a random non-negative integer uniformly from the |
767 | 767 |
/// whole range of the current \c Number type. The default result |
768 | 768 |
/// type of this function is <tt>unsigned int</tt>. |
769 | 769 |
template <typename Number> |
770 | 770 |
Number uinteger() { |
771 | 771 |
return _random_bits::IntConversion<Number, Word>::convert(core); |
772 | 772 |
} |
773 | 773 |
|
774 | 774 |
/// @} |
775 | 775 |
|
776 | 776 |
unsigned int uinteger() { |
777 | 777 |
return uinteger<unsigned int>(); |
778 | 778 |
} |
779 | 779 |
|
780 | 780 |
/// \brief Returns a random integer |
781 | 781 |
/// |
782 | 782 |
/// It returns a random integer uniformly from the whole range of |
783 | 783 |
/// the current \c Number type. The default result type of this |
784 | 784 |
/// function is \c int. |
785 | 785 |
template <typename Number> |
786 | 786 |
Number integer() { |
787 | 787 |
static const int nb = std::numeric_limits<Number>::digits + |
788 | 788 |
(std::numeric_limits<Number>::is_signed ? 1 : 0); |
789 | 789 |
return _random_bits::IntConversion<Number, Word, nb>::convert(core); |
790 | 790 |
} |
791 | 791 |
|
792 | 792 |
int integer() { |
793 | 793 |
return integer<int>(); |
794 | 794 |
} |
795 | 795 |
|
796 | 796 |
/// \brief Returns a random bool |
797 | 797 |
/// |
798 | 798 |
/// It returns a random bool. The generator holds a buffer for |
799 | 799 |
/// random bits. Every time when it become empty the generator makes |
800 | 800 |
/// a new random word and fill the buffer up. |
801 | 801 |
bool boolean() { |
802 | 802 |
return bool_producer.convert(core); |
803 | 803 |
} |
804 | 804 |
|
805 | 805 |
/// @} |
806 | 806 |
|
807 | 807 |
///\name Non-uniform distributions |
808 | 808 |
/// |
809 | 809 |
|
810 | 810 |
///@{ |
811 | 811 |
|
812 | 812 |
/// \brief Returns a random bool |
813 | 813 |
/// |
814 | 814 |
/// It returns a random bool with given probability of true result. |
815 | 815 |
bool boolean(double p) { |
816 | 816 |
return operator()() < p; |
817 | 817 |
} |
818 | 818 |
|
819 | 819 |
/// Standard Gauss distribution |
820 | 820 |
|
821 | 821 |
/// Standard Gauss distribution. |
822 | 822 |
/// \note The Cartesian form of the Box-Muller |
823 | 823 |
/// transformation is used to generate a random normal distribution. |
824 |
/// \todo Consider using the "ziggurat" method instead. |
|
825 | 824 |
double gauss() |
826 | 825 |
{ |
827 | 826 |
double V1,V2,S; |
828 | 827 |
do { |
829 | 828 |
V1=2*real<double>()-1; |
830 | 829 |
V2=2*real<double>()-1; |
831 | 830 |
S=V1*V1+V2*V2; |
832 | 831 |
} while(S>=1); |
833 | 832 |
return std::sqrt(-2*std::log(S)/S)*V1; |
834 | 833 |
} |
835 | 834 |
/// Gauss distribution with given mean and standard deviation |
836 | 835 |
|
837 | 836 |
/// Gauss distribution with given mean and standard deviation. |
838 | 837 |
/// \sa gauss() |
839 | 838 |
double gauss(double mean,double std_dev) |
840 | 839 |
{ |
841 | 840 |
return gauss()*std_dev+mean; |
842 | 841 |
} |
843 | 842 |
|
844 | 843 |
/// Exponential distribution with given mean |
845 | 844 |
|
846 | 845 |
/// This function generates an exponential distribution random number |
847 | 846 |
/// with mean <tt>1/lambda</tt>. |
848 | 847 |
/// |
849 | 848 |
double exponential(double lambda=1.0) |
850 | 849 |
{ |
851 | 850 |
return -std::log(1.0-real<double>())/lambda; |
852 | 851 |
} |
853 | 852 |
|
854 | 853 |
/// Gamma distribution with given integer shape |
855 | 854 |
|
856 | 855 |
/// This function generates a gamma distribution random number. |
857 | 856 |
/// |
858 | 857 |
///\param k shape parameter (<tt>k>0</tt> integer) |
859 | 858 |
double gamma(int k) |
860 | 859 |
{ |
861 | 860 |
double s = 0; |
862 | 861 |
for(int i=0;i<k;i++) s-=std::log(1.0-real<double>()); |
863 | 862 |
return s; |
864 | 863 |
} |
865 | 864 |
|
866 | 865 |
/// Gamma distribution with given shape and scale parameter |
867 | 866 |
|
868 | 867 |
/// This function generates a gamma distribution random number. |
869 | 868 |
/// |
870 | 869 |
///\param k shape parameter (<tt>k>0</tt>) |
871 | 870 |
///\param theta scale parameter |
872 | 871 |
/// |
873 | 872 |
double gamma(double k,double theta=1.0) |
874 | 873 |
{ |
875 | 874 |
double xi,nu; |
876 | 875 |
const double delta = k-std::floor(k); |
877 | 876 |
const double v0=E/(E-delta); |
878 | 877 |
do { |
879 | 878 |
double V0=1.0-real<double>(); |
880 | 879 |
double V1=1.0-real<double>(); |
881 | 880 |
double V2=1.0-real<double>(); |
882 | 881 |
if(V2<=v0) |
883 | 882 |
{ |
884 | 883 |
xi=std::pow(V1,1.0/delta); |
885 | 884 |
nu=V0*std::pow(xi,delta-1.0); |
886 | 885 |
} |
887 | 886 |
else |
888 | 887 |
{ |
889 | 888 |
xi=1.0-std::log(V1); |
890 | 889 |
nu=V0*std::exp(-xi); |
891 | 890 |
} |
892 | 891 |
} while(nu>std::pow(xi,delta-1.0)*std::exp(-xi)); |
893 | 892 |
return theta*(xi+gamma(int(std::floor(k)))); |
894 | 893 |
} |
895 | 894 |
|
896 | 895 |
/// Weibull distribution |
897 | 896 |
|
898 | 897 |
/// This function generates a Weibull distribution random number. |
899 | 898 |
/// |
900 | 899 |
///\param k shape parameter (<tt>k>0</tt>) |
901 | 900 |
///\param lambda scale parameter (<tt>lambda>0</tt>) |
902 | 901 |
/// |
903 | 902 |
double weibull(double k,double lambda) |
904 | 903 |
{ |
905 | 904 |
return lambda*pow(-std::log(1.0-real<double>()),1.0/k); |
906 | 905 |
} |
907 | 906 |
|
908 | 907 |
/// Pareto distribution |
909 | 908 |
|
910 | 909 |
/// This function generates a Pareto distribution random number. |
911 | 910 |
/// |
912 | 911 |
///\param k shape parameter (<tt>k>0</tt>) |
913 | 912 |
///\param x_min location parameter (<tt>x_min>0</tt>) |
914 | 913 |
/// |
915 | 914 |
double pareto(double k,double x_min) |
916 | 915 |
{ |
917 | 916 |
return exponential(gamma(k,1.0/x_min))+x_min; |
918 | 917 |
} |
919 | 918 |
|
920 | 919 |
/// Poisson distribution |
921 | 920 |
|
922 | 921 |
/// This function generates a Poisson distribution random number with |
923 | 922 |
/// parameter \c lambda. |
924 | 923 |
/// |
925 | 924 |
/// The probability mass function of this distribusion is |
926 | 925 |
/// \f[ \frac{e^{-\lambda}\lambda^k}{k!} \f] |
927 | 926 |
/// \note The algorithm is taken from the book of Donald E. Knuth titled |
928 | 927 |
/// ''Seminumerical Algorithms'' (1969). Its running time is linear in the |
929 | 928 |
/// return value. |
930 | 929 |
|
931 | 930 |
int poisson(double lambda) |
932 | 931 |
{ |
933 | 932 |
const double l = std::exp(-lambda); |
934 | 933 |
int k=0; |
935 | 934 |
double p = 1.0; |
936 | 935 |
do { |
937 | 936 |
k++; |
938 | 937 |
p*=real<double>(); |
939 | 938 |
} while (p>=l); |
940 | 939 |
return k-1; |
941 | 940 |
} |
942 | 941 |
|
943 | 942 |
///@} |
944 | 943 |
|
945 | 944 |
///\name Two dimensional distributions |
946 | 945 |
/// |
947 | 946 |
|
948 | 947 |
///@{ |
949 | 948 |
|
950 | 949 |
/// Uniform distribution on the full unit circle |
951 | 950 |
|
952 | 951 |
/// Uniform distribution on the full unit circle. |
953 | 952 |
/// |
954 | 953 |
dim2::Point<double> disc() |
955 | 954 |
{ |
956 | 955 |
double V1,V2; |
957 | 956 |
do { |
958 | 957 |
V1=2*real<double>()-1; |
959 | 958 |
V2=2*real<double>()-1; |
960 | 959 |
|
961 | 960 |
} while(V1*V1+V2*V2>=1); |
962 | 961 |
return dim2::Point<double>(V1,V2); |
963 | 962 |
} |
964 | 963 |
/// A kind of two dimensional Gauss distribution |
965 | 964 |
|
966 | 965 |
/// This function provides a turning symmetric two-dimensional distribution. |
967 | 966 |
/// Both coordinates are of standard normal distribution, but they are not |
968 | 967 |
/// independent. |
969 | 968 |
/// |
970 | 969 |
/// \note The coordinates are the two random variables provided by |
971 | 970 |
/// the Box-Muller method. |
972 | 971 |
dim2::Point<double> gauss2() |
973 | 972 |
{ |
974 | 973 |
double V1,V2,S; |
975 | 974 |
do { |
976 | 975 |
V1=2*real<double>()-1; |
977 | 976 |
V2=2*real<double>()-1; |
978 | 977 |
S=V1*V1+V2*V2; |
979 | 978 |
} while(S>=1); |
980 | 979 |
double W=std::sqrt(-2*std::log(S)/S); |
981 | 980 |
return dim2::Point<double>(W*V1,W*V2); |
982 | 981 |
} |
983 | 982 |
/// A kind of two dimensional exponential distribution |
984 | 983 |
|
985 | 984 |
/// This function provides a turning symmetric two-dimensional distribution. |
986 | 985 |
/// The x-coordinate is of conditionally exponential distribution |
987 | 986 |
/// with the condition that x is positive and y=0. If x is negative and |
988 | 987 |
/// y=0 then, -x is of exponential distribution. The same is true for the |
989 | 988 |
/// y-coordinate. |
990 | 989 |
dim2::Point<double> exponential2() |
991 | 990 |
{ |
992 | 991 |
double V1,V2,S; |
993 | 992 |
do { |
994 | 993 |
V1=2*real<double>()-1; |
995 | 994 |
V2=2*real<double>()-1; |
996 | 995 |
S=V1*V1+V2*V2; |
997 | 996 |
} while(S>=1); |
998 | 997 |
double W=-std::log(S)/S; |
999 | 998 |
return dim2::Point<double>(W*V1,W*V2); |
1000 | 999 |
} |
1001 | 1000 |
|
1002 | 1001 |
///@} |
1003 | 1002 |
}; |
1004 | 1003 |
|
1005 | 1004 |
|
1006 | 1005 |
extern Random rnd; |
1007 | 1006 |
|
1008 | 1007 |
} |
1009 | 1008 |
|
1010 | 1009 |
#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-2008 |
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_SMART_GRAPH_H |
20 | 20 |
#define LEMON_SMART_GRAPH_H |
21 | 21 |
|
22 | 22 |
///\ingroup graphs |
23 | 23 |
///\file |
24 | 24 |
///\brief SmartDigraph and SmartGraph classes. |
25 | 25 |
|
26 | 26 |
#include <vector> |
27 | 27 |
|
28 | 28 |
#include <lemon/core.h> |
29 | 29 |
#include <lemon/error.h> |
30 | 30 |
#include <lemon/bits/graph_extender.h> |
31 | 31 |
|
32 | 32 |
namespace lemon { |
33 | 33 |
|
34 | 34 |
class SmartDigraph; |
35 | 35 |
///Base of SmartDigraph |
36 | 36 |
|
37 | 37 |
///Base of SmartDigraph |
38 | 38 |
/// |
39 | 39 |
class SmartDigraphBase { |
40 | 40 |
protected: |
41 | 41 |
|
42 | 42 |
struct NodeT |
43 | 43 |
{ |
44 | 44 |
int first_in, first_out; |
45 | 45 |
NodeT() {} |
46 | 46 |
}; |
47 | 47 |
struct ArcT |
48 | 48 |
{ |
49 | 49 |
int target, source, next_in, next_out; |
50 | 50 |
ArcT() {} |
51 | 51 |
}; |
52 | 52 |
|
53 | 53 |
std::vector<NodeT> nodes; |
54 | 54 |
std::vector<ArcT> arcs; |
55 | 55 |
|
56 | 56 |
public: |
57 | 57 |
|
58 | 58 |
typedef SmartDigraphBase Graph; |
59 | 59 |
|
60 | 60 |
class Node; |
61 | 61 |
class Arc; |
62 | 62 |
|
63 | 63 |
public: |
64 | 64 |
|
65 | 65 |
SmartDigraphBase() : nodes(), arcs() { } |
66 | 66 |
SmartDigraphBase(const SmartDigraphBase &_g) |
67 | 67 |
: nodes(_g.nodes), arcs(_g.arcs) { } |
68 | 68 |
|
69 | 69 |
typedef True NodeNumTag; |
70 | 70 |
typedef True EdgeNumTag; |
71 | 71 |
|
72 | 72 |
int nodeNum() const { return nodes.size(); } |
73 | 73 |
int arcNum() const { return arcs.size(); } |
74 | 74 |
|
75 | 75 |
int maxNodeId() const { return nodes.size()-1; } |
76 | 76 |
int maxArcId() const { return arcs.size()-1; } |
77 | 77 |
|
78 | 78 |
Node addNode() { |
79 | 79 |
int n = nodes.size(); |
80 | 80 |
nodes.push_back(NodeT()); |
81 | 81 |
nodes[n].first_in = -1; |
82 | 82 |
nodes[n].first_out = -1; |
83 | 83 |
return Node(n); |
84 | 84 |
} |
85 | 85 |
|
86 | 86 |
Arc addArc(Node u, Node v) { |
87 | 87 |
int n = arcs.size(); |
88 | 88 |
arcs.push_back(ArcT()); |
89 | 89 |
arcs[n].source = u._id; |
90 | 90 |
arcs[n].target = v._id; |
91 | 91 |
arcs[n].next_out = nodes[u._id].first_out; |
92 | 92 |
arcs[n].next_in = nodes[v._id].first_in; |
93 | 93 |
nodes[u._id].first_out = nodes[v._id].first_in = n; |
94 | 94 |
|
95 | 95 |
return Arc(n); |
96 | 96 |
} |
97 | 97 |
|
98 | 98 |
void clear() { |
99 | 99 |
arcs.clear(); |
100 | 100 |
nodes.clear(); |
101 | 101 |
} |
102 | 102 |
|
103 | 103 |
Node source(Arc a) const { return Node(arcs[a._id].source); } |
104 | 104 |
Node target(Arc a) const { return Node(arcs[a._id].target); } |
105 | 105 |
|
106 | 106 |
static int id(Node v) { return v._id; } |
107 | 107 |
static int id(Arc a) { return a._id; } |
108 | 108 |
|
109 | 109 |
static Node nodeFromId(int id) { return Node(id);} |
110 | 110 |
static Arc arcFromId(int id) { return Arc(id);} |
111 | 111 |
|
112 | 112 |
bool valid(Node n) const { |
113 | 113 |
return n._id >= 0 && n._id < static_cast<int>(nodes.size()); |
114 | 114 |
} |
115 | 115 |
bool valid(Arc a) const { |
116 | 116 |
return a._id >= 0 && a._id < static_cast<int>(arcs.size()); |
117 | 117 |
} |
118 | 118 |
|
119 | 119 |
class Node { |
120 | 120 |
friend class SmartDigraphBase; |
121 | 121 |
friend class SmartDigraph; |
122 | 122 |
|
123 | 123 |
protected: |
124 | 124 |
int _id; |
125 | 125 |
explicit Node(int id) : _id(id) {} |
126 | 126 |
public: |
127 | 127 |
Node() {} |
128 | 128 |
Node (Invalid) : _id(-1) {} |
129 | 129 |
bool operator==(const Node i) const {return _id == i._id;} |
130 | 130 |
bool operator!=(const Node i) const {return _id != i._id;} |
131 | 131 |
bool operator<(const Node i) const {return _id < i._id;} |
132 | 132 |
}; |
133 | 133 |
|
134 | 134 |
|
135 | 135 |
class Arc { |
136 | 136 |
friend class SmartDigraphBase; |
137 | 137 |
friend class SmartDigraph; |
138 | 138 |
|
139 | 139 |
protected: |
140 | 140 |
int _id; |
141 | 141 |
explicit Arc(int id) : _id(id) {} |
142 | 142 |
public: |
143 | 143 |
Arc() { } |
144 | 144 |
Arc (Invalid) : _id(-1) {} |
145 | 145 |
bool operator==(const Arc i) const {return _id == i._id;} |
146 | 146 |
bool operator!=(const Arc i) const {return _id != i._id;} |
147 | 147 |
bool operator<(const Arc i) const {return _id < i._id;} |
148 | 148 |
}; |
149 | 149 |
|
150 | 150 |
void first(Node& node) const { |
151 | 151 |
node._id = nodes.size() - 1; |
152 | 152 |
} |
153 | 153 |
|
154 | 154 |
static void next(Node& node) { |
155 | 155 |
--node._id; |
156 | 156 |
} |
157 | 157 |
|
158 | 158 |
void first(Arc& arc) const { |
159 | 159 |
arc._id = arcs.size() - 1; |
160 | 160 |
} |
161 | 161 |
|
162 | 162 |
static void next(Arc& arc) { |
163 | 163 |
--arc._id; |
164 | 164 |
} |
165 | 165 |
|
166 | 166 |
void firstOut(Arc& arc, const Node& node) const { |
167 | 167 |
arc._id = nodes[node._id].first_out; |
168 | 168 |
} |
169 | 169 |
|
170 | 170 |
void nextOut(Arc& arc) const { |
171 | 171 |
arc._id = arcs[arc._id].next_out; |
172 | 172 |
} |
173 | 173 |
|
174 | 174 |
void firstIn(Arc& arc, const Node& node) const { |
175 | 175 |
arc._id = nodes[node._id].first_in; |
176 | 176 |
} |
177 | 177 |
|
178 | 178 |
void nextIn(Arc& arc) const { |
179 | 179 |
arc._id = arcs[arc._id].next_in; |
180 | 180 |
} |
181 | 181 |
|
182 | 182 |
}; |
183 | 183 |
|
184 | 184 |
typedef DigraphExtender<SmartDigraphBase> ExtendedSmartDigraphBase; |
185 | 185 |
|
186 | 186 |
///\ingroup graphs |
187 | 187 |
/// |
188 | 188 |
///\brief A smart directed graph class. |
189 | 189 |
/// |
190 | 190 |
///This is a simple and fast digraph implementation. |
191 | 191 |
///It is also quite memory efficient, but at the price |
192 | 192 |
///that <b> it does support only limited (only stack-like) |
193 | 193 |
///node and arc deletions</b>. |
194 | 194 |
///It conforms to the \ref concepts::Digraph "Digraph concept" with |
195 | 195 |
///an important extra feature that its maps are real \ref |
196 | 196 |
///concepts::ReferenceMap "reference map"s. |
197 | 197 |
/// |
198 | 198 |
///\sa concepts::Digraph. |
199 | 199 |
class SmartDigraph : public ExtendedSmartDigraphBase { |
200 | 200 |
public: |
201 | 201 |
|
202 | 202 |
typedef ExtendedSmartDigraphBase Parent; |
203 | 203 |
|
204 | 204 |
private: |
205 | 205 |
|
206 | 206 |
///SmartDigraph is \e not copy constructible. Use DigraphCopy() instead. |
207 | 207 |
|
208 | 208 |
///SmartDigraph is \e not copy constructible. Use DigraphCopy() instead. |
209 | 209 |
/// |
210 | 210 |
SmartDigraph(const SmartDigraph &) : ExtendedSmartDigraphBase() {}; |
211 | 211 |
///\brief Assignment of SmartDigraph to another one is \e not allowed. |
212 | 212 |
///Use DigraphCopy() instead. |
213 | 213 |
|
214 | 214 |
///Assignment of SmartDigraph to another one is \e not allowed. |
215 | 215 |
///Use DigraphCopy() instead. |
216 | 216 |
void operator=(const SmartDigraph &) {} |
217 | 217 |
|
218 | 218 |
public: |
219 | 219 |
|
220 | 220 |
/// Constructor |
221 | 221 |
|
222 | 222 |
/// Constructor. |
223 | 223 |
/// |
224 | 224 |
SmartDigraph() {}; |
225 | 225 |
|
226 | 226 |
///Add a new node to the digraph. |
227 | 227 |
|
228 | 228 |
/// \return the new node. |
229 | 229 |
/// |
230 | 230 |
Node addNode() { return Parent::addNode(); } |
231 | 231 |
|
232 | 232 |
///Add a new arc to the digraph. |
233 | 233 |
|
234 | 234 |
///Add a new arc to the digraph with source node \c s |
235 | 235 |
///and target node \c t. |
236 | 236 |
///\return the new arc. |
237 | 237 |
Arc addArc(const Node& s, const Node& t) { |
238 | 238 |
return Parent::addArc(s, t); |
239 | 239 |
} |
240 | 240 |
|
241 | 241 |
/// \brief Using this it is possible to avoid the superfluous memory |
242 | 242 |
/// allocation. |
243 | 243 |
|
244 | 244 |
/// Using this it is possible to avoid the superfluous memory |
245 | 245 |
/// allocation: if you know that the digraph you want to build will |
246 | 246 |
/// be very large (e.g. it will contain millions of nodes and/or arcs) |
247 | 247 |
/// then it is worth reserving space for this amount before starting |
248 | 248 |
/// to build the digraph. |
249 | 249 |
/// \sa reserveArc |
250 | 250 |
void reserveNode(int n) { nodes.reserve(n); }; |
251 | 251 |
|
252 | 252 |
/// \brief Using this it is possible to avoid the superfluous memory |
253 | 253 |
/// allocation. |
254 | 254 |
|
255 | 255 |
/// Using this it is possible to avoid the superfluous memory |
256 | 256 |
/// allocation: if you know that the digraph you want to build will |
257 | 257 |
/// be very large (e.g. it will contain millions of nodes and/or arcs) |
258 | 258 |
/// then it is worth reserving space for this amount before starting |
259 | 259 |
/// to build the digraph. |
260 | 260 |
/// \sa reserveNode |
261 | 261 |
void reserveArc(int m) { arcs.reserve(m); }; |
262 | 262 |
|
263 | 263 |
/// \brief Node validity check |
264 | 264 |
/// |
265 | 265 |
/// This function gives back true if the given node is valid, |
266 | 266 |
/// ie. it is a real node of the graph. |
267 | 267 |
/// |
268 | 268 |
/// \warning A removed node (using Snapshot) could become valid again |
269 | 269 |
/// when new nodes are added to the graph. |
270 | 270 |
bool valid(Node n) const { return Parent::valid(n); } |
271 | 271 |
|
272 | 272 |
/// \brief Arc validity check |
273 | 273 |
/// |
274 | 274 |
/// This function gives back true if the given arc is valid, |
275 | 275 |
/// ie. it is a real arc of the graph. |
276 | 276 |
/// |
277 | 277 |
/// \warning A removed arc (using Snapshot) could become valid again |
278 | 278 |
/// when new arcs are added to the graph. |
279 | 279 |
bool valid(Arc a) const { return Parent::valid(a); } |
280 | 280 |
|
281 | 281 |
///Clear the digraph. |
282 | 282 |
|
283 | 283 |
///Erase all the nodes and arcs from the digraph. |
284 | 284 |
/// |
285 | 285 |
void clear() { |
286 | 286 |
Parent::clear(); |
287 | 287 |
} |
288 | 288 |
|
289 | 289 |
///Split a node. |
290 | 290 |
|
291 | 291 |
///This function splits a node. First a new node is added to the digraph, |
292 | 292 |
///then the source of each outgoing arc of \c n is moved to this new node. |
293 | 293 |
///If \c connect is \c true (this is the default value), then a new arc |
294 | 294 |
///from \c n to the newly created node is also added. |
295 | 295 |
///\return The newly created node. |
296 | 296 |
/// |
297 | 297 |
///\note The <tt>Arc</tt>s |
298 | 298 |
///referencing a moved arc remain |
299 | 299 |
///valid. However <tt>InArc</tt>'s and <tt>OutArc</tt>'s |
300 | 300 |
///may be invalidated. |
301 | 301 |
///\warning This functionality cannot be used together with the Snapshot |
302 | 302 |
///feature. |
303 |
///\todo It could be implemented in a bit faster way. |
|
304 | 303 |
Node split(Node n, bool connect = true) |
305 | 304 |
{ |
306 | 305 |
Node b = addNode(); |
307 | 306 |
nodes[b._id].first_out=nodes[n._id].first_out; |
308 | 307 |
nodes[n._id].first_out=-1; |
309 | 308 |
for(int i=nodes[b._id].first_out;i!=-1;i++) arcs[i].source=b._id; |
310 | 309 |
if(connect) addArc(n,b); |
311 | 310 |
return b; |
312 | 311 |
} |
313 | 312 |
|
314 | 313 |
public: |
315 | 314 |
|
316 | 315 |
class Snapshot; |
317 | 316 |
|
318 | 317 |
protected: |
319 | 318 |
|
320 | 319 |
void restoreSnapshot(const Snapshot &s) |
321 | 320 |
{ |
322 | 321 |
while(s.arc_num<arcs.size()) { |
323 | 322 |
Arc arc = arcFromId(arcs.size()-1); |
324 | 323 |
Parent::notifier(Arc()).erase(arc); |
325 | 324 |
nodes[arcs.back().source].first_out=arcs.back().next_out; |
326 | 325 |
nodes[arcs.back().target].first_in=arcs.back().next_in; |
327 | 326 |
arcs.pop_back(); |
328 | 327 |
} |
329 | 328 |
while(s.node_num<nodes.size()) { |
330 | 329 |
Node node = nodeFromId(nodes.size()-1); |
331 | 330 |
Parent::notifier(Node()).erase(node); |
332 | 331 |
nodes.pop_back(); |
333 | 332 |
} |
334 | 333 |
} |
335 | 334 |
|
336 | 335 |
public: |
337 | 336 |
|
338 | 337 |
///Class to make a snapshot of the digraph and to restrore to it later. |
339 | 338 |
|
340 | 339 |
///Class to make a snapshot of the digraph and to restrore to it later. |
341 | 340 |
/// |
342 | 341 |
///The newly added nodes and arcs can be removed using the |
343 | 342 |
///restore() function. |
344 | 343 |
///\note After you restore a state, you cannot restore |
345 | 344 |
///a later state, in other word you cannot add again the arcs deleted |
346 | 345 |
///by restore() using another one Snapshot instance. |
347 | 346 |
/// |
348 | 347 |
///\warning If you do not use correctly the snapshot that can cause |
349 | 348 |
///either broken program, invalid state of the digraph, valid but |
350 | 349 |
///not the restored digraph or no change. Because the runtime performance |
351 | 350 |
///the validity of the snapshot is not stored. |
352 | 351 |
class Snapshot |
353 | 352 |
{ |
354 | 353 |
SmartDigraph *_graph; |
355 | 354 |
protected: |
356 | 355 |
friend class SmartDigraph; |
357 | 356 |
unsigned int node_num; |
358 | 357 |
unsigned int arc_num; |
359 | 358 |
public: |
360 | 359 |
///Default constructor. |
361 | 360 |
|
362 | 361 |
///Default constructor. |
363 | 362 |
///To actually make a snapshot you must call save(). |
364 | 363 |
/// |
365 | 364 |
Snapshot() : _graph(0) {} |
366 | 365 |
///Constructor that immediately makes a snapshot |
367 | 366 |
|
368 | 367 |
///This constructor immediately makes a snapshot of the digraph. |
369 | 368 |
///\param _g The digraph we make a snapshot of. |
370 | 369 |
Snapshot(SmartDigraph &graph) : _graph(&graph) { |
371 | 370 |
node_num=_graph->nodes.size(); |
372 | 371 |
arc_num=_graph->arcs.size(); |
373 | 372 |
} |
374 | 373 |
|
375 | 374 |
///Make a snapshot. |
376 | 375 |
|
377 | 376 |
///Make a snapshot of the digraph. |
378 | 377 |
/// |
379 | 378 |
///This function can be called more than once. In case of a repeated |
380 | 379 |
///call, the previous snapshot gets lost. |
381 | 380 |
///\param _g The digraph we make the snapshot of. |
382 | 381 |
void save(SmartDigraph &graph) |
383 | 382 |
{ |
384 | 383 |
_graph=&graph; |
385 | 384 |
node_num=_graph->nodes.size(); |
386 | 385 |
arc_num=_graph->arcs.size(); |
387 | 386 |
} |
388 | 387 |
|
389 | 388 |
///Undo the changes until a snapshot. |
390 | 389 |
|
391 | 390 |
///Undo the changes until a snapshot created by save(). |
392 | 391 |
/// |
393 | 392 |
///\note After you restored a state, you cannot restore |
394 | 393 |
///a later state, in other word you cannot add again the arcs deleted |
395 | 394 |
///by restore(). |
396 | 395 |
void restore() |
397 | 396 |
{ |
398 | 397 |
_graph->restoreSnapshot(*this); |
399 | 398 |
} |
400 | 399 |
}; |
401 | 400 |
}; |
402 | 401 |
|
403 | 402 |
|
404 | 403 |
class SmartGraphBase { |
405 | 404 |
|
406 | 405 |
protected: |
407 | 406 |
|
408 | 407 |
struct NodeT { |
409 | 408 |
int first_out; |
410 | 409 |
}; |
411 | 410 |
|
412 | 411 |
struct ArcT { |
413 | 412 |
int target; |
414 | 413 |
int next_out; |
415 | 414 |
}; |
416 | 415 |
|
417 | 416 |
std::vector<NodeT> nodes; |
418 | 417 |
std::vector<ArcT> arcs; |
419 | 418 |
|
420 | 419 |
int first_free_arc; |
421 | 420 |
|
422 | 421 |
public: |
423 | 422 |
|
424 | 423 |
typedef SmartGraphBase Digraph; |
425 | 424 |
|
426 | 425 |
class Node; |
427 | 426 |
class Arc; |
428 | 427 |
class Edge; |
429 | 428 |
|
430 | 429 |
class Node { |
431 | 430 |
friend class SmartGraphBase; |
432 | 431 |
protected: |
433 | 432 |
|
434 | 433 |
int _id; |
435 | 434 |
explicit Node(int id) { _id = id;} |
436 | 435 |
|
437 | 436 |
public: |
438 | 437 |
Node() {} |
439 | 438 |
Node (Invalid) { _id = -1; } |
440 | 439 |
bool operator==(const Node& node) const {return _id == node._id;} |
441 | 440 |
bool operator!=(const Node& node) const {return _id != node._id;} |
442 | 441 |
bool operator<(const Node& node) const {return _id < node._id;} |
443 | 442 |
}; |
444 | 443 |
|
445 | 444 |
class Edge { |
446 | 445 |
friend class SmartGraphBase; |
447 | 446 |
protected: |
448 | 447 |
|
449 | 448 |
int _id; |
450 | 449 |
explicit Edge(int id) { _id = id;} |
451 | 450 |
|
452 | 451 |
public: |
453 | 452 |
Edge() {} |
454 | 453 |
Edge (Invalid) { _id = -1; } |
455 | 454 |
bool operator==(const Edge& arc) const {return _id == arc._id;} |
456 | 455 |
bool operator!=(const Edge& arc) const {return _id != arc._id;} |
457 | 456 |
bool operator<(const Edge& arc) const {return _id < arc._id;} |
458 | 457 |
}; |
459 | 458 |
|
460 | 459 |
class Arc { |
461 | 460 |
friend class SmartGraphBase; |
462 | 461 |
protected: |
463 | 462 |
|
464 | 463 |
int _id; |
465 | 464 |
explicit Arc(int id) { _id = id;} |
466 | 465 |
|
467 | 466 |
public: |
468 | 467 |
operator Edge() const { |
469 | 468 |
return _id != -1 ? edgeFromId(_id / 2) : INVALID; |
470 | 469 |
} |
471 | 470 |
|
472 | 471 |
Arc() {} |
473 | 472 |
Arc (Invalid) { _id = -1; } |
474 | 473 |
bool operator==(const Arc& arc) const {return _id == arc._id;} |
475 | 474 |
bool operator!=(const Arc& arc) const {return _id != arc._id;} |
476 | 475 |
bool operator<(const Arc& arc) const {return _id < arc._id;} |
477 | 476 |
}; |
478 | 477 |
|
479 | 478 |
|
480 | 479 |
|
481 | 480 |
SmartGraphBase() |
482 | 481 |
: nodes(), arcs() {} |
483 | 482 |
|
484 | 483 |
|
485 | 484 |
int maxNodeId() const { return nodes.size()-1; } |
486 | 485 |
int maxEdgeId() const { return arcs.size() / 2 - 1; } |
487 | 486 |
int maxArcId() const { return arcs.size()-1; } |
488 | 487 |
|
489 | 488 |
Node source(Arc e) const { return Node(arcs[e._id ^ 1].target); } |
490 | 489 |
Node target(Arc e) const { return Node(arcs[e._id].target); } |
491 | 490 |
|
492 | 491 |
Node u(Edge e) const { return Node(arcs[2 * e._id].target); } |
493 | 492 |
Node v(Edge e) const { return Node(arcs[2 * e._id + 1].target); } |
494 | 493 |
|
495 | 494 |
static bool direction(Arc e) { |
496 | 495 |
return (e._id & 1) == 1; |
497 | 496 |
} |
498 | 497 |
|
499 | 498 |
static Arc direct(Edge e, bool d) { |
500 | 499 |
return Arc(e._id * 2 + (d ? 1 : 0)); |
501 | 500 |
} |
502 | 501 |
|
503 | 502 |
void first(Node& node) const { |
504 | 503 |
node._id = nodes.size() - 1; |
505 | 504 |
} |
506 | 505 |
|
507 | 506 |
void next(Node& node) const { |
508 | 507 |
--node._id; |
509 | 508 |
} |
510 | 509 |
|
511 | 510 |
void first(Arc& arc) const { |
512 | 511 |
arc._id = arcs.size() - 1; |
513 | 512 |
} |
514 | 513 |
|
515 | 514 |
void next(Arc& arc) const { |
516 | 515 |
--arc._id; |
517 | 516 |
} |
518 | 517 |
|
519 | 518 |
void first(Edge& arc) const { |
520 | 519 |
arc._id = arcs.size() / 2 - 1; |
521 | 520 |
} |
522 | 521 |
|
523 | 522 |
void next(Edge& arc) const { |
524 | 523 |
--arc._id; |
525 | 524 |
} |
526 | 525 |
|
527 | 526 |
void firstOut(Arc &arc, const Node& v) const { |
528 | 527 |
arc._id = nodes[v._id].first_out; |
529 | 528 |
} |
530 | 529 |
void nextOut(Arc &arc) const { |
531 | 530 |
arc._id = arcs[arc._id].next_out; |
532 | 531 |
} |
533 | 532 |
|
534 | 533 |
void firstIn(Arc &arc, const Node& v) const { |
535 | 534 |
arc._id = ((nodes[v._id].first_out) ^ 1); |
536 | 535 |
if (arc._id == -2) arc._id = -1; |
537 | 536 |
} |
538 | 537 |
void nextIn(Arc &arc) const { |
539 | 538 |
arc._id = ((arcs[arc._id ^ 1].next_out) ^ 1); |
540 | 539 |
if (arc._id == -2) arc._id = -1; |
541 | 540 |
} |
542 | 541 |
|
543 | 542 |
void firstInc(Edge &arc, bool& d, const Node& v) const { |
544 | 543 |
int de = nodes[v._id].first_out; |
545 | 544 |
if (de != -1) { |
546 | 545 |
arc._id = de / 2; |
547 | 546 |
d = ((de & 1) == 1); |
548 | 547 |
} else { |
549 | 548 |
arc._id = -1; |
550 | 549 |
d = true; |
551 | 550 |
} |
552 | 551 |
} |
553 | 552 |
void nextInc(Edge &arc, bool& d) const { |
554 | 553 |
int de = (arcs[(arc._id * 2) | (d ? 1 : 0)].next_out); |
555 | 554 |
if (de != -1) { |
556 | 555 |
arc._id = de / 2; |
557 | 556 |
d = ((de & 1) == 1); |
558 | 557 |
} else { |
559 | 558 |
arc._id = -1; |
560 | 559 |
d = true; |
561 | 560 |
} |
562 | 561 |
} |
563 | 562 |
|
564 | 563 |
static int id(Node v) { return v._id; } |
565 | 564 |
static int id(Arc e) { return e._id; } |
566 | 565 |
static int id(Edge e) { return e._id; } |
567 | 566 |
|
568 | 567 |
static Node nodeFromId(int id) { return Node(id);} |
569 | 568 |
static Arc arcFromId(int id) { return Arc(id);} |
570 | 569 |
static Edge edgeFromId(int id) { return Edge(id);} |
571 | 570 |
|
572 | 571 |
bool valid(Node n) const { |
573 | 572 |
return n._id >= 0 && n._id < static_cast<int>(nodes.size()); |
574 | 573 |
} |
575 | 574 |
bool valid(Arc a) const { |
576 | 575 |
return a._id >= 0 && a._id < static_cast<int>(arcs.size()); |
577 | 576 |
} |
578 | 577 |
bool valid(Edge e) const { |
579 | 578 |
return e._id >= 0 && 2 * e._id < static_cast<int>(arcs.size()); |
580 | 579 |
} |
581 | 580 |
|
582 | 581 |
Node addNode() { |
583 | 582 |
int n = nodes.size(); |
584 | 583 |
nodes.push_back(NodeT()); |
585 | 584 |
nodes[n].first_out = -1; |
586 | 585 |
|
587 | 586 |
return Node(n); |
588 | 587 |
} |
589 | 588 |
|
590 | 589 |
Edge addEdge(Node u, Node v) { |
591 | 590 |
int n = arcs.size(); |
592 | 591 |
arcs.push_back(ArcT()); |
593 | 592 |
arcs.push_back(ArcT()); |
594 | 593 |
|
595 | 594 |
arcs[n].target = u._id; |
596 | 595 |
arcs[n | 1].target = v._id; |
597 | 596 |
|
598 | 597 |
arcs[n].next_out = nodes[v._id].first_out; |
599 | 598 |
nodes[v._id].first_out = n; |
600 | 599 |
|
601 | 600 |
arcs[n | 1].next_out = nodes[u._id].first_out; |
602 | 601 |
nodes[u._id].first_out = (n | 1); |
603 | 602 |
|
604 | 603 |
return Edge(n / 2); |
605 | 604 |
} |
606 | 605 |
|
607 | 606 |
void clear() { |
608 | 607 |
arcs.clear(); |
609 | 608 |
nodes.clear(); |
610 | 609 |
} |
611 | 610 |
|
612 | 611 |
}; |
613 | 612 |
|
614 | 613 |
typedef GraphExtender<SmartGraphBase> ExtendedSmartGraphBase; |
615 | 614 |
|
616 | 615 |
/// \ingroup graphs |
617 | 616 |
/// |
618 | 617 |
/// \brief A smart undirected graph class. |
619 | 618 |
/// |
620 | 619 |
/// This is a simple and fast graph implementation. |
621 | 620 |
/// It is also quite memory efficient, but at the price |
622 | 621 |
/// that <b> it does support only limited (only stack-like) |
623 | 622 |
/// node and arc deletions</b>. |
624 | 623 |
/// Except from this it conforms to |
625 | 624 |
/// the \ref concepts::Graph "Graph concept". |
626 | 625 |
/// |
627 | 626 |
/// It also has an |
628 | 627 |
/// important extra feature that |
629 | 628 |
/// its maps are real \ref concepts::ReferenceMap "reference map"s. |
630 | 629 |
/// |
631 | 630 |
/// \sa concepts::Graph. |
632 | 631 |
/// |
633 | 632 |
class SmartGraph : public ExtendedSmartGraphBase { |
634 | 633 |
private: |
635 | 634 |
|
636 | 635 |
///SmartGraph is \e not copy constructible. Use GraphCopy() instead. |
637 | 636 |
|
638 | 637 |
///SmartGraph is \e not copy constructible. Use GraphCopy() instead. |
639 | 638 |
/// |
640 | 639 |
SmartGraph(const SmartGraph &) : ExtendedSmartGraphBase() {}; |
641 | 640 |
|
642 | 641 |
///\brief Assignment of SmartGraph to another one is \e not allowed. |
643 | 642 |
///Use GraphCopy() instead. |
644 | 643 |
|
645 | 644 |
///Assignment of SmartGraph to another one is \e not allowed. |
646 | 645 |
///Use GraphCopy() instead. |
647 | 646 |
void operator=(const SmartGraph &) {} |
648 | 647 |
|
649 | 648 |
public: |
650 | 649 |
|
651 | 650 |
typedef ExtendedSmartGraphBase Parent; |
652 | 651 |
|
653 | 652 |
/// Constructor |
654 | 653 |
|
655 | 654 |
/// Constructor. |
656 | 655 |
/// |
657 | 656 |
SmartGraph() {} |
658 | 657 |
|
659 | 658 |
///Add a new node to the graph. |
660 | 659 |
|
661 | 660 |
/// \return the new node. |
662 | 661 |
/// |
663 | 662 |
Node addNode() { return Parent::addNode(); } |
664 | 663 |
|
665 | 664 |
///Add a new edge to the graph. |
666 | 665 |
|
667 | 666 |
///Add a new edge to the graph with node \c s |
668 | 667 |
///and \c t. |
669 | 668 |
///\return the new edge. |
670 | 669 |
Edge addEdge(const Node& s, const Node& t) { |
671 | 670 |
return Parent::addEdge(s, t); |
672 | 671 |
} |
673 | 672 |
|
674 | 673 |
/// \brief Node validity check |
675 | 674 |
/// |
676 | 675 |
/// This function gives back true if the given node is valid, |
677 | 676 |
/// ie. it is a real node of the graph. |
678 | 677 |
/// |
679 | 678 |
/// \warning A removed node (using Snapshot) could become valid again |
680 | 679 |
/// when new nodes are added to the graph. |
681 | 680 |
bool valid(Node n) const { return Parent::valid(n); } |
682 | 681 |
|
683 | 682 |
/// \brief Arc validity check |
684 | 683 |
/// |
685 | 684 |
/// This function gives back true if the given arc is valid, |
686 | 685 |
/// ie. it is a real arc of the graph. |
687 | 686 |
/// |
688 | 687 |
/// \warning A removed arc (using Snapshot) could become valid again |
689 | 688 |
/// when new edges are added to the graph. |
690 | 689 |
bool valid(Arc a) const { return Parent::valid(a); } |
691 | 690 |
|
692 | 691 |
/// \brief Edge validity check |
693 | 692 |
/// |
694 | 693 |
/// This function gives back true if the given edge is valid, |
695 | 694 |
/// ie. it is a real edge of the graph. |
696 | 695 |
/// |
697 | 696 |
/// \warning A removed edge (using Snapshot) could become valid again |
698 | 697 |
/// when new edges are added to the graph. |
699 | 698 |
bool valid(Edge e) const { return Parent::valid(e); } |
700 | 699 |
|
701 | 700 |
///Clear the graph. |
702 | 701 |
|
703 | 702 |
///Erase all the nodes and edges from the graph. |
704 | 703 |
/// |
705 | 704 |
void clear() { |
706 | 705 |
Parent::clear(); |
707 | 706 |
} |
708 | 707 |
|
709 | 708 |
public: |
710 | 709 |
|
711 | 710 |
class Snapshot; |
712 | 711 |
|
713 | 712 |
protected: |
714 | 713 |
|
715 | 714 |
void saveSnapshot(Snapshot &s) |
716 | 715 |
{ |
717 | 716 |
s._graph = this; |
718 | 717 |
s.node_num = nodes.size(); |
719 | 718 |
s.arc_num = arcs.size(); |
720 | 719 |
} |
721 | 720 |
|
722 | 721 |
void restoreSnapshot(const Snapshot &s) |
723 | 722 |
{ |
724 | 723 |
while(s.arc_num<arcs.size()) { |
725 | 724 |
int n=arcs.size()-1; |
726 | 725 |
Edge arc=edgeFromId(n/2); |
727 | 726 |
Parent::notifier(Edge()).erase(arc); |
728 | 727 |
std::vector<Arc> dir; |
729 | 728 |
dir.push_back(arcFromId(n)); |
730 | 729 |
dir.push_back(arcFromId(n-1)); |
731 | 730 |
Parent::notifier(Arc()).erase(dir); |
732 | 731 |
nodes[arcs[n].target].first_out=arcs[n].next_out; |
733 | 732 |
nodes[arcs[n-1].target].first_out=arcs[n-1].next_out; |
734 | 733 |
arcs.pop_back(); |
735 | 734 |
arcs.pop_back(); |
736 | 735 |
} |
737 | 736 |
while(s.node_num<nodes.size()) { |
738 | 737 |
int n=nodes.size()-1; |
739 | 738 |
Node node = nodeFromId(n); |
740 | 739 |
Parent::notifier(Node()).erase(node); |
741 | 740 |
nodes.pop_back(); |
742 | 741 |
} |
743 | 742 |
} |
744 | 743 |
|
745 | 744 |
public: |
746 | 745 |
|
747 | 746 |
///Class to make a snapshot of the digraph and to restrore to it later. |
748 | 747 |
|
749 | 748 |
///Class to make a snapshot of the digraph and to restrore to it later. |
750 | 749 |
/// |
751 | 750 |
///The newly added nodes and arcs can be removed using the |
752 | 751 |
///restore() function. |
753 | 752 |
/// |
754 | 753 |
///\note After you restore a state, you cannot restore |
755 | 754 |
///a later state, in other word you cannot add again the arcs deleted |
756 | 755 |
///by restore() using another one Snapshot instance. |
757 | 756 |
/// |
758 | 757 |
///\warning If you do not use correctly the snapshot that can cause |
759 | 758 |
///either broken program, invalid state of the digraph, valid but |
760 | 759 |
///not the restored digraph or no change. Because the runtime performance |
761 | 760 |
///the validity of the snapshot is not stored. |
762 | 761 |
class Snapshot |
763 | 762 |
{ |
764 | 763 |
SmartGraph *_graph; |
765 | 764 |
protected: |
766 | 765 |
friend class SmartGraph; |
767 | 766 |
unsigned int node_num; |
768 | 767 |
unsigned int arc_num; |
769 | 768 |
public: |
770 | 769 |
///Default constructor. |
771 | 770 |
|
772 | 771 |
///Default constructor. |
773 | 772 |
///To actually make a snapshot you must call save(). |
774 | 773 |
/// |
775 | 774 |
Snapshot() : _graph(0) {} |
776 | 775 |
///Constructor that immediately makes a snapshot |
777 | 776 |
|
778 | 777 |
///This constructor immediately makes a snapshot of the digraph. |
779 | 778 |
///\param g The digraph we make a snapshot of. |
780 | 779 |
Snapshot(SmartGraph &graph) { |
781 | 780 |
graph.saveSnapshot(*this); |
782 | 781 |
} |
783 | 782 |
|
784 | 783 |
///Make a snapshot. |
785 | 784 |
|
786 | 785 |
///Make a snapshot of the graph. |
787 | 786 |
/// |
788 | 787 |
///This function can be called more than once. In case of a repeated |
789 | 788 |
///call, the previous snapshot gets lost. |
790 | 789 |
///\param g The digraph we make the snapshot of. |
791 | 790 |
void save(SmartGraph &graph) |
792 | 791 |
{ |
793 | 792 |
graph.saveSnapshot(*this); |
794 | 793 |
} |
795 | 794 |
|
796 | 795 |
///Undo the changes until a snapshot. |
797 | 796 |
|
798 | 797 |
///Undo the changes until a snapshot created by save(). |
799 | 798 |
/// |
800 | 799 |
///\note After you restored a state, you cannot restore |
801 | 800 |
///a later state, in other word you cannot add again the arcs deleted |
802 | 801 |
///by restore(). |
803 | 802 |
void restore() |
804 | 803 |
{ |
805 | 804 |
_graph->restoreSnapshot(*this); |
806 | 805 |
} |
807 | 806 |
}; |
808 | 807 |
}; |
809 | 808 |
|
810 | 809 |
} //namespace lemon |
811 | 810 |
|
812 | 811 |
|
813 | 812 |
#endif //LEMON_SMART_GRAPH_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-2008 |
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_TIME_MEASURE_H |
20 | 20 |
#define LEMON_TIME_MEASURE_H |
21 | 21 |
|
22 | 22 |
///\ingroup timecount |
23 | 23 |
///\file |
24 | 24 |
///\brief Tools for measuring cpu usage |
25 | 25 |
|
26 | 26 |
#ifdef WIN32 |
27 | 27 |
#define WIN32_LEAN_AND_MEAN |
28 | 28 |
#define NOMINMAX |
29 | 29 |
#include <windows.h> |
30 | 30 |
#include <cmath> |
31 | 31 |
#else |
32 | 32 |
#include <sys/times.h> |
33 | 33 |
#include <sys/time.h> |
34 | 34 |
#endif |
35 | 35 |
|
36 | 36 |
#include <string> |
37 | 37 |
#include <fstream> |
38 | 38 |
#include <iostream> |
39 | 39 |
|
40 | 40 |
namespace lemon { |
41 | 41 |
|
42 | 42 |
/// \addtogroup timecount |
43 | 43 |
/// @{ |
44 | 44 |
|
45 | 45 |
/// A class to store (cpu)time instances. |
46 | 46 |
|
47 | 47 |
/// This class stores five time values. |
48 | 48 |
/// - a real time |
49 | 49 |
/// - a user cpu time |
50 | 50 |
/// - a system cpu time |
51 | 51 |
/// - a user cpu time of children |
52 | 52 |
/// - a system cpu time of children |
53 | 53 |
/// |
54 | 54 |
/// TimeStamp's can be added to or substracted from each other and |
55 | 55 |
/// they can be pushed to a stream. |
56 | 56 |
/// |
57 | 57 |
/// In most cases, perhaps the \ref Timer or the \ref TimeReport |
58 | 58 |
/// class is what you want to use instead. |
59 | 59 |
|
60 | 60 |
class TimeStamp |
61 | 61 |
{ |
62 | 62 |
double utime; |
63 | 63 |
double stime; |
64 | 64 |
double cutime; |
65 | 65 |
double cstime; |
66 | 66 |
double rtime; |
67 | 67 |
|
68 | 68 |
void _reset() { |
69 | 69 |
utime = stime = cutime = cstime = rtime = 0; |
70 | 70 |
} |
71 | 71 |
|
72 | 72 |
public: |
73 | 73 |
|
74 | 74 |
///Read the current time values of the process |
75 | 75 |
void stamp() |
76 | 76 |
{ |
77 | 77 |
#ifndef WIN32 |
78 | 78 |
timeval tv; |
79 | 79 |
gettimeofday(&tv, 0); |
80 | 80 |
rtime=tv.tv_sec+double(tv.tv_usec)/1e6; |
81 | 81 |
|
82 | 82 |
tms ts; |
83 | 83 |
double tck=sysconf(_SC_CLK_TCK); |
84 | 84 |
times(&ts); |
85 | 85 |
utime=ts.tms_utime/tck; |
86 | 86 |
stime=ts.tms_stime/tck; |
87 | 87 |
cutime=ts.tms_cutime/tck; |
88 | 88 |
cstime=ts.tms_cstime/tck; |
89 | 89 |
#else |
90 | 90 |
static const double ch = 4294967296.0e-7; |
91 | 91 |
static const double cl = 1.0e-7; |
92 | 92 |
|
93 | 93 |
FILETIME system; |
94 | 94 |
GetSystemTimeAsFileTime(&system); |
95 | 95 |
rtime = ch * system.dwHighDateTime + cl * system.dwLowDateTime; |
96 | 96 |
|
97 | 97 |
FILETIME create, exit, kernel, user; |
98 | 98 |
if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) { |
99 | 99 |
utime = ch * user.dwHighDateTime + cl * user.dwLowDateTime; |
100 | 100 |
stime = ch * kernel.dwHighDateTime + cl * kernel.dwLowDateTime; |
101 | 101 |
cutime = 0; |
102 | 102 |
cstime = 0; |
103 | 103 |
} else { |
104 | 104 |
rtime = 0; |
105 | 105 |
utime = 0; |
106 | 106 |
stime = 0; |
107 | 107 |
cutime = 0; |
108 | 108 |
cstime = 0; |
109 | 109 |
} |
110 | 110 |
#endif |
111 | 111 |
} |
112 | 112 |
|
113 | 113 |
/// Constructor initializing with zero |
114 | 114 |
TimeStamp() |
115 | 115 |
{ _reset(); } |
116 | 116 |
///Constructor initializing with the current time values of the process |
117 | 117 |
TimeStamp(void *) { stamp();} |
118 | 118 |
|
119 | 119 |
///Set every time value to zero |
120 | 120 |
TimeStamp &reset() {_reset();return *this;} |
121 | 121 |
|
122 | 122 |
///\e |
123 | 123 |
TimeStamp &operator+=(const TimeStamp &b) |
124 | 124 |
{ |
125 | 125 |
utime+=b.utime; |
126 | 126 |
stime+=b.stime; |
127 | 127 |
cutime+=b.cutime; |
128 | 128 |
cstime+=b.cstime; |
129 | 129 |
rtime+=b.rtime; |
130 | 130 |
return *this; |
131 | 131 |
} |
132 | 132 |
///\e |
133 | 133 |
TimeStamp operator+(const TimeStamp &b) const |
134 | 134 |
{ |
135 | 135 |
TimeStamp t(*this); |
136 | 136 |
return t+=b; |
137 | 137 |
} |
138 | 138 |
///\e |
139 | 139 |
TimeStamp &operator-=(const TimeStamp &b) |
140 | 140 |
{ |
141 | 141 |
utime-=b.utime; |
142 | 142 |
stime-=b.stime; |
143 | 143 |
cutime-=b.cutime; |
144 | 144 |
cstime-=b.cstime; |
145 | 145 |
rtime-=b.rtime; |
146 | 146 |
return *this; |
147 | 147 |
} |
148 | 148 |
///\e |
149 | 149 |
TimeStamp operator-(const TimeStamp &b) const |
150 | 150 |
{ |
151 | 151 |
TimeStamp t(*this); |
152 | 152 |
return t-=b; |
153 | 153 |
} |
154 | 154 |
///\e |
155 | 155 |
TimeStamp &operator*=(double b) |
156 | 156 |
{ |
157 | 157 |
utime*=b; |
158 | 158 |
stime*=b; |
159 | 159 |
cutime*=b; |
160 | 160 |
cstime*=b; |
161 | 161 |
rtime*=b; |
162 | 162 |
return *this; |
163 | 163 |
} |
164 | 164 |
///\e |
165 | 165 |
TimeStamp operator*(double b) const |
166 | 166 |
{ |
167 | 167 |
TimeStamp t(*this); |
168 | 168 |
return t*=b; |
169 | 169 |
} |
170 | 170 |
friend TimeStamp operator*(double b,const TimeStamp &t); |
171 | 171 |
///\e |
172 | 172 |
TimeStamp &operator/=(double b) |
173 | 173 |
{ |
174 | 174 |
utime/=b; |
175 | 175 |
stime/=b; |
176 | 176 |
cutime/=b; |
177 | 177 |
cstime/=b; |
178 | 178 |
rtime/=b; |
179 | 179 |
return *this; |
180 | 180 |
} |
181 | 181 |
///\e |
182 | 182 |
TimeStamp operator/(double b) const |
183 | 183 |
{ |
184 | 184 |
TimeStamp t(*this); |
185 | 185 |
return t/=b; |
186 | 186 |
} |
187 | 187 |
///The time ellapsed since the last call of stamp() |
188 | 188 |
TimeStamp ellapsed() const |
189 | 189 |
{ |
190 | 190 |
TimeStamp t(NULL); |
191 | 191 |
return t-*this; |
192 | 192 |
} |
193 | 193 |
|
194 | 194 |
friend std::ostream& operator<<(std::ostream& os,const TimeStamp &t); |
195 | 195 |
|
196 | 196 |
///Gives back the user time of the process |
197 | 197 |
double userTime() const |
198 | 198 |
{ |
199 | 199 |
return utime; |
200 | 200 |
} |
201 | 201 |
///Gives back the system time of the process |
202 | 202 |
double systemTime() const |
203 | 203 |
{ |
204 | 204 |
return stime; |
205 | 205 |
} |
206 | 206 |
///Gives back the user time of the process' children |
207 | 207 |
|
208 | 208 |
///\note On <tt>WIN32</tt> platform this value is not calculated. |
209 | 209 |
/// |
210 | 210 |
double cUserTime() const |
211 | 211 |
{ |
212 | 212 |
return cutime; |
213 | 213 |
} |
214 | 214 |
///Gives back the user time of the process' children |
215 | 215 |
|
216 | 216 |
///\note On <tt>WIN32</tt> platform this value is not calculated. |
217 | 217 |
/// |
218 | 218 |
double cSystemTime() const |
219 | 219 |
{ |
220 | 220 |
return cstime; |
221 | 221 |
} |
222 | 222 |
///Gives back the real time |
223 | 223 |
double realTime() const {return rtime;} |
224 | 224 |
}; |
225 | 225 |
|
226 | 226 |
TimeStamp operator*(double b,const TimeStamp &t) |
227 | 227 |
{ |
228 | 228 |
return t*b; |
229 | 229 |
} |
230 | 230 |
|
231 | 231 |
///Prints the time counters |
232 | 232 |
|
233 | 233 |
///Prints the time counters in the following form: |
234 | 234 |
/// |
235 | 235 |
/// <tt>u: XX.XXs s: XX.XXs cu: XX.XXs cs: XX.XXs real: XX.XXs</tt> |
236 | 236 |
/// |
237 | 237 |
/// where the values are the |
238 | 238 |
/// \li \c u: user cpu time, |
239 | 239 |
/// \li \c s: system cpu time, |
240 | 240 |
/// \li \c cu: user cpu time of children, |
241 | 241 |
/// \li \c cs: system cpu time of children, |
242 | 242 |
/// \li \c real: real time. |
243 | 243 |
/// \relates TimeStamp |
244 | 244 |
/// \note On <tt>WIN32</tt> platform the cummulative values are not |
245 | 245 |
/// calculated. |
246 | 246 |
inline std::ostream& operator<<(std::ostream& os,const TimeStamp &t) |
247 | 247 |
{ |
248 | 248 |
os << "u: " << t.userTime() << |
249 | 249 |
"s, s: " << t.systemTime() << |
250 | 250 |
"s, cu: " << t.cUserTime() << |
251 | 251 |
"s, cs: " << t.cSystemTime() << |
252 | 252 |
"s, real: " << t.realTime() << "s"; |
253 | 253 |
return os; |
254 | 254 |
} |
255 | 255 |
|
256 | 256 |
///Class for measuring the cpu time and real time usage of the process |
257 | 257 |
|
258 | 258 |
///Class for measuring the cpu time and real time usage of the process. |
259 | 259 |
///It is quite easy-to-use, here is a short example. |
260 | 260 |
///\code |
261 | 261 |
/// #include<lemon/time_measure.h> |
262 | 262 |
/// #include<iostream> |
263 | 263 |
/// |
264 | 264 |
/// int main() |
265 | 265 |
/// { |
266 | 266 |
/// |
267 | 267 |
/// ... |
268 | 268 |
/// |
269 | 269 |
/// Timer t; |
270 | 270 |
/// doSomething(); |
271 | 271 |
/// std::cout << t << '\n'; |
272 | 272 |
/// t.restart(); |
273 | 273 |
/// doSomethingElse(); |
274 | 274 |
/// std::cout << t << '\n'; |
275 | 275 |
/// |
276 | 276 |
/// ... |
277 | 277 |
/// |
278 | 278 |
/// } |
279 | 279 |
///\endcode |
280 | 280 |
/// |
281 | 281 |
///The \ref Timer can also be \ref stop() "stopped" and |
282 | 282 |
///\ref start() "started" again, so it is possible to compute collected |
283 | 283 |
///running times. |
284 | 284 |
/// |
285 | 285 |
///\warning Depending on the operation system and its actual configuration |
286 | 286 |
///the time counters have a certain (10ms on a typical Linux system) |
287 | 287 |
///granularity. |
288 | 288 |
///Therefore this tool is not appropriate to measure very short times. |
289 | 289 |
///Also, if you start and stop the timer very frequently, it could lead to |
290 | 290 |
///distorted results. |
291 | 291 |
/// |
292 | 292 |
///\note If you want to measure the running time of the execution of a certain |
293 | 293 |
///function, consider the usage of \ref TimeReport instead. |
294 | 294 |
/// |
295 |
///\todo This shouldn't be Unix (Linux) specific. |
|
296 | 295 |
///\sa TimeReport |
297 | 296 |
class Timer |
298 | 297 |
{ |
299 | 298 |
int _running; //Timer is running iff _running>0; (_running>=0 always holds) |
300 | 299 |
TimeStamp start_time; //This is the relativ start-time if the timer |
301 | 300 |
//is _running, the collected _running time otherwise. |
302 | 301 |
|
303 | 302 |
void _reset() {if(_running) start_time.stamp(); else start_time.reset();} |
304 | 303 |
|
305 | 304 |
public: |
306 | 305 |
///Constructor. |
307 | 306 |
|
308 | 307 |
///\param run indicates whether or not the timer starts immediately. |
309 | 308 |
/// |
310 | 309 |
Timer(bool run=true) :_running(run) {_reset();} |
311 | 310 |
|
312 | 311 |
///\name Control the state of the timer |
313 | 312 |
///Basically a Timer can be either running or stopped, |
314 | 313 |
///but it provides a bit finer control on the execution. |
315 | 314 |
///The \ref Timer also counts the number of \ref start() |
316 | 315 |
///executions, and is stops only after the same amount (or more) |
317 | 316 |
///\ref stop() "stop()"s. This can be useful e.g. to compute |
318 | 317 |
///the running time |
319 | 318 |
///of recursive functions. |
320 | 319 |
/// |
321 | 320 |
|
322 | 321 |
///@{ |
323 | 322 |
|
324 | 323 |
///Reset and stop the time counters |
325 | 324 |
|
326 | 325 |
///This function resets and stops the time counters |
327 | 326 |
///\sa restart() |
328 | 327 |
void reset() |
329 | 328 |
{ |
330 | 329 |
_running=0; |
331 | 330 |
_reset(); |
332 | 331 |
} |
333 | 332 |
|
334 | 333 |
///Start the time counters |
335 | 334 |
|
336 | 335 |
///This function starts the time counters. |
337 | 336 |
/// |
338 | 337 |
///If the timer is started more than ones, it will remain running |
339 | 338 |
///until the same amount of \ref stop() is called. |
340 | 339 |
///\sa stop() |
341 | 340 |
void start() |
342 | 341 |
{ |
343 | 342 |
if(_running) _running++; |
344 | 343 |
else { |
345 | 344 |
_running=1; |
346 | 345 |
TimeStamp t; |
347 | 346 |
t.stamp(); |
348 | 347 |
start_time=t-start_time; |
349 | 348 |
} |
350 | 349 |
} |
351 | 350 |
|
352 | 351 |
|
353 | 352 |
///Stop the time counters |
354 | 353 |
|
355 | 354 |
///This function stops the time counters. If start() was executed more than |
356 | 355 |
///once, then the same number of stop() execution is necessary the really |
357 | 356 |
///stop the timer. |
358 | 357 |
/// |
359 | 358 |
///\sa halt() |
360 | 359 |
///\sa start() |
361 | 360 |
///\sa restart() |
362 | 361 |
///\sa reset() |
363 | 362 |
|
364 | 363 |
void stop() |
365 | 364 |
{ |
366 | 365 |
if(_running && !--_running) { |
367 | 366 |
TimeStamp t; |
368 | 367 |
t.stamp(); |
369 | 368 |
start_time=t-start_time; |
370 | 369 |
} |
371 | 370 |
} |
372 | 371 |
|
373 | 372 |
///Halt (i.e stop immediately) the time counters |
374 | 373 |
|
375 | 374 |
///This function stops immediately the time counters, i.e. <tt>t.halt()</tt> |
376 | 375 |
///is a faster |
377 | 376 |
///equivalent of the following. |
378 | 377 |
///\code |
379 | 378 |
/// while(t.running()) t.stop() |
380 | 379 |
///\endcode |
381 | 380 |
/// |
382 | 381 |
/// |
383 | 382 |
///\sa stop() |
384 | 383 |
///\sa restart() |
385 | 384 |
///\sa reset() |
386 | 385 |
|
387 | 386 |
void halt() |
388 | 387 |
{ |
389 | 388 |
if(_running) { |
390 | 389 |
_running=0; |
391 | 390 |
TimeStamp t; |
392 | 391 |
t.stamp(); |
393 | 392 |
start_time=t-start_time; |
394 | 393 |
} |
395 | 394 |
} |
396 | 395 |
|
397 | 396 |
///Returns the running state of the timer |
398 | 397 |
|
399 | 398 |
///This function returns the number of stop() exections that is |
400 | 399 |
///necessary to really stop the timer. |
401 | 400 |
///For example the timer |
402 | 401 |
///is running if and only if the return value is \c true |
403 | 402 |
///(i.e. greater than |
404 | 403 |
///zero). |
405 | 404 |
int running() { return _running; } |
406 | 405 |
|
407 | 406 |
|
408 | 407 |
///Restart the time counters |
409 | 408 |
|
410 | 409 |
///This function is a shorthand for |
411 | 410 |
///a reset() and a start() calls. |
412 | 411 |
/// |
413 | 412 |
void restart() |
414 | 413 |
{ |
415 | 414 |
reset(); |
416 | 415 |
start(); |
417 | 416 |
} |
418 | 417 |
|
419 | 418 |
///@} |
420 | 419 |
|
421 | 420 |
///\name Query Functions for the ellapsed time |
422 | 421 |
|
423 | 422 |
///@{ |
424 | 423 |
|
425 | 424 |
///Gives back the ellapsed user time of the process |
426 | 425 |
double userTime() const |
427 | 426 |
{ |
428 | 427 |
return operator TimeStamp().userTime(); |
429 | 428 |
} |
430 | 429 |
///Gives back the ellapsed system time of the process |
431 | 430 |
double systemTime() const |
432 | 431 |
{ |
433 | 432 |
return operator TimeStamp().systemTime(); |
434 | 433 |
} |
435 | 434 |
///Gives back the ellapsed user time of the process' children |
436 | 435 |
|
437 | 436 |
///\note On <tt>WIN32</tt> platform this value is not calculated. |
438 | 437 |
/// |
439 | 438 |
double cUserTime() const |
440 | 439 |
{ |
441 | 440 |
return operator TimeStamp().cUserTime(); |
442 | 441 |
} |
443 | 442 |
///Gives back the ellapsed user time of the process' children |
444 | 443 |
|
445 | 444 |
///\note On <tt>WIN32</tt> platform this value is not calculated. |
446 | 445 |
/// |
447 | 446 |
double cSystemTime() const |
448 | 447 |
{ |
449 | 448 |
return operator TimeStamp().cSystemTime(); |
450 | 449 |
} |
451 | 450 |
///Gives back the ellapsed real time |
452 | 451 |
double realTime() const |
453 | 452 |
{ |
454 | 453 |
return operator TimeStamp().realTime(); |
455 | 454 |
} |
456 | 455 |
///Computes the ellapsed time |
457 | 456 |
|
458 | 457 |
///This conversion computes the ellapsed time, therefore you can print |
459 | 458 |
///the ellapsed time like this. |
460 | 459 |
///\code |
461 | 460 |
/// Timer t; |
462 | 461 |
/// doSomething(); |
463 | 462 |
/// std::cout << t << '\n'; |
464 | 463 |
///\endcode |
465 | 464 |
operator TimeStamp () const |
466 | 465 |
{ |
467 | 466 |
TimeStamp t; |
468 | 467 |
t.stamp(); |
469 | 468 |
return _running?t-start_time:start_time; |
470 | 469 |
} |
471 | 470 |
|
472 | 471 |
|
473 | 472 |
///@} |
474 | 473 |
}; |
475 | 474 |
|
476 | 475 |
///Same as \ref Timer but prints a report on destruction. |
477 | 476 |
|
478 | 477 |
///Same as \ref Timer but prints a report on destruction. |
479 | 478 |
///This example shows its usage. |
480 | 479 |
///\code |
481 | 480 |
/// void myAlg(ListGraph &g,int n) |
482 | 481 |
/// { |
483 | 482 |
/// TimeReport tr("Running time of myAlg: "); |
484 | 483 |
/// ... //Here comes the algorithm |
485 | 484 |
/// } |
486 | 485 |
///\endcode |
487 | 486 |
/// |
488 | 487 |
///\sa Timer |
489 | 488 |
///\sa NoTimeReport |
490 |
///\todo There is no test case for this |
|
491 | 489 |
class TimeReport : public Timer |
492 | 490 |
{ |
493 | 491 |
std::string _title; |
494 | 492 |
std::ostream &_os; |
495 | 493 |
public: |
496 | 494 |
///\e |
497 | 495 |
|
498 | 496 |
///\param title This text will be printed before the ellapsed time. |
499 | 497 |
///\param os The stream to print the report to. |
500 | 498 |
///\param run Sets whether the timer should start immediately. |
501 | 499 |
|
502 | 500 |
TimeReport(std::string title,std::ostream &os=std::cerr,bool run=true) |
503 | 501 |
: Timer(run), _title(title), _os(os){} |
504 | 502 |
///\e Prints the ellapsed time on destruction. |
505 | 503 |
~TimeReport() |
506 | 504 |
{ |
507 | 505 |
_os << _title << *this << std::endl; |
508 | 506 |
} |
509 | 507 |
}; |
510 | 508 |
|
511 | 509 |
///'Do nothing' version of \ref TimeReport |
512 | 510 |
|
513 | 511 |
///\sa TimeReport |
514 | 512 |
/// |
515 | 513 |
class NoTimeReport |
516 | 514 |
{ |
517 | 515 |
public: |
518 | 516 |
///\e |
519 | 517 |
NoTimeReport(std::string,std::ostream &,bool) {} |
520 | 518 |
///\e |
521 | 519 |
NoTimeReport(std::string,std::ostream &) {} |
522 | 520 |
///\e |
523 | 521 |
NoTimeReport(std::string) {} |
524 | 522 |
///\e Do nothing. |
525 | 523 |
~NoTimeReport() {} |
526 | 524 |
|
527 | 525 |
operator TimeStamp () const { return TimeStamp(); } |
528 | 526 |
void reset() {} |
529 | 527 |
void start() {} |
530 | 528 |
void stop() {} |
531 | 529 |
void halt() {} |
532 | 530 |
int running() { return 0; } |
533 | 531 |
void restart() {} |
534 | 532 |
double userTime() const { return 0; } |
535 | 533 |
double systemTime() const { return 0; } |
536 | 534 |
double cUserTime() const { return 0; } |
537 | 535 |
double cSystemTime() const { return 0; } |
538 | 536 |
double realTime() const { return 0; } |
539 | 537 |
}; |
540 | 538 |
|
541 | 539 |
///Tool to measure the running time more exactly. |
542 | 540 |
|
543 | 541 |
///This function calls \c f several times and returns the average |
544 | 542 |
///running time. The number of the executions will be choosen in such a way |
545 | 543 |
///that the full real running time will be roughly between \c min_time |
546 | 544 |
///and <tt>2*min_time</tt>. |
547 | 545 |
///\param f the function object to be measured. |
548 | 546 |
///\param min_time the minimum total running time. |
549 | 547 |
///\retval num if it is not \c NULL, then the actual |
550 | 548 |
/// number of execution of \c f will be written into <tt>*num</tt>. |
551 | 549 |
///\retval full_time if it is not \c NULL, then the actual |
552 | 550 |
/// total running time will be written into <tt>*full_time</tt>. |
553 | 551 |
///\return The average running time of \c f. |
554 | 552 |
|
555 | 553 |
template<class F> |
556 | 554 |
TimeStamp runningTimeTest(F f,double min_time=10,unsigned int *num = NULL, |
557 | 555 |
TimeStamp *full_time=NULL) |
558 | 556 |
{ |
559 | 557 |
TimeStamp full; |
560 | 558 |
unsigned int total=0; |
561 | 559 |
Timer t; |
562 | 560 |
for(unsigned int tn=1;tn <= 1U<<31 && full.realTime()<=min_time; tn*=2) { |
563 | 561 |
for(;total<tn;total++) f(); |
564 | 562 |
full=t; |
565 | 563 |
} |
566 | 564 |
if(num) *num=total; |
567 | 565 |
if(full_time) *full_time=full; |
568 | 566 |
return full/total; |
569 | 567 |
} |
570 | 568 |
|
571 | 569 |
/// @} |
572 | 570 |
|
573 | 571 |
|
574 | 572 |
} //namespace lemon |
575 | 573 |
|
576 | 574 |
#endif //LEMON_TIME_MEASURE_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-2008 |
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_TOLERANCE_H |
20 | 20 |
#define LEMON_TOLERANCE_H |
21 | 21 |
|
22 | 22 |
///\ingroup misc |
23 | 23 |
///\file |
24 | 24 |
///\brief A basic tool to handle the anomalies of calculation with |
25 | 25 |
///floating point numbers. |
26 | 26 |
/// |
27 |
///\todo It should be in a module like "Basic tools" |
|
28 |
|
|
29 | 27 |
|
30 | 28 |
namespace lemon { |
31 | 29 |
|
32 | 30 |
/// \addtogroup misc |
33 | 31 |
/// @{ |
34 | 32 |
|
35 | 33 |
///\brief A class to provide a basic way to |
36 | 34 |
///handle the comparison of numbers that are obtained |
37 | 35 |
///as a result of a probably inexact computation. |
38 | 36 |
/// |
39 | 37 |
///\ref Tolerance is a class to provide a basic way to |
40 | 38 |
///handle the comparison of numbers that are obtained |
41 | 39 |
///as a result of a probably inexact computation. |
42 | 40 |
/// |
43 | 41 |
///This is an abstract class, it should be specialized for all |
44 | 42 |
///numerical data types. These specialized classes like |
45 | 43 |
///Tolerance<double> may offer additional tuning parameters. |
46 | 44 |
/// |
47 | 45 |
///\sa Tolerance<float> |
48 | 46 |
///\sa Tolerance<double> |
49 | 47 |
///\sa Tolerance<long double> |
50 | 48 |
///\sa Tolerance<int> |
51 | 49 |
///\sa Tolerance<long long int> |
52 | 50 |
///\sa Tolerance<unsigned int> |
53 | 51 |
///\sa Tolerance<unsigned long long int> |
54 | 52 |
|
55 | 53 |
template<class T> |
56 | 54 |
class Tolerance |
57 | 55 |
{ |
58 | 56 |
public: |
59 | 57 |
typedef T Value; |
60 | 58 |
|
61 | 59 |
///\name Comparisons |
62 | 60 |
///The concept is that these bool functions return \c true only if |
63 | 61 |
///the related comparisons hold even if some numerical error appeared |
64 | 62 |
///during the computations. |
65 | 63 |
|
66 | 64 |
///@{ |
67 | 65 |
|
68 | 66 |
///Returns \c true if \c a is \e surely strictly less than \c b |
69 | 67 |
static bool less(Value a,Value b) {return false;} |
70 | 68 |
///Returns \c true if \c a is \e surely different from \c b |
71 | 69 |
static bool different(Value a,Value b) {return false;} |
72 | 70 |
///Returns \c true if \c a is \e surely positive |
73 | 71 |
static bool positive(Value a) {return false;} |
74 | 72 |
///Returns \c true if \c a is \e surely negative |
75 | 73 |
static bool negative(Value a) {return false;} |
76 | 74 |
///Returns \c true if \c a is \e surely non-zero |
77 | 75 |
static bool nonZero(Value a) {return false;} |
78 | 76 |
|
79 | 77 |
///@} |
80 | 78 |
|
81 | 79 |
///Returns the zero value. |
82 | 80 |
static Value zero() {return T();} |
83 | 81 |
|
84 | 82 |
// static bool finite(Value a) {} |
85 | 83 |
// static Value big() {} |
86 | 84 |
// static Value negativeBig() {} |
87 | 85 |
}; |
88 | 86 |
|
89 | 87 |
|
90 | 88 |
///Float specialization of Tolerance. |
91 | 89 |
|
92 | 90 |
///Float specialization of Tolerance. |
93 | 91 |
///\sa Tolerance |
94 | 92 |
///\relates Tolerance |
95 | 93 |
template<> |
96 | 94 |
class Tolerance<float> |
97 | 95 |
{ |
98 | 96 |
static float def_epsilon; |
99 | 97 |
float _epsilon; |
100 | 98 |
public: |
101 | 99 |
///\e |
102 | 100 |
typedef float Value; |
103 | 101 |
|
104 | 102 |
///Constructor setting the epsilon tolerance to the default value. |
105 | 103 |
Tolerance() : _epsilon(def_epsilon) {} |
106 | 104 |
///Constructor setting the epsilon tolerance to the given value. |
107 | 105 |
Tolerance(float e) : _epsilon(e) {} |
108 | 106 |
|
109 | 107 |
///Returns the epsilon value. |
110 | 108 |
Value epsilon() const {return _epsilon;} |
111 | 109 |
///Sets the epsilon value. |
112 | 110 |
void epsilon(Value e) {_epsilon=e;} |
113 | 111 |
|
114 | 112 |
///Returns the default epsilon value. |
115 | 113 |
static Value defaultEpsilon() {return def_epsilon;} |
116 | 114 |
///Sets the default epsilon value. |
117 | 115 |
static void defaultEpsilon(Value e) {def_epsilon=e;} |
118 | 116 |
|
119 | 117 |
///\name Comparisons |
120 | 118 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
121 | 119 |
|
122 | 120 |
///@{ |
123 | 121 |
|
124 | 122 |
///Returns \c true if \c a is \e surely strictly less than \c b |
125 | 123 |
bool less(Value a,Value b) const {return a+_epsilon<b;} |
126 | 124 |
///Returns \c true if \c a is \e surely different from \c b |
127 | 125 |
bool different(Value a,Value b) const { return less(a,b)||less(b,a); } |
128 | 126 |
///Returns \c true if \c a is \e surely positive |
129 | 127 |
bool positive(Value a) const { return _epsilon<a; } |
130 | 128 |
///Returns \c true if \c a is \e surely negative |
131 | 129 |
bool negative(Value a) const { return -_epsilon>a; } |
132 | 130 |
///Returns \c true if \c a is \e surely non-zero |
133 | 131 |
bool nonZero(Value a) const { return positive(a)||negative(a); } |
134 | 132 |
|
135 | 133 |
///@} |
136 | 134 |
|
137 | 135 |
///Returns zero |
138 | 136 |
static Value zero() {return 0;} |
139 | 137 |
}; |
140 | 138 |
|
141 | 139 |
///Double specialization of Tolerance. |
142 | 140 |
|
143 | 141 |
///Double specialization of Tolerance. |
144 | 142 |
///\sa Tolerance |
145 | 143 |
///\relates Tolerance |
146 | 144 |
template<> |
147 | 145 |
class Tolerance<double> |
148 | 146 |
{ |
149 | 147 |
static double def_epsilon; |
150 | 148 |
double _epsilon; |
151 | 149 |
public: |
152 | 150 |
///\e |
153 | 151 |
typedef double Value; |
154 | 152 |
|
155 | 153 |
///Constructor setting the epsilon tolerance to the default value. |
156 | 154 |
Tolerance() : _epsilon(def_epsilon) {} |
157 | 155 |
///Constructor setting the epsilon tolerance to the given value. |
158 | 156 |
Tolerance(double e) : _epsilon(e) {} |
159 | 157 |
|
160 | 158 |
///Returns the epsilon value. |
161 | 159 |
Value epsilon() const {return _epsilon;} |
162 | 160 |
///Sets the epsilon value. |
163 | 161 |
void epsilon(Value e) {_epsilon=e;} |
164 | 162 |
|
165 | 163 |
///Returns the default epsilon value. |
166 | 164 |
static Value defaultEpsilon() {return def_epsilon;} |
167 | 165 |
///Sets the default epsilon value. |
168 | 166 |
static void defaultEpsilon(Value e) {def_epsilon=e;} |
169 | 167 |
|
170 | 168 |
///\name Comparisons |
171 | 169 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
172 | 170 |
|
173 | 171 |
///@{ |
174 | 172 |
|
175 | 173 |
///Returns \c true if \c a is \e surely strictly less than \c b |
176 | 174 |
bool less(Value a,Value b) const {return a+_epsilon<b;} |
177 | 175 |
///Returns \c true if \c a is \e surely different from \c b |
178 | 176 |
bool different(Value a,Value b) const { return less(a,b)||less(b,a); } |
179 | 177 |
///Returns \c true if \c a is \e surely positive |
180 | 178 |
bool positive(Value a) const { return _epsilon<a; } |
181 | 179 |
///Returns \c true if \c a is \e surely negative |
182 | 180 |
bool negative(Value a) const { return -_epsilon>a; } |
183 | 181 |
///Returns \c true if \c a is \e surely non-zero |
184 | 182 |
bool nonZero(Value a) const { return positive(a)||negative(a); } |
185 | 183 |
|
186 | 184 |
///@} |
187 | 185 |
|
188 | 186 |
///Returns zero |
189 | 187 |
static Value zero() {return 0;} |
190 | 188 |
}; |
191 | 189 |
|
192 | 190 |
///Long double specialization of Tolerance. |
193 | 191 |
|
194 | 192 |
///Long double specialization of Tolerance. |
195 | 193 |
///\sa Tolerance |
196 | 194 |
///\relates Tolerance |
197 | 195 |
template<> |
198 | 196 |
class Tolerance<long double> |
199 | 197 |
{ |
200 | 198 |
static long double def_epsilon; |
201 | 199 |
long double _epsilon; |
202 | 200 |
public: |
203 | 201 |
///\e |
204 | 202 |
typedef long double Value; |
205 | 203 |
|
206 | 204 |
///Constructor setting the epsilon tolerance to the default value. |
207 | 205 |
Tolerance() : _epsilon(def_epsilon) {} |
208 | 206 |
///Constructor setting the epsilon tolerance to the given value. |
209 | 207 |
Tolerance(long double e) : _epsilon(e) {} |
210 | 208 |
|
211 | 209 |
///Returns the epsilon value. |
212 | 210 |
Value epsilon() const {return _epsilon;} |
213 | 211 |
///Sets the epsilon value. |
214 | 212 |
void epsilon(Value e) {_epsilon=e;} |
215 | 213 |
|
216 | 214 |
///Returns the default epsilon value. |
217 | 215 |
static Value defaultEpsilon() {return def_epsilon;} |
218 | 216 |
///Sets the default epsilon value. |
219 | 217 |
static void defaultEpsilon(Value e) {def_epsilon=e;} |
220 | 218 |
|
221 | 219 |
///\name Comparisons |
222 | 220 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
223 | 221 |
|
224 | 222 |
///@{ |
225 | 223 |
|
226 | 224 |
///Returns \c true if \c a is \e surely strictly less than \c b |
227 | 225 |
bool less(Value a,Value b) const {return a+_epsilon<b;} |
228 | 226 |
///Returns \c true if \c a is \e surely different from \c b |
229 | 227 |
bool different(Value a,Value b) const { return less(a,b)||less(b,a); } |
230 | 228 |
///Returns \c true if \c a is \e surely positive |
231 | 229 |
bool positive(Value a) const { return _epsilon<a; } |
232 | 230 |
///Returns \c true if \c a is \e surely negative |
233 | 231 |
bool negative(Value a) const { return -_epsilon>a; } |
234 | 232 |
///Returns \c true if \c a is \e surely non-zero |
235 | 233 |
bool nonZero(Value a) const { return positive(a)||negative(a); } |
236 | 234 |
|
237 | 235 |
///@} |
238 | 236 |
|
239 | 237 |
///Returns zero |
240 | 238 |
static Value zero() {return 0;} |
241 | 239 |
}; |
242 | 240 |
|
243 | 241 |
///Integer specialization of Tolerance. |
244 | 242 |
|
245 | 243 |
///Integer specialization of Tolerance. |
246 | 244 |
///\sa Tolerance |
247 | 245 |
template<> |
248 | 246 |
class Tolerance<int> |
249 | 247 |
{ |
250 | 248 |
public: |
251 | 249 |
///\e |
252 | 250 |
typedef int Value; |
253 | 251 |
|
254 | 252 |
///\name Comparisons |
255 | 253 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
256 | 254 |
|
257 | 255 |
///@{ |
258 | 256 |
|
259 | 257 |
///Returns \c true if \c a is \e surely strictly less than \c b |
260 | 258 |
static bool less(Value a,Value b) { return a<b;} |
261 | 259 |
///Returns \c true if \c a is \e surely different from \c b |
262 | 260 |
static bool different(Value a,Value b) { return a!=b; } |
263 | 261 |
///Returns \c true if \c a is \e surely positive |
264 | 262 |
static bool positive(Value a) { return 0<a; } |
265 | 263 |
///Returns \c true if \c a is \e surely negative |
266 | 264 |
static bool negative(Value a) { return 0>a; } |
267 | 265 |
///Returns \c true if \c a is \e surely non-zero |
268 | 266 |
static bool nonZero(Value a) { return a!=0; } |
269 | 267 |
|
270 | 268 |
///@} |
271 | 269 |
|
272 | 270 |
///Returns zero |
273 | 271 |
static Value zero() {return 0;} |
274 | 272 |
}; |
275 | 273 |
|
276 | 274 |
///Unsigned integer specialization of Tolerance. |
277 | 275 |
|
278 | 276 |
///Unsigned integer specialization of Tolerance. |
279 | 277 |
///\sa Tolerance |
280 | 278 |
template<> |
281 | 279 |
class Tolerance<unsigned int> |
282 | 280 |
{ |
283 | 281 |
public: |
284 | 282 |
///\e |
285 | 283 |
typedef unsigned int Value; |
286 | 284 |
|
287 | 285 |
///\name Comparisons |
288 | 286 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
289 | 287 |
|
290 | 288 |
///@{ |
291 | 289 |
|
292 | 290 |
///Returns \c true if \c a is \e surely strictly less than \c b |
293 | 291 |
static bool less(Value a,Value b) { return a<b;} |
294 | 292 |
///Returns \c true if \c a is \e surely different from \c b |
295 | 293 |
static bool different(Value a,Value b) { return a!=b; } |
296 | 294 |
///Returns \c true if \c a is \e surely positive |
297 | 295 |
static bool positive(Value a) { return 0<a; } |
298 | 296 |
///Returns \c true if \c a is \e surely negative |
299 | 297 |
static bool negative(Value) { return false; } |
300 | 298 |
///Returns \c true if \c a is \e surely non-zero |
301 | 299 |
static bool nonZero(Value a) { return a!=0; } |
302 | 300 |
|
303 | 301 |
///@} |
304 | 302 |
|
305 | 303 |
///Returns zero |
306 | 304 |
static Value zero() {return 0;} |
307 | 305 |
}; |
308 | 306 |
|
309 | 307 |
|
310 | 308 |
///Long integer specialization of Tolerance. |
311 | 309 |
|
312 | 310 |
///Long integer specialization of Tolerance. |
313 | 311 |
///\sa Tolerance |
314 | 312 |
template<> |
315 | 313 |
class Tolerance<long int> |
316 | 314 |
{ |
317 | 315 |
public: |
318 | 316 |
///\e |
319 | 317 |
typedef long int Value; |
320 | 318 |
|
321 | 319 |
///\name Comparisons |
322 | 320 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
323 | 321 |
|
324 | 322 |
///@{ |
325 | 323 |
|
326 | 324 |
///Returns \c true if \c a is \e surely strictly less than \c b |
327 | 325 |
static bool less(Value a,Value b) { return a<b;} |
328 | 326 |
///Returns \c true if \c a is \e surely different from \c b |
329 | 327 |
static bool different(Value a,Value b) { return a!=b; } |
330 | 328 |
///Returns \c true if \c a is \e surely positive |
331 | 329 |
static bool positive(Value a) { return 0<a; } |
332 | 330 |
///Returns \c true if \c a is \e surely negative |
333 | 331 |
static bool negative(Value a) { return 0>a; } |
334 | 332 |
///Returns \c true if \c a is \e surely non-zero |
335 | 333 |
static bool nonZero(Value a) { return a!=0;} |
336 | 334 |
|
337 | 335 |
///@} |
338 | 336 |
|
339 | 337 |
///Returns zero |
340 | 338 |
static Value zero() {return 0;} |
341 | 339 |
}; |
342 | 340 |
|
343 | 341 |
///Unsigned long integer specialization of Tolerance. |
344 | 342 |
|
345 | 343 |
///Unsigned long integer specialization of Tolerance. |
346 | 344 |
///\sa Tolerance |
347 | 345 |
template<> |
348 | 346 |
class Tolerance<unsigned long int> |
349 | 347 |
{ |
350 | 348 |
public: |
351 | 349 |
///\e |
352 | 350 |
typedef unsigned long int Value; |
353 | 351 |
|
354 | 352 |
///\name Comparisons |
355 | 353 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
356 | 354 |
|
357 | 355 |
///@{ |
358 | 356 |
|
359 | 357 |
///Returns \c true if \c a is \e surely strictly less than \c b |
360 | 358 |
static bool less(Value a,Value b) { return a<b;} |
361 | 359 |
///Returns \c true if \c a is \e surely different from \c b |
362 | 360 |
static bool different(Value a,Value b) { return a!=b; } |
363 | 361 |
///Returns \c true if \c a is \e surely positive |
364 | 362 |
static bool positive(Value a) { return 0<a; } |
365 | 363 |
///Returns \c true if \c a is \e surely negative |
366 | 364 |
static bool negative(Value) { return false; } |
367 | 365 |
///Returns \c true if \c a is \e surely non-zero |
368 | 366 |
static bool nonZero(Value a) { return a!=0;} |
369 | 367 |
|
370 | 368 |
///@} |
371 | 369 |
|
372 | 370 |
///Returns zero |
373 | 371 |
static Value zero() {return 0;} |
374 | 372 |
}; |
375 | 373 |
|
376 | 374 |
#if defined __GNUC__ && !defined __STRICT_ANSI__ |
377 | 375 |
|
378 | 376 |
///Long long integer specialization of Tolerance. |
379 | 377 |
|
380 | 378 |
///Long long integer specialization of Tolerance. |
381 | 379 |
///\warning This class (more exactly, type <tt>long long</tt>) |
382 | 380 |
///is not ansi compatible. |
383 | 381 |
///\sa Tolerance |
384 | 382 |
template<> |
385 | 383 |
class Tolerance<long long int> |
386 | 384 |
{ |
387 | 385 |
public: |
388 | 386 |
///\e |
389 | 387 |
typedef long long int Value; |
390 | 388 |
|
391 | 389 |
///\name Comparisons |
392 | 390 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
393 | 391 |
|
394 | 392 |
///@{ |
395 | 393 |
|
396 | 394 |
///Returns \c true if \c a is \e surely strictly less than \c b |
397 | 395 |
static bool less(Value a,Value b) { return a<b;} |
398 | 396 |
///Returns \c true if \c a is \e surely different from \c b |
399 | 397 |
static bool different(Value a,Value b) { return a!=b; } |
400 | 398 |
///Returns \c true if \c a is \e surely positive |
401 | 399 |
static bool positive(Value a) { return 0<a; } |
402 | 400 |
///Returns \c true if \c a is \e surely negative |
403 | 401 |
static bool negative(Value a) { return 0>a; } |
404 | 402 |
///Returns \c true if \c a is \e surely non-zero |
405 | 403 |
static bool nonZero(Value a) { return a!=0;} |
406 | 404 |
|
407 | 405 |
///@} |
408 | 406 |
|
409 | 407 |
///Returns zero |
410 | 408 |
static Value zero() {return 0;} |
411 | 409 |
}; |
412 | 410 |
|
413 | 411 |
///Unsigned long long integer specialization of Tolerance. |
414 | 412 |
|
415 | 413 |
///Unsigned long long integer specialization of Tolerance. |
416 | 414 |
///\warning This class (more exactly, type <tt>unsigned long long</tt>) |
417 | 415 |
///is not ansi compatible. |
418 | 416 |
///\sa Tolerance |
419 | 417 |
template<> |
420 | 418 |
class Tolerance<unsigned long long int> |
421 | 419 |
{ |
422 | 420 |
public: |
423 | 421 |
///\e |
424 | 422 |
typedef unsigned long long int Value; |
425 | 423 |
|
426 | 424 |
///\name Comparisons |
427 | 425 |
///See \ref lemon::Tolerance "Tolerance" for more details. |
428 | 426 |
|
429 | 427 |
///@{ |
430 | 428 |
|
431 | 429 |
///Returns \c true if \c a is \e surely strictly less than \c b |
432 | 430 |
static bool less(Value a,Value b) { return a<b;} |
433 | 431 |
///Returns \c true if \c a is \e surely different from \c b |
434 | 432 |
static bool different(Value a,Value b) { return a!=b; } |
435 | 433 |
///Returns \c true if \c a is \e surely positive |
436 | 434 |
static bool positive(Value a) { return 0<a; } |
437 | 435 |
///Returns \c true if \c a is \e surely negative |
438 | 436 |
static bool negative(Value) { return false; } |
439 | 437 |
///Returns \c true if \c a is \e surely non-zero |
440 | 438 |
static bool nonZero(Value a) { return a!=0;} |
441 | 439 |
|
442 | 440 |
///@} |
443 | 441 |
|
444 | 442 |
///Returns zero |
445 | 443 |
static Value zero() {return 0;} |
446 | 444 |
}; |
447 | 445 |
|
448 | 446 |
#endif |
449 | 447 |
|
450 | 448 |
/// @} |
451 | 449 |
|
452 | 450 |
} //namespace lemon |
453 | 451 |
|
454 | 452 |
#endif //LEMON_TOLERANCE_H |
0 comments (0 inline)