gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Better return type for cycleLength() functions (#179) in the min mean cycle algorithms. The original Value type is used instead of the LargeValue type, which is introduced for internal computations.
0 3 0
default
3 files changed with 6 insertions and 6 deletions:
↑ Collapse diff ↑
Ignore white space 6 line context
1 1
/* -*- C++ -*-
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_HARTMANN_ORLIN_H
20 20
#define LEMON_HARTMANN_ORLIN_H
21 21

	
22 22
/// \ingroup min_mean_cycle
23 23
///
24 24
/// \file
25 25
/// \brief Hartmann-Orlin's algorithm for finding a minimum mean cycle.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <lemon/core.h>
30 30
#include <lemon/path.h>
31 31
#include <lemon/tolerance.h>
32 32
#include <lemon/connectivity.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default traits class of HartmannOrlin algorithm.
37 37
  ///
38 38
  /// Default traits class of HartmannOrlin algorithm.
39 39
  /// \tparam GR The type of the digraph.
40 40
  /// \tparam LEN The type of the length map.
41 41
  /// It must conform to the \ref concepts::Rea_data "Rea_data" concept.
42 42
#ifdef DOXYGEN
43 43
  template <typename GR, typename LEN>
44 44
#else
45 45
  template <typename GR, typename LEN,
46 46
    bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
47 47
#endif
48 48
  struct HartmannOrlinDefaultTraits
49 49
  {
50 50
    /// The type of the digraph
51 51
    typedef GR Digraph;
52 52
    /// The type of the length map
53 53
    typedef LEN LengthMap;
54 54
    /// The type of the arc lengths
55 55
    typedef typename LengthMap::Value Value;
56 56

	
57 57
    /// \brief The large value type used for internal computations
58 58
    ///
59 59
    /// The large value type used for internal computations.
60 60
    /// It is \c long \c long if the \c Value type is integer,
61 61
    /// otherwise it is \c double.
62 62
    /// \c Value must be convertible to \c LargeValue.
63 63
    typedef double LargeValue;
64 64

	
65 65
    /// The tolerance type used for internal computations
66 66
    typedef lemon::Tolerance<LargeValue> Tolerance;
67 67

	
68 68
    /// \brief The path type of the found cycles
69 69
    ///
70 70
    /// The path type of the found cycles.
71 71
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
72 72
    /// and it must have an \c addFront() function.
73 73
    typedef lemon::Path<Digraph> Path;
74 74
  };
75 75

	
76 76
  // Default traits class for integer value types
77 77
  template <typename GR, typename LEN>
78 78
  struct HartmannOrlinDefaultTraits<GR, LEN, true>
79 79
  {
80 80
    typedef GR Digraph;
81 81
    typedef LEN LengthMap;
82 82
    typedef typename LengthMap::Value Value;
83 83
#ifdef LEMON_HAVE_LONG_LONG
84 84
    typedef long long LargeValue;
85 85
#else
86 86
    typedef long LargeValue;
87 87
#endif
88 88
    typedef lemon::Tolerance<LargeValue> Tolerance;
89 89
    typedef lemon::Path<Digraph> Path;
90 90
  };
91 91

	
92 92

	
93 93
  /// \addtogroup min_mean_cycle
94 94
  /// @{
95 95

	
96 96
  /// \brief Implementation of the Hartmann-Orlin algorithm for finding
97 97
  /// a minimum mean cycle.
98 98
  ///
99 99
  /// This class implements the Hartmann-Orlin algorithm for finding
100 100
  /// a directed cycle of minimum mean length (cost) in a digraph
101 101
  /// \ref amo93networkflows, \ref dasdan98minmeancycle.
102 102
  /// It is an improved version of \ref Karp "Karp"'s original algorithm,
103 103
  /// it applies an efficient early termination scheme.
104 104
  /// It runs in time O(ne) and uses space O(n<sup>2</sup>+e).
105 105
  ///
106 106
  /// \tparam GR The type of the digraph the algorithm runs on.
107 107
  /// \tparam LEN The type of the length map. The default
108 108
  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
109 109
  /// \tparam TR The traits class that defines various types used by the
110 110
  /// algorithm. By default, it is \ref HartmannOrlinDefaultTraits
111 111
  /// "HartmannOrlinDefaultTraits<GR, LEN>".
112 112
  /// In most cases, this parameter should not be set directly,
113 113
  /// consider to use the named template parameters instead.
114 114
#ifdef DOXYGEN
115 115
  template <typename GR, typename LEN, typename TR>
116 116
#else
117 117
  template < typename GR,
118 118
             typename LEN = typename GR::template ArcMap<int>,
119 119
             typename TR = HartmannOrlinDefaultTraits<GR, LEN> >
120 120
#endif
121 121
  class HartmannOrlin
122 122
  {
123 123
  public:
124 124

	
125 125
    /// The type of the digraph
126 126
    typedef typename TR::Digraph Digraph;
127 127
    /// The type of the length map
128 128
    typedef typename TR::LengthMap LengthMap;
129 129
    /// The type of the arc lengths
130 130
    typedef typename TR::Value Value;
131 131

	
132 132
    /// \brief The large value type
133 133
    ///
134 134
    /// The large value type used for internal computations.
135 135
    /// By default, it is \c long \c long if the \c Value type is integer,
136 136
    /// otherwise it is \c double.
137 137
    typedef typename TR::LargeValue LargeValue;
138 138

	
139 139
    /// The tolerance type
140 140
    typedef typename TR::Tolerance Tolerance;
141 141

	
142 142
    /// \brief The path type of the found cycles
143 143
    ///
144 144
    /// The path type of the found cycles.
145 145
    /// Using the \ref HartmannOrlinDefaultTraits "default traits class",
146 146
    /// it is \ref lemon::Path "Path<Digraph>".
147 147
    typedef typename TR::Path Path;
148 148

	
149 149
    /// The \ref HartmannOrlinDefaultTraits "traits class" of the algorithm
150 150
    typedef TR Traits;
151 151

	
152 152
  private:
153 153

	
154 154
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
155 155

	
156 156
    // Data sturcture for path data
157 157
    struct PathData
158 158
    {
159 159
      LargeValue dist;
160 160
      Arc pred;
161 161
      PathData(LargeValue d, Arc p = INVALID) :
162 162
        dist(d), pred(p) {}
163 163
    };
164 164

	
165 165
    typedef typename Digraph::template NodeMap<std::vector<PathData> >
166 166
      PathDataNodeMap;
167 167

	
168 168
  private:
169 169

	
170 170
    // The digraph the algorithm runs on
171 171
    const Digraph &_gr;
172 172
    // The length of the arcs
173 173
    const LengthMap &_length;
174 174

	
175 175
    // Data for storing the strongly connected components
176 176
    int _comp_num;
177 177
    typename Digraph::template NodeMap<int> _comp;
178 178
    std::vector<std::vector<Node> > _comp_nodes;
179 179
    std::vector<Node>* _nodes;
180 180
    typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
181 181

	
182 182
    // Data for the found cycles
183 183
    bool _curr_found, _best_found;
184 184
    LargeValue _curr_length, _best_length;
185 185
    int _curr_size, _best_size;
186 186
    Node _curr_node, _best_node;
187 187
    int _curr_level, _best_level;
188 188

	
189 189
    Path *_cycle_path;
190 190
    bool _local_path;
191 191

	
192 192
    // Node map for storing path data
193 193
    PathDataNodeMap _data;
194 194
    // The processed nodes in the last round
195 195
    std::vector<Node> _process;
196 196

	
197 197
    Tolerance _tolerance;
198 198

	
199 199
    // Infinite constant
200 200
    const LargeValue INF;
201 201

	
202 202
  public:
203 203

	
204 204
    /// \name Named Template Parameters
205 205
    /// @{
206 206

	
207 207
    template <typename T>
208 208
    struct SetLargeValueTraits : public Traits {
209 209
      typedef T LargeValue;
210 210
      typedef lemon::Tolerance<T> Tolerance;
211 211
    };
212 212

	
213 213
    /// \brief \ref named-templ-param "Named parameter" for setting
214 214
    /// \c LargeValue type.
215 215
    ///
216 216
    /// \ref named-templ-param "Named parameter" for setting \c LargeValue
217 217
    /// type. It is used for internal computations in the algorithm.
218 218
    template <typename T>
219 219
    struct SetLargeValue
220 220
      : public HartmannOrlin<GR, LEN, SetLargeValueTraits<T> > {
221 221
      typedef HartmannOrlin<GR, LEN, SetLargeValueTraits<T> > Create;
222 222
    };
223 223

	
224 224
    template <typename T>
225 225
    struct SetPathTraits : public Traits {
226 226
      typedef T Path;
227 227
    };
228 228

	
229 229
    /// \brief \ref named-templ-param "Named parameter" for setting
230 230
    /// \c %Path type.
231 231
    ///
232 232
    /// \ref named-templ-param "Named parameter" for setting the \c %Path
233 233
    /// type of the found cycles.
234 234
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
235 235
    /// and it must have an \c addFront() function.
236 236
    template <typename T>
237 237
    struct SetPath
238 238
      : public HartmannOrlin<GR, LEN, SetPathTraits<T> > {
239 239
      typedef HartmannOrlin<GR, LEN, SetPathTraits<T> > Create;
240 240
    };
241 241

	
242 242
    /// @}
243 243

	
244 244
  public:
245 245

	
246 246
    /// \brief Constructor.
247 247
    ///
248 248
    /// The constructor of the class.
249 249
    ///
250 250
    /// \param digraph The digraph the algorithm runs on.
251 251
    /// \param length The lengths (costs) of the arcs.
252 252
    HartmannOrlin( const Digraph &digraph,
253 253
                   const LengthMap &length ) :
254 254
      _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
255 255
      _best_found(false), _best_length(0), _best_size(1),
256 256
      _cycle_path(NULL), _local_path(false), _data(digraph),
257 257
      INF(std::numeric_limits<LargeValue>::has_infinity ?
258 258
          std::numeric_limits<LargeValue>::infinity() :
259 259
          std::numeric_limits<LargeValue>::max())
260 260
    {}
261 261

	
262 262
    /// Destructor.
263 263
    ~HartmannOrlin() {
264 264
      if (_local_path) delete _cycle_path;
265 265
    }
266 266

	
267 267
    /// \brief Set the path structure for storing the found cycle.
268 268
    ///
269 269
    /// This function sets an external path structure for storing the
270 270
    /// found cycle.
271 271
    ///
272 272
    /// If you don't call this function before calling \ref run() or
273 273
    /// \ref findMinMean(), it will allocate a local \ref Path "path"
274 274
    /// structure. The destuctor deallocates this automatically
275 275
    /// allocated object, of course.
276 276
    ///
277 277
    /// \note The algorithm calls only the \ref lemon::Path::addFront()
278 278
    /// "addFront()" function of the given path structure.
279 279
    ///
280 280
    /// \return <tt>(*this)</tt>
281 281
    HartmannOrlin& cycle(Path &path) {
282 282
      if (_local_path) {
283 283
        delete _cycle_path;
284 284
        _local_path = false;
285 285
      }
286 286
      _cycle_path = &path;
287 287
      return *this;
288 288
    }
289 289

	
290 290
    /// \brief Set the tolerance used by the algorithm.
291 291
    ///
292 292
    /// This function sets the tolerance object used by the algorithm.
293 293
    ///
294 294
    /// \return <tt>(*this)</tt>
295 295
    HartmannOrlin& tolerance(const Tolerance& tolerance) {
296 296
      _tolerance = tolerance;
297 297
      return *this;
298 298
    }
299 299

	
300 300
    /// \brief Return a const reference to the tolerance.
301 301
    ///
302 302
    /// This function returns a const reference to the tolerance object
303 303
    /// used by the algorithm.
304 304
    const Tolerance& tolerance() const {
305 305
      return _tolerance;
306 306
    }
307 307

	
308 308
    /// \name Execution control
309 309
    /// The simplest way to execute the algorithm is to call the \ref run()
310 310
    /// function.\n
311 311
    /// If you only need the minimum mean length, you may call
312 312
    /// \ref findMinMean().
313 313

	
314 314
    /// @{
315 315

	
316 316
    /// \brief Run the algorithm.
317 317
    ///
318 318
    /// This function runs the algorithm.
319 319
    /// It can be called more than once (e.g. if the underlying digraph
320 320
    /// and/or the arc lengths have been modified).
321 321
    ///
322 322
    /// \return \c true if a directed cycle exists in the digraph.
323 323
    ///
324 324
    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
325 325
    /// \code
326 326
    ///   return mmc.findMinMean() && mmc.findCycle();
327 327
    /// \endcode
328 328
    bool run() {
329 329
      return findMinMean() && findCycle();
330 330
    }
331 331

	
332 332
    /// \brief Find the minimum cycle mean.
333 333
    ///
334 334
    /// This function finds the minimum mean length of the directed
335 335
    /// cycles in the digraph.
336 336
    ///
337 337
    /// \return \c true if a directed cycle exists in the digraph.
338 338
    bool findMinMean() {
339 339
      // Initialization and find strongly connected components
340 340
      init();
341 341
      findComponents();
342 342
      
343 343
      // Find the minimum cycle mean in the components
344 344
      for (int comp = 0; comp < _comp_num; ++comp) {
345 345
        if (!initComponent(comp)) continue;
346 346
        processRounds();
347 347
        
348 348
        // Update the best cycle (global minimum mean cycle)
349 349
        if ( _curr_found && (!_best_found || 
350 350
             _curr_length * _best_size < _best_length * _curr_size) ) {
351 351
          _best_found = true;
352 352
          _best_length = _curr_length;
353 353
          _best_size = _curr_size;
354 354
          _best_node = _curr_node;
355 355
          _best_level = _curr_level;
356 356
        }
357 357
      }
358 358
      return _best_found;
359 359
    }
360 360

	
361 361
    /// \brief Find a minimum mean directed cycle.
362 362
    ///
363 363
    /// This function finds a directed cycle of minimum mean length
364 364
    /// in the digraph using the data computed by findMinMean().
365 365
    ///
366 366
    /// \return \c true if a directed cycle exists in the digraph.
367 367
    ///
368 368
    /// \pre \ref findMinMean() must be called before using this function.
369 369
    bool findCycle() {
370 370
      if (!_best_found) return false;
371 371
      IntNodeMap reached(_gr, -1);
372 372
      int r = _best_level + 1;
373 373
      Node u = _best_node;
374 374
      while (reached[u] < 0) {
375 375
        reached[u] = --r;
376 376
        u = _gr.source(_data[u][r].pred);
377 377
      }
378 378
      r = reached[u];
379 379
      Arc e = _data[u][r].pred;
380 380
      _cycle_path->addFront(e);
381 381
      _best_length = _length[e];
382 382
      _best_size = 1;
383 383
      Node v;
384 384
      while ((v = _gr.source(e)) != u) {
385 385
        e = _data[v][--r].pred;
386 386
        _cycle_path->addFront(e);
387 387
        _best_length += _length[e];
388 388
        ++_best_size;
389 389
      }
390 390
      return true;
391 391
    }
392 392

	
393 393
    /// @}
394 394

	
395 395
    /// \name Query Functions
396 396
    /// The results of the algorithm can be obtained using these
397 397
    /// functions.\n
398 398
    /// The algorithm should be executed before using them.
399 399

	
400 400
    /// @{
401 401

	
402 402
    /// \brief Return the total length of the found cycle.
403 403
    ///
404 404
    /// This function returns the total length of the found cycle.
405 405
    ///
406 406
    /// \pre \ref run() or \ref findMinMean() must be called before
407 407
    /// using this function.
408
    LargeValue cycleLength() const {
409
      return _best_length;
408
    Value cycleLength() const {
409
      return static_cast<Value>(_best_length);
410 410
    }
411 411

	
412 412
    /// \brief Return the number of arcs on the found cycle.
413 413
    ///
414 414
    /// This function returns the number of arcs on the found cycle.
415 415
    ///
416 416
    /// \pre \ref run() or \ref findMinMean() must be called before
417 417
    /// using this function.
418 418
    int cycleArcNum() const {
419 419
      return _best_size;
420 420
    }
421 421

	
422 422
    /// \brief Return the mean length of the found cycle.
423 423
    ///
424 424
    /// This function returns the mean length of the found cycle.
425 425
    ///
426 426
    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
427 427
    /// following code.
428 428
    /// \code
429 429
    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
430 430
    /// \endcode
431 431
    ///
432 432
    /// \pre \ref run() or \ref findMinMean() must be called before
433 433
    /// using this function.
434 434
    double cycleMean() const {
435 435
      return static_cast<double>(_best_length) / _best_size;
436 436
    }
437 437

	
438 438
    /// \brief Return the found cycle.
439 439
    ///
440 440
    /// This function returns a const reference to the path structure
441 441
    /// storing the found cycle.
442 442
    ///
443 443
    /// \pre \ref run() or \ref findCycle() must be called before using
444 444
    /// this function.
445 445
    const Path& cycle() const {
446 446
      return *_cycle_path;
447 447
    }
448 448

	
449 449
    ///@}
450 450

	
451 451
  private:
452 452

	
453 453
    // Initialization
454 454
    void init() {
455 455
      if (!_cycle_path) {
456 456
        _local_path = true;
457 457
        _cycle_path = new Path;
458 458
      }
459 459
      _cycle_path->clear();
460 460
      _best_found = false;
461 461
      _best_length = 0;
462 462
      _best_size = 1;
463 463
      _cycle_path->clear();
464 464
      for (NodeIt u(_gr); u != INVALID; ++u)
465 465
        _data[u].clear();
466 466
    }
467 467

	
468 468
    // Find strongly connected components and initialize _comp_nodes
469 469
    // and _out_arcs
470 470
    void findComponents() {
471 471
      _comp_num = stronglyConnectedComponents(_gr, _comp);
472 472
      _comp_nodes.resize(_comp_num);
473 473
      if (_comp_num == 1) {
474 474
        _comp_nodes[0].clear();
475 475
        for (NodeIt n(_gr); n != INVALID; ++n) {
476 476
          _comp_nodes[0].push_back(n);
477 477
          _out_arcs[n].clear();
478 478
          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
479 479
            _out_arcs[n].push_back(a);
480 480
          }
481 481
        }
482 482
      } else {
483 483
        for (int i = 0; i < _comp_num; ++i)
484 484
          _comp_nodes[i].clear();
485 485
        for (NodeIt n(_gr); n != INVALID; ++n) {
486 486
          int k = _comp[n];
487 487
          _comp_nodes[k].push_back(n);
488 488
          _out_arcs[n].clear();
489 489
          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
490 490
            if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
491 491
          }
492 492
        }
493 493
      }
494 494
    }
495 495

	
496 496
    // Initialize path data for the current component
497 497
    bool initComponent(int comp) {
498 498
      _nodes = &(_comp_nodes[comp]);
499 499
      int n = _nodes->size();
500 500
      if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
501 501
        return false;
502 502
      }      
503 503
      for (int i = 0; i < n; ++i) {
504 504
        _data[(*_nodes)[i]].resize(n + 1, PathData(INF));
505 505
      }
506 506
      return true;
507 507
    }
508 508

	
509 509
    // Process all rounds of computing path data for the current component.
510 510
    // _data[v][k] is the length of a shortest directed walk from the root
511 511
    // node to node v containing exactly k arcs.
512 512
    void processRounds() {
513 513
      Node start = (*_nodes)[0];
514 514
      _data[start][0] = PathData(0);
515 515
      _process.clear();
516 516
      _process.push_back(start);
517 517

	
518 518
      int k, n = _nodes->size();
519 519
      int next_check = 4;
520 520
      bool terminate = false;
521 521
      for (k = 1; k <= n && int(_process.size()) < n && !terminate; ++k) {
522 522
        processNextBuildRound(k);
523 523
        if (k == next_check || k == n) {
524 524
          terminate = checkTermination(k);
525 525
          next_check = next_check * 3 / 2;
526 526
        }
527 527
      }
528 528
      for ( ; k <= n && !terminate; ++k) {
529 529
        processNextFullRound(k);
530 530
        if (k == next_check || k == n) {
531 531
          terminate = checkTermination(k);
532 532
          next_check = next_check * 3 / 2;
533 533
        }
534 534
      }
535 535
    }
536 536

	
537 537
    // Process one round and rebuild _process
538 538
    void processNextBuildRound(int k) {
539 539
      std::vector<Node> next;
540 540
      Node u, v;
541 541
      Arc e;
542 542
      LargeValue d;
543 543
      for (int i = 0; i < int(_process.size()); ++i) {
544 544
        u = _process[i];
545 545
        for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
546 546
          e = _out_arcs[u][j];
547 547
          v = _gr.target(e);
548 548
          d = _data[u][k-1].dist + _length[e];
549 549
          if (_tolerance.less(d, _data[v][k].dist)) {
550 550
            if (_data[v][k].dist == INF) next.push_back(v);
551 551
            _data[v][k] = PathData(d, e);
552 552
          }
553 553
        }
554 554
      }
555 555
      _process.swap(next);
556 556
    }
557 557

	
558 558
    // Process one round using _nodes instead of _process
559 559
    void processNextFullRound(int k) {
560 560
      Node u, v;
561 561
      Arc e;
562 562
      LargeValue d;
563 563
      for (int i = 0; i < int(_nodes->size()); ++i) {
564 564
        u = (*_nodes)[i];
565 565
        for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
566 566
          e = _out_arcs[u][j];
567 567
          v = _gr.target(e);
568 568
          d = _data[u][k-1].dist + _length[e];
569 569
          if (_tolerance.less(d, _data[v][k].dist)) {
570 570
            _data[v][k] = PathData(d, e);
571 571
          }
572 572
        }
573 573
      }
574 574
    }
575 575
    
576 576
    // Check early termination
577 577
    bool checkTermination(int k) {
578 578
      typedef std::pair<int, int> Pair;
579 579
      typename GR::template NodeMap<Pair> level(_gr, Pair(-1, 0));
580 580
      typename GR::template NodeMap<LargeValue> pi(_gr);
581 581
      int n = _nodes->size();
582 582
      LargeValue length;
583 583
      int size;
584 584
      Node u;
585 585
      
586 586
      // Search for cycles that are already found
587 587
      _curr_found = false;
588 588
      for (int i = 0; i < n; ++i) {
589 589
        u = (*_nodes)[i];
590 590
        if (_data[u][k].dist == INF) continue;
591 591
        for (int j = k; j >= 0; --j) {
592 592
          if (level[u].first == i && level[u].second > 0) {
593 593
            // A cycle is found
594 594
            length = _data[u][level[u].second].dist - _data[u][j].dist;
595 595
            size = level[u].second - j;
596 596
            if (!_curr_found || length * _curr_size < _curr_length * size) {
597 597
              _curr_length = length;
598 598
              _curr_size = size;
599 599
              _curr_node = u;
600 600
              _curr_level = level[u].second;
601 601
              _curr_found = true;
602 602
            }
603 603
          }
604 604
          level[u] = Pair(i, j);
605 605
          if (j != 0) {
606 606
	    u = _gr.source(_data[u][j].pred);
607 607
	  }
608 608
        }
609 609
      }
610 610

	
611 611
      // If at least one cycle is found, check the optimality condition
612 612
      LargeValue d;
613 613
      if (_curr_found && k < n) {
614 614
        // Find node potentials
615 615
        for (int i = 0; i < n; ++i) {
616 616
          u = (*_nodes)[i];
617 617
          pi[u] = INF;
618 618
          for (int j = 0; j <= k; ++j) {
619 619
            if (_data[u][j].dist < INF) {
620 620
              d = _data[u][j].dist * _curr_size - j * _curr_length;
621 621
              if (_tolerance.less(d, pi[u])) pi[u] = d;
622 622
            }
623 623
          }
624 624
        }
625 625

	
626 626
        // Check the optimality condition for all arcs
627 627
        bool done = true;
628 628
        for (ArcIt a(_gr); a != INVALID; ++a) {
629 629
          if (_tolerance.less(_length[a] * _curr_size - _curr_length,
630 630
                              pi[_gr.target(a)] - pi[_gr.source(a)]) ) {
631 631
            done = false;
632 632
            break;
633 633
          }
634 634
        }
635 635
        return done;
636 636
      }
637 637
      return (k == n);
638 638
    }
639 639

	
640 640
  }; //class HartmannOrlin
641 641

	
642 642
  ///@}
643 643

	
644 644
} //namespace lemon
645 645

	
646 646
#endif //LEMON_HARTMANN_ORLIN_H
Ignore white space 524288 line context
1 1
/* -*- C++ -*-
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_HOWARD_H
20 20
#define LEMON_HOWARD_H
21 21

	
22 22
/// \ingroup min_mean_cycle
23 23
///
24 24
/// \file
25 25
/// \brief Howard's algorithm for finding a minimum mean cycle.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <lemon/core.h>
30 30
#include <lemon/path.h>
31 31
#include <lemon/tolerance.h>
32 32
#include <lemon/connectivity.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default traits class of Howard class.
37 37
  ///
38 38
  /// Default traits class of Howard class.
39 39
  /// \tparam GR The type of the digraph.
40 40
  /// \tparam LEN The type of the length map.
41 41
  /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
42 42
#ifdef DOXYGEN
43 43
  template <typename GR, typename LEN>
44 44
#else
45 45
  template <typename GR, typename LEN,
46 46
    bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
47 47
#endif
48 48
  struct HowardDefaultTraits
49 49
  {
50 50
    /// The type of the digraph
51 51
    typedef GR Digraph;
52 52
    /// The type of the length map
53 53
    typedef LEN LengthMap;
54 54
    /// The type of the arc lengths
55 55
    typedef typename LengthMap::Value Value;
56 56

	
57 57
    /// \brief The large value type used for internal computations
58 58
    ///
59 59
    /// The large value type used for internal computations.
60 60
    /// It is \c long \c long if the \c Value type is integer,
61 61
    /// otherwise it is \c double.
62 62
    /// \c Value must be convertible to \c LargeValue.
63 63
    typedef double LargeValue;
64 64

	
65 65
    /// The tolerance type used for internal computations
66 66
    typedef lemon::Tolerance<LargeValue> Tolerance;
67 67

	
68 68
    /// \brief The path type of the found cycles
69 69
    ///
70 70
    /// The path type of the found cycles.
71 71
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
72 72
    /// and it must have an \c addBack() function.
73 73
    typedef lemon::Path<Digraph> Path;
74 74
  };
75 75

	
76 76
  // Default traits class for integer value types
77 77
  template <typename GR, typename LEN>
78 78
  struct HowardDefaultTraits<GR, LEN, true>
79 79
  {
80 80
    typedef GR Digraph;
81 81
    typedef LEN LengthMap;
82 82
    typedef typename LengthMap::Value Value;
83 83
#ifdef LEMON_HAVE_LONG_LONG
84 84
    typedef long long LargeValue;
85 85
#else
86 86
    typedef long LargeValue;
87 87
#endif
88 88
    typedef lemon::Tolerance<LargeValue> Tolerance;
89 89
    typedef lemon::Path<Digraph> Path;
90 90
  };
91 91

	
92 92

	
93 93
  /// \addtogroup min_mean_cycle
94 94
  /// @{
95 95

	
96 96
  /// \brief Implementation of Howard's algorithm for finding a minimum
97 97
  /// mean cycle.
98 98
  ///
99 99
  /// This class implements Howard's policy iteration algorithm for finding
100 100
  /// a directed cycle of minimum mean length (cost) in a digraph
101 101
  /// \ref amo93networkflows, \ref dasdan98minmeancycle.
102 102
  /// This class provides the most efficient algorithm for the
103 103
  /// minimum mean cycle problem, though the best known theoretical
104 104
  /// bound on its running time is exponential.
105 105
  ///
106 106
  /// \tparam GR The type of the digraph the algorithm runs on.
107 107
  /// \tparam LEN The type of the length map. The default
108 108
  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
109 109
  /// \tparam TR The traits class that defines various types used by the
110 110
  /// algorithm. By default, it is \ref HowardDefaultTraits
111 111
  /// "HowardDefaultTraits<GR, LEN>".
112 112
  /// In most cases, this parameter should not be set directly,
113 113
  /// consider to use the named template parameters instead.
114 114
#ifdef DOXYGEN
115 115
  template <typename GR, typename LEN, typename TR>
116 116
#else
117 117
  template < typename GR,
118 118
             typename LEN = typename GR::template ArcMap<int>,
119 119
             typename TR = HowardDefaultTraits<GR, LEN> >
120 120
#endif
121 121
  class Howard
122 122
  {
123 123
  public:
124 124
  
125 125
    /// The type of the digraph
126 126
    typedef typename TR::Digraph Digraph;
127 127
    /// The type of the length map
128 128
    typedef typename TR::LengthMap LengthMap;
129 129
    /// The type of the arc lengths
130 130
    typedef typename TR::Value Value;
131 131

	
132 132
    /// \brief The large value type
133 133
    ///
134 134
    /// The large value type used for internal computations.
135 135
    /// By default, it is \c long \c long if the \c Value type is integer,
136 136
    /// otherwise it is \c double.
137 137
    typedef typename TR::LargeValue LargeValue;
138 138

	
139 139
    /// The tolerance type
140 140
    typedef typename TR::Tolerance Tolerance;
141 141

	
142 142
    /// \brief The path type of the found cycles
143 143
    ///
144 144
    /// The path type of the found cycles.
145 145
    /// Using the \ref HowardDefaultTraits "default traits class",
146 146
    /// it is \ref lemon::Path "Path<Digraph>".
147 147
    typedef typename TR::Path Path;
148 148

	
149 149
    /// The \ref HowardDefaultTraits "traits class" of the algorithm
150 150
    typedef TR Traits;
151 151

	
152 152
  private:
153 153

	
154 154
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
155 155
  
156 156
    // The digraph the algorithm runs on
157 157
    const Digraph &_gr;
158 158
    // The length of the arcs
159 159
    const LengthMap &_length;
160 160

	
161 161
    // Data for the found cycles
162 162
    bool _curr_found, _best_found;
163 163
    LargeValue _curr_length, _best_length;
164 164
    int _curr_size, _best_size;
165 165
    Node _curr_node, _best_node;
166 166

	
167 167
    Path *_cycle_path;
168 168
    bool _local_path;
169 169

	
170 170
    // Internal data used by the algorithm
171 171
    typename Digraph::template NodeMap<Arc> _policy;
172 172
    typename Digraph::template NodeMap<bool> _reached;
173 173
    typename Digraph::template NodeMap<int> _level;
174 174
    typename Digraph::template NodeMap<LargeValue> _dist;
175 175

	
176 176
    // Data for storing the strongly connected components
177 177
    int _comp_num;
178 178
    typename Digraph::template NodeMap<int> _comp;
179 179
    std::vector<std::vector<Node> > _comp_nodes;
180 180
    std::vector<Node>* _nodes;
181 181
    typename Digraph::template NodeMap<std::vector<Arc> > _in_arcs;
182 182
    
183 183
    // Queue used for BFS search
184 184
    std::vector<Node> _queue;
185 185
    int _qfront, _qback;
186 186

	
187 187
    Tolerance _tolerance;
188 188
  
189 189
    // Infinite constant
190 190
    const LargeValue INF;
191 191

	
192 192
  public:
193 193
  
194 194
    /// \name Named Template Parameters
195 195
    /// @{
196 196

	
197 197
    template <typename T>
198 198
    struct SetLargeValueTraits : public Traits {
199 199
      typedef T LargeValue;
200 200
      typedef lemon::Tolerance<T> Tolerance;
201 201
    };
202 202

	
203 203
    /// \brief \ref named-templ-param "Named parameter" for setting
204 204
    /// \c LargeValue type.
205 205
    ///
206 206
    /// \ref named-templ-param "Named parameter" for setting \c LargeValue
207 207
    /// type. It is used for internal computations in the algorithm.
208 208
    template <typename T>
209 209
    struct SetLargeValue
210 210
      : public Howard<GR, LEN, SetLargeValueTraits<T> > {
211 211
      typedef Howard<GR, LEN, SetLargeValueTraits<T> > Create;
212 212
    };
213 213

	
214 214
    template <typename T>
215 215
    struct SetPathTraits : public Traits {
216 216
      typedef T Path;
217 217
    };
218 218

	
219 219
    /// \brief \ref named-templ-param "Named parameter" for setting
220 220
    /// \c %Path type.
221 221
    ///
222 222
    /// \ref named-templ-param "Named parameter" for setting the \c %Path
223 223
    /// type of the found cycles.
224 224
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
225 225
    /// and it must have an \c addBack() function.
226 226
    template <typename T>
227 227
    struct SetPath
228 228
      : public Howard<GR, LEN, SetPathTraits<T> > {
229 229
      typedef Howard<GR, LEN, SetPathTraits<T> > Create;
230 230
    };
231 231
    
232 232
    /// @}
233 233

	
234 234
  public:
235 235

	
236 236
    /// \brief Constructor.
237 237
    ///
238 238
    /// The constructor of the class.
239 239
    ///
240 240
    /// \param digraph The digraph the algorithm runs on.
241 241
    /// \param length The lengths (costs) of the arcs.
242 242
    Howard( const Digraph &digraph,
243 243
            const LengthMap &length ) :
244 244
      _gr(digraph), _length(length), _best_found(false),
245 245
      _best_length(0), _best_size(1), _cycle_path(NULL), _local_path(false),
246 246
      _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
247 247
      _comp(digraph), _in_arcs(digraph),
248 248
      INF(std::numeric_limits<LargeValue>::has_infinity ?
249 249
          std::numeric_limits<LargeValue>::infinity() :
250 250
          std::numeric_limits<LargeValue>::max())
251 251
    {}
252 252

	
253 253
    /// Destructor.
254 254
    ~Howard() {
255 255
      if (_local_path) delete _cycle_path;
256 256
    }
257 257

	
258 258
    /// \brief Set the path structure for storing the found cycle.
259 259
    ///
260 260
    /// This function sets an external path structure for storing the
261 261
    /// found cycle.
262 262
    ///
263 263
    /// If you don't call this function before calling \ref run() or
264 264
    /// \ref findMinMean(), it will allocate a local \ref Path "path"
265 265
    /// structure. The destuctor deallocates this automatically
266 266
    /// allocated object, of course.
267 267
    ///
268 268
    /// \note The algorithm calls only the \ref lemon::Path::addBack()
269 269
    /// "addBack()" function of the given path structure.
270 270
    ///
271 271
    /// \return <tt>(*this)</tt>
272 272
    Howard& cycle(Path &path) {
273 273
      if (_local_path) {
274 274
        delete _cycle_path;
275 275
        _local_path = false;
276 276
      }
277 277
      _cycle_path = &path;
278 278
      return *this;
279 279
    }
280 280

	
281 281
    /// \brief Set the tolerance used by the algorithm.
282 282
    ///
283 283
    /// This function sets the tolerance object used by the algorithm.
284 284
    ///
285 285
    /// \return <tt>(*this)</tt>
286 286
    Howard& tolerance(const Tolerance& tolerance) {
287 287
      _tolerance = tolerance;
288 288
      return *this;
289 289
    }
290 290

	
291 291
    /// \brief Return a const reference to the tolerance.
292 292
    ///
293 293
    /// This function returns a const reference to the tolerance object
294 294
    /// used by the algorithm.
295 295
    const Tolerance& tolerance() const {
296 296
      return _tolerance;
297 297
    }
298 298

	
299 299
    /// \name Execution control
300 300
    /// The simplest way to execute the algorithm is to call the \ref run()
301 301
    /// function.\n
302 302
    /// If you only need the minimum mean length, you may call
303 303
    /// \ref findMinMean().
304 304

	
305 305
    /// @{
306 306

	
307 307
    /// \brief Run the algorithm.
308 308
    ///
309 309
    /// This function runs the algorithm.
310 310
    /// It can be called more than once (e.g. if the underlying digraph
311 311
    /// and/or the arc lengths have been modified).
312 312
    ///
313 313
    /// \return \c true if a directed cycle exists in the digraph.
314 314
    ///
315 315
    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
316 316
    /// \code
317 317
    ///   return mmc.findMinMean() && mmc.findCycle();
318 318
    /// \endcode
319 319
    bool run() {
320 320
      return findMinMean() && findCycle();
321 321
    }
322 322

	
323 323
    /// \brief Find the minimum cycle mean.
324 324
    ///
325 325
    /// This function finds the minimum mean length of the directed
326 326
    /// cycles in the digraph.
327 327
    ///
328 328
    /// \return \c true if a directed cycle exists in the digraph.
329 329
    bool findMinMean() {
330 330
      // Initialize and find strongly connected components
331 331
      init();
332 332
      findComponents();
333 333
      
334 334
      // Find the minimum cycle mean in the components
335 335
      for (int comp = 0; comp < _comp_num; ++comp) {
336 336
        // Find the minimum mean cycle in the current component
337 337
        if (!buildPolicyGraph(comp)) continue;
338 338
        while (true) {
339 339
          findPolicyCycle();
340 340
          if (!computeNodeDistances()) break;
341 341
        }
342 342
        // Update the best cycle (global minimum mean cycle)
343 343
        if ( _curr_found && (!_best_found ||
344 344
             _curr_length * _best_size < _best_length * _curr_size) ) {
345 345
          _best_found = true;
346 346
          _best_length = _curr_length;
347 347
          _best_size = _curr_size;
348 348
          _best_node = _curr_node;
349 349
        }
350 350
      }
351 351
      return _best_found;
352 352
    }
353 353

	
354 354
    /// \brief Find a minimum mean directed cycle.
355 355
    ///
356 356
    /// This function finds a directed cycle of minimum mean length
357 357
    /// in the digraph using the data computed by findMinMean().
358 358
    ///
359 359
    /// \return \c true if a directed cycle exists in the digraph.
360 360
    ///
361 361
    /// \pre \ref findMinMean() must be called before using this function.
362 362
    bool findCycle() {
363 363
      if (!_best_found) return false;
364 364
      _cycle_path->addBack(_policy[_best_node]);
365 365
      for ( Node v = _best_node;
366 366
            (v = _gr.target(_policy[v])) != _best_node; ) {
367 367
        _cycle_path->addBack(_policy[v]);
368 368
      }
369 369
      return true;
370 370
    }
371 371

	
372 372
    /// @}
373 373

	
374 374
    /// \name Query Functions
375 375
    /// The results of the algorithm can be obtained using these
376 376
    /// functions.\n
377 377
    /// The algorithm should be executed before using them.
378 378

	
379 379
    /// @{
380 380

	
381 381
    /// \brief Return the total length of the found cycle.
382 382
    ///
383 383
    /// This function returns the total length of the found cycle.
384 384
    ///
385 385
    /// \pre \ref run() or \ref findMinMean() must be called before
386 386
    /// using this function.
387
    LargeValue cycleLength() const {
388
      return _best_length;
387
    Value cycleLength() const {
388
      return static_cast<Value>(_best_length);
389 389
    }
390 390

	
391 391
    /// \brief Return the number of arcs on the found cycle.
392 392
    ///
393 393
    /// This function returns the number of arcs on the found cycle.
394 394
    ///
395 395
    /// \pre \ref run() or \ref findMinMean() must be called before
396 396
    /// using this function.
397 397
    int cycleArcNum() const {
398 398
      return _best_size;
399 399
    }
400 400

	
401 401
    /// \brief Return the mean length of the found cycle.
402 402
    ///
403 403
    /// This function returns the mean length of the found cycle.
404 404
    ///
405 405
    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
406 406
    /// following code.
407 407
    /// \code
408 408
    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
409 409
    /// \endcode
410 410
    ///
411 411
    /// \pre \ref run() or \ref findMinMean() must be called before
412 412
    /// using this function.
413 413
    double cycleMean() const {
414 414
      return static_cast<double>(_best_length) / _best_size;
415 415
    }
416 416

	
417 417
    /// \brief Return the found cycle.
418 418
    ///
419 419
    /// This function returns a const reference to the path structure
420 420
    /// storing the found cycle.
421 421
    ///
422 422
    /// \pre \ref run() or \ref findCycle() must be called before using
423 423
    /// this function.
424 424
    const Path& cycle() const {
425 425
      return *_cycle_path;
426 426
    }
427 427

	
428 428
    ///@}
429 429

	
430 430
  private:
431 431

	
432 432
    // Initialize
433 433
    void init() {
434 434
      if (!_cycle_path) {
435 435
        _local_path = true;
436 436
        _cycle_path = new Path;
437 437
      }
438 438
      _queue.resize(countNodes(_gr));
439 439
      _best_found = false;
440 440
      _best_length = 0;
441 441
      _best_size = 1;
442 442
      _cycle_path->clear();
443 443
    }
444 444
    
445 445
    // Find strongly connected components and initialize _comp_nodes
446 446
    // and _in_arcs
447 447
    void findComponents() {
448 448
      _comp_num = stronglyConnectedComponents(_gr, _comp);
449 449
      _comp_nodes.resize(_comp_num);
450 450
      if (_comp_num == 1) {
451 451
        _comp_nodes[0].clear();
452 452
        for (NodeIt n(_gr); n != INVALID; ++n) {
453 453
          _comp_nodes[0].push_back(n);
454 454
          _in_arcs[n].clear();
455 455
          for (InArcIt a(_gr, n); a != INVALID; ++a) {
456 456
            _in_arcs[n].push_back(a);
457 457
          }
458 458
        }
459 459
      } else {
460 460
        for (int i = 0; i < _comp_num; ++i)
461 461
          _comp_nodes[i].clear();
462 462
        for (NodeIt n(_gr); n != INVALID; ++n) {
463 463
          int k = _comp[n];
464 464
          _comp_nodes[k].push_back(n);
465 465
          _in_arcs[n].clear();
466 466
          for (InArcIt a(_gr, n); a != INVALID; ++a) {
467 467
            if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
468 468
          }
469 469
        }
470 470
      }
471 471
    }
472 472

	
473 473
    // Build the policy graph in the given strongly connected component
474 474
    // (the out-degree of every node is 1)
475 475
    bool buildPolicyGraph(int comp) {
476 476
      _nodes = &(_comp_nodes[comp]);
477 477
      if (_nodes->size() < 1 ||
478 478
          (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
479 479
        return false;
480 480
      }
481 481
      for (int i = 0; i < int(_nodes->size()); ++i) {
482 482
        _dist[(*_nodes)[i]] = INF;
483 483
      }
484 484
      Node u, v;
485 485
      Arc e;
486 486
      for (int i = 0; i < int(_nodes->size()); ++i) {
487 487
        v = (*_nodes)[i];
488 488
        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
489 489
          e = _in_arcs[v][j];
490 490
          u = _gr.source(e);
491 491
          if (_length[e] < _dist[u]) {
492 492
            _dist[u] = _length[e];
493 493
            _policy[u] = e;
494 494
          }
495 495
        }
496 496
      }
497 497
      return true;
498 498
    }
499 499

	
500 500
    // Find the minimum mean cycle in the policy graph
501 501
    void findPolicyCycle() {
502 502
      for (int i = 0; i < int(_nodes->size()); ++i) {
503 503
        _level[(*_nodes)[i]] = -1;
504 504
      }
505 505
      LargeValue clength;
506 506
      int csize;
507 507
      Node u, v;
508 508
      _curr_found = false;
509 509
      for (int i = 0; i < int(_nodes->size()); ++i) {
510 510
        u = (*_nodes)[i];
511 511
        if (_level[u] >= 0) continue;
512 512
        for (; _level[u] < 0; u = _gr.target(_policy[u])) {
513 513
          _level[u] = i;
514 514
        }
515 515
        if (_level[u] == i) {
516 516
          // A cycle is found
517 517
          clength = _length[_policy[u]];
518 518
          csize = 1;
519 519
          for (v = u; (v = _gr.target(_policy[v])) != u; ) {
520 520
            clength += _length[_policy[v]];
521 521
            ++csize;
522 522
          }
523 523
          if ( !_curr_found ||
524 524
               (clength * _curr_size < _curr_length * csize) ) {
525 525
            _curr_found = true;
526 526
            _curr_length = clength;
527 527
            _curr_size = csize;
528 528
            _curr_node = u;
529 529
          }
530 530
        }
531 531
      }
532 532
    }
533 533

	
534 534
    // Contract the policy graph and compute node distances
535 535
    bool computeNodeDistances() {
536 536
      // Find the component of the main cycle and compute node distances
537 537
      // using reverse BFS
538 538
      for (int i = 0; i < int(_nodes->size()); ++i) {
539 539
        _reached[(*_nodes)[i]] = false;
540 540
      }
541 541
      _qfront = _qback = 0;
542 542
      _queue[0] = _curr_node;
543 543
      _reached[_curr_node] = true;
544 544
      _dist[_curr_node] = 0;
545 545
      Node u, v;
546 546
      Arc e;
547 547
      while (_qfront <= _qback) {
548 548
        v = _queue[_qfront++];
549 549
        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
550 550
          e = _in_arcs[v][j];
551 551
          u = _gr.source(e);
552 552
          if (_policy[u] == e && !_reached[u]) {
553 553
            _reached[u] = true;
554 554
            _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
555 555
            _queue[++_qback] = u;
556 556
          }
557 557
        }
558 558
      }
559 559

	
560 560
      // Connect all other nodes to this component and compute node
561 561
      // distances using reverse BFS
562 562
      _qfront = 0;
563 563
      while (_qback < int(_nodes->size())-1) {
564 564
        v = _queue[_qfront++];
565 565
        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
566 566
          e = _in_arcs[v][j];
567 567
          u = _gr.source(e);
568 568
          if (!_reached[u]) {
569 569
            _reached[u] = true;
570 570
            _policy[u] = e;
571 571
            _dist[u] = _dist[v] + _length[e] * _curr_size - _curr_length;
572 572
            _queue[++_qback] = u;
573 573
          }
574 574
        }
575 575
      }
576 576

	
577 577
      // Improve node distances
578 578
      bool improved = false;
579 579
      for (int i = 0; i < int(_nodes->size()); ++i) {
580 580
        v = (*_nodes)[i];
581 581
        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
582 582
          e = _in_arcs[v][j];
583 583
          u = _gr.source(e);
584 584
          LargeValue delta = _dist[v] + _length[e] * _curr_size - _curr_length;
585 585
          if (_tolerance.less(delta, _dist[u])) {
586 586
            _dist[u] = delta;
587 587
            _policy[u] = e;
588 588
            improved = true;
589 589
          }
590 590
        }
591 591
      }
592 592
      return improved;
593 593
    }
594 594

	
595 595
  }; //class Howard
596 596

	
597 597
  ///@}
598 598

	
599 599
} //namespace lemon
600 600

	
601 601
#endif //LEMON_HOWARD_H
Ignore white space 6 line context
1 1
/* -*- C++ -*-
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_KARP_H
20 20
#define LEMON_KARP_H
21 21

	
22 22
/// \ingroup min_mean_cycle
23 23
///
24 24
/// \file
25 25
/// \brief Karp's algorithm for finding a minimum mean cycle.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <lemon/core.h>
30 30
#include <lemon/path.h>
31 31
#include <lemon/tolerance.h>
32 32
#include <lemon/connectivity.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default traits class of Karp algorithm.
37 37
  ///
38 38
  /// Default traits class of Karp algorithm.
39 39
  /// \tparam GR The type of the digraph.
40 40
  /// \tparam LEN The type of the length map.
41 41
  /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
42 42
#ifdef DOXYGEN
43 43
  template <typename GR, typename LEN>
44 44
#else
45 45
  template <typename GR, typename LEN,
46 46
    bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
47 47
#endif
48 48
  struct KarpDefaultTraits
49 49
  {
50 50
    /// The type of the digraph
51 51
    typedef GR Digraph;
52 52
    /// The type of the length map
53 53
    typedef LEN LengthMap;
54 54
    /// The type of the arc lengths
55 55
    typedef typename LengthMap::Value Value;
56 56

	
57 57
    /// \brief The large value type used for internal computations
58 58
    ///
59 59
    /// The large value type used for internal computations.
60 60
    /// It is \c long \c long if the \c Value type is integer,
61 61
    /// otherwise it is \c double.
62 62
    /// \c Value must be convertible to \c LargeValue.
63 63
    typedef double LargeValue;
64 64

	
65 65
    /// The tolerance type used for internal computations
66 66
    typedef lemon::Tolerance<LargeValue> Tolerance;
67 67

	
68 68
    /// \brief The path type of the found cycles
69 69
    ///
70 70
    /// The path type of the found cycles.
71 71
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
72 72
    /// and it must have an \c addFront() function.
73 73
    typedef lemon::Path<Digraph> Path;
74 74
  };
75 75

	
76 76
  // Default traits class for integer value types
77 77
  template <typename GR, typename LEN>
78 78
  struct KarpDefaultTraits<GR, LEN, true>
79 79
  {
80 80
    typedef GR Digraph;
81 81
    typedef LEN LengthMap;
82 82
    typedef typename LengthMap::Value Value;
83 83
#ifdef LEMON_HAVE_LONG_LONG
84 84
    typedef long long LargeValue;
85 85
#else
86 86
    typedef long LargeValue;
87 87
#endif
88 88
    typedef lemon::Tolerance<LargeValue> Tolerance;
89 89
    typedef lemon::Path<Digraph> Path;
90 90
  };
91 91

	
92 92

	
93 93
  /// \addtogroup min_mean_cycle
94 94
  /// @{
95 95

	
96 96
  /// \brief Implementation of Karp's algorithm for finding a minimum
97 97
  /// mean cycle.
98 98
  ///
99 99
  /// This class implements Karp's algorithm for finding a directed
100 100
  /// cycle of minimum mean length (cost) in a digraph
101 101
  /// \ref amo93networkflows, \ref dasdan98minmeancycle.
102 102
  /// It runs in time O(ne) and uses space O(n<sup>2</sup>+e).
103 103
  ///
104 104
  /// \tparam GR The type of the digraph the algorithm runs on.
105 105
  /// \tparam LEN The type of the length map. The default
106 106
  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
107 107
  /// \tparam TR The traits class that defines various types used by the
108 108
  /// algorithm. By default, it is \ref KarpDefaultTraits
109 109
  /// "KarpDefaultTraits<GR, LEN>".
110 110
  /// In most cases, this parameter should not be set directly,
111 111
  /// consider to use the named template parameters instead.
112 112
#ifdef DOXYGEN
113 113
  template <typename GR, typename LEN, typename TR>
114 114
#else
115 115
  template < typename GR,
116 116
             typename LEN = typename GR::template ArcMap<int>,
117 117
             typename TR = KarpDefaultTraits<GR, LEN> >
118 118
#endif
119 119
  class Karp
120 120
  {
121 121
  public:
122 122

	
123 123
    /// The type of the digraph
124 124
    typedef typename TR::Digraph Digraph;
125 125
    /// The type of the length map
126 126
    typedef typename TR::LengthMap LengthMap;
127 127
    /// The type of the arc lengths
128 128
    typedef typename TR::Value Value;
129 129

	
130 130
    /// \brief The large value type
131 131
    ///
132 132
    /// The large value type used for internal computations.
133 133
    /// By default, it is \c long \c long if the \c Value type is integer,
134 134
    /// otherwise it is \c double.
135 135
    typedef typename TR::LargeValue LargeValue;
136 136

	
137 137
    /// The tolerance type
138 138
    typedef typename TR::Tolerance Tolerance;
139 139

	
140 140
    /// \brief The path type of the found cycles
141 141
    ///
142 142
    /// The path type of the found cycles.
143 143
    /// Using the \ref KarpDefaultTraits "default traits class",
144 144
    /// it is \ref lemon::Path "Path<Digraph>".
145 145
    typedef typename TR::Path Path;
146 146

	
147 147
    /// The \ref KarpDefaultTraits "traits class" of the algorithm
148 148
    typedef TR Traits;
149 149

	
150 150
  private:
151 151

	
152 152
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
153 153

	
154 154
    // Data sturcture for path data
155 155
    struct PathData
156 156
    {
157 157
      LargeValue dist;
158 158
      Arc pred;
159 159
      PathData(LargeValue d, Arc p = INVALID) :
160 160
        dist(d), pred(p) {}
161 161
    };
162 162

	
163 163
    typedef typename Digraph::template NodeMap<std::vector<PathData> >
164 164
      PathDataNodeMap;
165 165

	
166 166
  private:
167 167

	
168 168
    // The digraph the algorithm runs on
169 169
    const Digraph &_gr;
170 170
    // The length of the arcs
171 171
    const LengthMap &_length;
172 172

	
173 173
    // Data for storing the strongly connected components
174 174
    int _comp_num;
175 175
    typename Digraph::template NodeMap<int> _comp;
176 176
    std::vector<std::vector<Node> > _comp_nodes;
177 177
    std::vector<Node>* _nodes;
178 178
    typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
179 179

	
180 180
    // Data for the found cycle
181 181
    LargeValue _cycle_length;
182 182
    int _cycle_size;
183 183
    Node _cycle_node;
184 184

	
185 185
    Path *_cycle_path;
186 186
    bool _local_path;
187 187

	
188 188
    // Node map for storing path data
189 189
    PathDataNodeMap _data;
190 190
    // The processed nodes in the last round
191 191
    std::vector<Node> _process;
192 192

	
193 193
    Tolerance _tolerance;
194 194
    
195 195
    // Infinite constant
196 196
    const LargeValue INF;
197 197

	
198 198
  public:
199 199

	
200 200
    /// \name Named Template Parameters
201 201
    /// @{
202 202

	
203 203
    template <typename T>
204 204
    struct SetLargeValueTraits : public Traits {
205 205
      typedef T LargeValue;
206 206
      typedef lemon::Tolerance<T> Tolerance;
207 207
    };
208 208

	
209 209
    /// \brief \ref named-templ-param "Named parameter" for setting
210 210
    /// \c LargeValue type.
211 211
    ///
212 212
    /// \ref named-templ-param "Named parameter" for setting \c LargeValue
213 213
    /// type. It is used for internal computations in the algorithm.
214 214
    template <typename T>
215 215
    struct SetLargeValue
216 216
      : public Karp<GR, LEN, SetLargeValueTraits<T> > {
217 217
      typedef Karp<GR, LEN, SetLargeValueTraits<T> > Create;
218 218
    };
219 219

	
220 220
    template <typename T>
221 221
    struct SetPathTraits : public Traits {
222 222
      typedef T Path;
223 223
    };
224 224

	
225 225
    /// \brief \ref named-templ-param "Named parameter" for setting
226 226
    /// \c %Path type.
227 227
    ///
228 228
    /// \ref named-templ-param "Named parameter" for setting the \c %Path
229 229
    /// type of the found cycles.
230 230
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
231 231
    /// and it must have an \c addFront() function.
232 232
    template <typename T>
233 233
    struct SetPath
234 234
      : public Karp<GR, LEN, SetPathTraits<T> > {
235 235
      typedef Karp<GR, LEN, SetPathTraits<T> > Create;
236 236
    };
237 237

	
238 238
    /// @}
239 239

	
240 240
  public:
241 241

	
242 242
    /// \brief Constructor.
243 243
    ///
244 244
    /// The constructor of the class.
245 245
    ///
246 246
    /// \param digraph The digraph the algorithm runs on.
247 247
    /// \param length The lengths (costs) of the arcs.
248 248
    Karp( const Digraph &digraph,
249 249
          const LengthMap &length ) :
250 250
      _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
251 251
      _cycle_length(0), _cycle_size(1), _cycle_node(INVALID),
252 252
      _cycle_path(NULL), _local_path(false), _data(digraph),
253 253
      INF(std::numeric_limits<LargeValue>::has_infinity ?
254 254
          std::numeric_limits<LargeValue>::infinity() :
255 255
          std::numeric_limits<LargeValue>::max())
256 256
    {}
257 257

	
258 258
    /// Destructor.
259 259
    ~Karp() {
260 260
      if (_local_path) delete _cycle_path;
261 261
    }
262 262

	
263 263
    /// \brief Set the path structure for storing the found cycle.
264 264
    ///
265 265
    /// This function sets an external path structure for storing the
266 266
    /// found cycle.
267 267
    ///
268 268
    /// If you don't call this function before calling \ref run() or
269 269
    /// \ref findMinMean(), it will allocate a local \ref Path "path"
270 270
    /// structure. The destuctor deallocates this automatically
271 271
    /// allocated object, of course.
272 272
    ///
273 273
    /// \note The algorithm calls only the \ref lemon::Path::addFront()
274 274
    /// "addFront()" function of the given path structure.
275 275
    ///
276 276
    /// \return <tt>(*this)</tt>
277 277
    Karp& cycle(Path &path) {
278 278
      if (_local_path) {
279 279
        delete _cycle_path;
280 280
        _local_path = false;
281 281
      }
282 282
      _cycle_path = &path;
283 283
      return *this;
284 284
    }
285 285

	
286 286
    /// \brief Set the tolerance used by the algorithm.
287 287
    ///
288 288
    /// This function sets the tolerance object used by the algorithm.
289 289
    ///
290 290
    /// \return <tt>(*this)</tt>
291 291
    Karp& tolerance(const Tolerance& tolerance) {
292 292
      _tolerance = tolerance;
293 293
      return *this;
294 294
    }
295 295

	
296 296
    /// \brief Return a const reference to the tolerance.
297 297
    ///
298 298
    /// This function returns a const reference to the tolerance object
299 299
    /// used by the algorithm.
300 300
    const Tolerance& tolerance() const {
301 301
      return _tolerance;
302 302
    }
303 303

	
304 304
    /// \name Execution control
305 305
    /// The simplest way to execute the algorithm is to call the \ref run()
306 306
    /// function.\n
307 307
    /// If you only need the minimum mean length, you may call
308 308
    /// \ref findMinMean().
309 309

	
310 310
    /// @{
311 311

	
312 312
    /// \brief Run the algorithm.
313 313
    ///
314 314
    /// This function runs the algorithm.
315 315
    /// It can be called more than once (e.g. if the underlying digraph
316 316
    /// and/or the arc lengths have been modified).
317 317
    ///
318 318
    /// \return \c true if a directed cycle exists in the digraph.
319 319
    ///
320 320
    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
321 321
    /// \code
322 322
    ///   return mmc.findMinMean() && mmc.findCycle();
323 323
    /// \endcode
324 324
    bool run() {
325 325
      return findMinMean() && findCycle();
326 326
    }
327 327

	
328 328
    /// \brief Find the minimum cycle mean.
329 329
    ///
330 330
    /// This function finds the minimum mean length of the directed
331 331
    /// cycles in the digraph.
332 332
    ///
333 333
    /// \return \c true if a directed cycle exists in the digraph.
334 334
    bool findMinMean() {
335 335
      // Initialization and find strongly connected components
336 336
      init();
337 337
      findComponents();
338 338
      
339 339
      // Find the minimum cycle mean in the components
340 340
      for (int comp = 0; comp < _comp_num; ++comp) {
341 341
        if (!initComponent(comp)) continue;
342 342
        processRounds();
343 343
        updateMinMean();
344 344
      }
345 345
      return (_cycle_node != INVALID);
346 346
    }
347 347

	
348 348
    /// \brief Find a minimum mean directed cycle.
349 349
    ///
350 350
    /// This function finds a directed cycle of minimum mean length
351 351
    /// in the digraph using the data computed by findMinMean().
352 352
    ///
353 353
    /// \return \c true if a directed cycle exists in the digraph.
354 354
    ///
355 355
    /// \pre \ref findMinMean() must be called before using this function.
356 356
    bool findCycle() {
357 357
      if (_cycle_node == INVALID) return false;
358 358
      IntNodeMap reached(_gr, -1);
359 359
      int r = _data[_cycle_node].size();
360 360
      Node u = _cycle_node;
361 361
      while (reached[u] < 0) {
362 362
        reached[u] = --r;
363 363
        u = _gr.source(_data[u][r].pred);
364 364
      }
365 365
      r = reached[u];
366 366
      Arc e = _data[u][r].pred;
367 367
      _cycle_path->addFront(e);
368 368
      _cycle_length = _length[e];
369 369
      _cycle_size = 1;
370 370
      Node v;
371 371
      while ((v = _gr.source(e)) != u) {
372 372
        e = _data[v][--r].pred;
373 373
        _cycle_path->addFront(e);
374 374
        _cycle_length += _length[e];
375 375
        ++_cycle_size;
376 376
      }
377 377
      return true;
378 378
    }
379 379

	
380 380
    /// @}
381 381

	
382 382
    /// \name Query Functions
383 383
    /// The results of the algorithm can be obtained using these
384 384
    /// functions.\n
385 385
    /// The algorithm should be executed before using them.
386 386

	
387 387
    /// @{
388 388

	
389 389
    /// \brief Return the total length of the found cycle.
390 390
    ///
391 391
    /// This function returns the total length of the found cycle.
392 392
    ///
393 393
    /// \pre \ref run() or \ref findMinMean() must be called before
394 394
    /// using this function.
395
    LargeValue cycleLength() const {
396
      return _cycle_length;
395
    Value cycleLength() const {
396
      return static_cast<Value>(_cycle_length);
397 397
    }
398 398

	
399 399
    /// \brief Return the number of arcs on the found cycle.
400 400
    ///
401 401
    /// This function returns the number of arcs on the found cycle.
402 402
    ///
403 403
    /// \pre \ref run() or \ref findMinMean() must be called before
404 404
    /// using this function.
405 405
    int cycleArcNum() const {
406 406
      return _cycle_size;
407 407
    }
408 408

	
409 409
    /// \brief Return the mean length of the found cycle.
410 410
    ///
411 411
    /// This function returns the mean length of the found cycle.
412 412
    ///
413 413
    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
414 414
    /// following code.
415 415
    /// \code
416 416
    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
417 417
    /// \endcode
418 418
    ///
419 419
    /// \pre \ref run() or \ref findMinMean() must be called before
420 420
    /// using this function.
421 421
    double cycleMean() const {
422 422
      return static_cast<double>(_cycle_length) / _cycle_size;
423 423
    }
424 424

	
425 425
    /// \brief Return the found cycle.
426 426
    ///
427 427
    /// This function returns a const reference to the path structure
428 428
    /// storing the found cycle.
429 429
    ///
430 430
    /// \pre \ref run() or \ref findCycle() must be called before using
431 431
    /// this function.
432 432
    const Path& cycle() const {
433 433
      return *_cycle_path;
434 434
    }
435 435

	
436 436
    ///@}
437 437

	
438 438
  private:
439 439

	
440 440
    // Initialization
441 441
    void init() {
442 442
      if (!_cycle_path) {
443 443
        _local_path = true;
444 444
        _cycle_path = new Path;
445 445
      }
446 446
      _cycle_path->clear();
447 447
      _cycle_length = 0;
448 448
      _cycle_size = 1;
449 449
      _cycle_node = INVALID;
450 450
      for (NodeIt u(_gr); u != INVALID; ++u)
451 451
        _data[u].clear();
452 452
    }
453 453

	
454 454
    // Find strongly connected components and initialize _comp_nodes
455 455
    // and _out_arcs
456 456
    void findComponents() {
457 457
      _comp_num = stronglyConnectedComponents(_gr, _comp);
458 458
      _comp_nodes.resize(_comp_num);
459 459
      if (_comp_num == 1) {
460 460
        _comp_nodes[0].clear();
461 461
        for (NodeIt n(_gr); n != INVALID; ++n) {
462 462
          _comp_nodes[0].push_back(n);
463 463
          _out_arcs[n].clear();
464 464
          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
465 465
            _out_arcs[n].push_back(a);
466 466
          }
467 467
        }
468 468
      } else {
469 469
        for (int i = 0; i < _comp_num; ++i)
470 470
          _comp_nodes[i].clear();
471 471
        for (NodeIt n(_gr); n != INVALID; ++n) {
472 472
          int k = _comp[n];
473 473
          _comp_nodes[k].push_back(n);
474 474
          _out_arcs[n].clear();
475 475
          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
476 476
            if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
477 477
          }
478 478
        }
479 479
      }
480 480
    }
481 481

	
482 482
    // Initialize path data for the current component
483 483
    bool initComponent(int comp) {
484 484
      _nodes = &(_comp_nodes[comp]);
485 485
      int n = _nodes->size();
486 486
      if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
487 487
        return false;
488 488
      }      
489 489
      for (int i = 0; i < n; ++i) {
490 490
        _data[(*_nodes)[i]].resize(n + 1, PathData(INF));
491 491
      }
492 492
      return true;
493 493
    }
494 494

	
495 495
    // Process all rounds of computing path data for the current component.
496 496
    // _data[v][k] is the length of a shortest directed walk from the root
497 497
    // node to node v containing exactly k arcs.
498 498
    void processRounds() {
499 499
      Node start = (*_nodes)[0];
500 500
      _data[start][0] = PathData(0);
501 501
      _process.clear();
502 502
      _process.push_back(start);
503 503

	
504 504
      int k, n = _nodes->size();
505 505
      for (k = 1; k <= n && int(_process.size()) < n; ++k) {
506 506
        processNextBuildRound(k);
507 507
      }
508 508
      for ( ; k <= n; ++k) {
509 509
        processNextFullRound(k);
510 510
      }
511 511
    }
512 512

	
513 513
    // Process one round and rebuild _process
514 514
    void processNextBuildRound(int k) {
515 515
      std::vector<Node> next;
516 516
      Node u, v;
517 517
      Arc e;
518 518
      LargeValue d;
519 519
      for (int i = 0; i < int(_process.size()); ++i) {
520 520
        u = _process[i];
521 521
        for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
522 522
          e = _out_arcs[u][j];
523 523
          v = _gr.target(e);
524 524
          d = _data[u][k-1].dist + _length[e];
525 525
          if (_tolerance.less(d, _data[v][k].dist)) {
526 526
            if (_data[v][k].dist == INF) next.push_back(v);
527 527
            _data[v][k] = PathData(d, e);
528 528
          }
529 529
        }
530 530
      }
531 531
      _process.swap(next);
532 532
    }
533 533

	
534 534
    // Process one round using _nodes instead of _process
535 535
    void processNextFullRound(int k) {
536 536
      Node u, v;
537 537
      Arc e;
538 538
      LargeValue d;
539 539
      for (int i = 0; i < int(_nodes->size()); ++i) {
540 540
        u = (*_nodes)[i];
541 541
        for (int j = 0; j < int(_out_arcs[u].size()); ++j) {
542 542
          e = _out_arcs[u][j];
543 543
          v = _gr.target(e);
544 544
          d = _data[u][k-1].dist + _length[e];
545 545
          if (_tolerance.less(d, _data[v][k].dist)) {
546 546
            _data[v][k] = PathData(d, e);
547 547
          }
548 548
        }
549 549
      }
550 550
    }
551 551

	
552 552
    // Update the minimum cycle mean
553 553
    void updateMinMean() {
554 554
      int n = _nodes->size();
555 555
      for (int i = 0; i < n; ++i) {
556 556
        Node u = (*_nodes)[i];
557 557
        if (_data[u][n].dist == INF) continue;
558 558
        LargeValue length, max_length = 0;
559 559
        int size, max_size = 1;
560 560
        bool found_curr = false;
561 561
        for (int k = 0; k < n; ++k) {
562 562
          if (_data[u][k].dist == INF) continue;
563 563
          length = _data[u][n].dist - _data[u][k].dist;
564 564
          size = n - k;
565 565
          if (!found_curr || length * max_size > max_length * size) {
566 566
            found_curr = true;
567 567
            max_length = length;
568 568
            max_size = size;
569 569
          }
570 570
        }
571 571
        if ( found_curr && (_cycle_node == INVALID ||
572 572
             max_length * _cycle_size < _cycle_length * max_size) ) {
573 573
          _cycle_length = max_length;
574 574
          _cycle_size = max_size;
575 575
          _cycle_node = u;
576 576
        }
577 577
      }
578 578
    }
579 579

	
580 580
  }; //class Karp
581 581

	
582 582
  ///@}
583 583

	
584 584
} //namespace lemon
585 585

	
586 586
#endif //LEMON_KARP_H
0 comments (0 inline)