gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Merge
0 2 0
merge default
0 files changed with 55 insertions and 4 deletions:
↑ Collapse diff ↑
Ignore white space 384 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_BELLMAN_FORD_H
20 20
#define LEMON_BELLMAN_FORD_H
21 21

	
22 22
/// \ingroup shortest_path
23 23
/// \file
24 24
/// \brief Bellman-Ford 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
#include <lemon/tolerance.h>
31 32
#include <lemon/path.h>
32 33

	
33 34
#include <limits>
34 35

	
35 36
namespace lemon {
36 37

	
37
  /// \brief Default OperationTraits for the BellmanFord algorithm class.
38
  /// \brief Default operation traits for the BellmanFord algorithm class.
38 39
  ///  
39 40
  /// This operation traits class defines all computational operations
40 41
  /// and constants that are used in the Bellman-Ford algorithm.
41 42
  /// The default implementation is based on the \c numeric_limits class.
42 43
  /// If the numeric type does not have infinity value, then the maximum
43 44
  /// value is used as extremal infinity value.
45
  ///
46
  /// \see BellmanFordToleranceOperationTraits
44 47
  template <
45 48
    typename V, 
46 49
    bool has_inf = std::numeric_limits<V>::has_infinity>
47 50
  struct BellmanFordDefaultOperationTraits {
48
    /// \e
51
    /// \brief Value type for the algorithm.
49 52
    typedef V Value;
50 53
    /// \brief Gives back the zero value of the type.
51 54
    static Value zero() {
52 55
      return static_cast<Value>(0);
53 56
    }
54 57
    /// \brief Gives back the positive infinity value of the type.
55 58
    static Value infinity() {
56 59
      return std::numeric_limits<Value>::infinity();
57 60
    }
58 61
    /// \brief Gives back the sum of the given two elements.
59 62
    static Value plus(const Value& left, const Value& right) {
60 63
      return left + right;
61 64
    }
62 65
    /// \brief Gives back \c true only if the first value is less than
63 66
    /// the second.
64 67
    static bool less(const Value& left, const Value& right) {
65 68
      return left < right;
66 69
    }
67 70
  };
68 71

	
69 72
  template <typename V>
70 73
  struct BellmanFordDefaultOperationTraits<V, false> {
71 74
    typedef V Value;
72 75
    static Value zero() {
73 76
      return static_cast<Value>(0);
74 77
    }
75 78
    static Value infinity() {
76 79
      return std::numeric_limits<Value>::max();
77 80
    }
78 81
    static Value plus(const Value& left, const Value& right) {
79 82
      if (left == infinity() || right == infinity()) return infinity();
80 83
      return left + right;
81 84
    }
82 85
    static bool less(const Value& left, const Value& right) {
83 86
      return left < right;
84 87
    }
85 88
  };
86 89
  
90
  /// \brief Operation traits for the BellmanFord algorithm class
91
  /// using tolerance.
92
  ///
93
  /// This operation traits class defines all computational operations
94
  /// and constants that are used in the Bellman-Ford algorithm.
95
  /// The only difference between this implementation and
96
  /// \ref BellmanFordDefaultOperationTraits is that this class uses
97
  /// the \ref Tolerance "tolerance technique" in its \ref less()
98
  /// function.
99
  ///
100
  /// \tparam V The value type.
101
  /// \tparam eps The epsilon value for the \ref less() function.
102
  /// By default, it is the epsilon value used by \ref Tolerance
103
  /// "Tolerance<V>".
104
  ///
105
  /// \see BellmanFordDefaultOperationTraits
106
#ifdef DOXYGEN
107
  template <typename V, V eps>
108
#else
109
  template <
110
    typename V,
111
    V eps = Tolerance<V>::def_epsilon>
112
#endif
113
  struct BellmanFordToleranceOperationTraits {
114
    /// \brief Value type for the algorithm.
115
    typedef V Value;
116
    /// \brief Gives back the zero value of the type.
117
    static Value zero() {
118
      return static_cast<Value>(0);
119
    }
120
    /// \brief Gives back the positive infinity value of the type.
121
    static Value infinity() {
122
      return std::numeric_limits<Value>::infinity();
123
    }
124
    /// \brief Gives back the sum of the given two elements.
125
    static Value plus(const Value& left, const Value& right) {
126
      return left + right;
127
    }
128
    /// \brief Gives back \c true only if the first value is less than
129
    /// the second.
130
    static bool less(const Value& left, const Value& right) {
131
      return left + eps < right;
132
    }
133
  };
134

	
87 135
  /// \brief Default traits class of BellmanFord class.
88 136
  ///
89 137
  /// Default traits class of BellmanFord class.
90 138
  /// \param GR The type of the digraph.
91 139
  /// \param LEN The type of the length map.
92 140
  template<typename GR, typename LEN>
93 141
  struct BellmanFordDefaultTraits {
94 142
    /// The type of the digraph the algorithm runs on. 
95 143
    typedef GR Digraph;
96 144

	
97 145
    /// \brief The type of the map that stores the arc lengths.
98 146
    ///
99 147
    /// The type of the map that stores the arc lengths.
100 148
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
101 149
    typedef LEN LengthMap;
102 150

	
103 151
    /// The type of the arc lengths.
104 152
    typedef typename LEN::Value Value;
105 153

	
106 154
    /// \brief Operation traits for Bellman-Ford algorithm.
107 155
    ///
108 156
    /// It defines the used operations and the infinity value for the
109 157
    /// given \c Value type.
110
    /// \see BellmanFordDefaultOperationTraits
158
    /// \see BellmanFordDefaultOperationTraits,
159
    /// BellmanFordToleranceOperationTraits
111 160
    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
112 161
 
113 162
    /// \brief The type of the map that stores the last arcs of the 
114 163
    /// shortest paths.
115 164
    /// 
116 165
    /// The type of the map that stores the last
117 166
    /// arcs of the shortest paths.
118 167
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
119 168
    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
120 169

	
121 170
    /// \brief Instantiates a \c PredMap.
122 171
    /// 
123 172
    /// This function instantiates a \ref PredMap. 
124 173
    /// \param g is the digraph to which we would like to define the
125 174
    /// \ref PredMap.
126 175
    static PredMap *createPredMap(const GR& g) {
127 176
      return new PredMap(g);
128 177
    }
129 178

	
130 179
    /// \brief The type of the map that stores the distances of the nodes.
131 180
    ///
132 181
    /// The type of the map that stores the distances of the nodes.
133 182
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
134 183
    typedef typename GR::template NodeMap<typename LEN::Value> DistMap;
135 184

	
136 185
    /// \brief Instantiates a \c DistMap.
137 186
    ///
138 187
    /// This function instantiates a \ref DistMap. 
139 188
    /// \param g is the digraph to which we would like to define the 
140 189
    /// \ref DistMap.
141 190
    static DistMap *createDistMap(const GR& g) {
142 191
      return new DistMap(g);
143 192
    }
144 193

	
145 194
  };
146 195
  
147 196
  /// \brief %BellmanFord algorithm class.
148 197
  ///
149 198
  /// \ingroup shortest_path
150 199
  /// This class provides an efficient implementation of the Bellman-Ford 
151 200
  /// algorithm. The maximum time complexity of the algorithm is
152 201
  /// <tt>O(ne)</tt>.
153 202
  ///
154 203
  /// The Bellman-Ford algorithm solves the single-source shortest path
155 204
  /// problem when the arcs can have negative lengths, but the digraph
156 205
  /// should not contain directed cycles with negative total length.
157 206
  /// If all arc costs are non-negative, consider to use the Dijkstra
158 207
  /// algorithm instead, since it is more efficient.
159 208
  ///
160 209
  /// The arc lengths are passed to the algorithm using a
161 210
  /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any 
162 211
  /// kind of length. The type of the length values is determined by the
163 212
  /// \ref concepts::ReadMap::Value "Value" type of the length map.
164 213
  ///
165 214
  /// There is also a \ref bellmanFord() "function-type interface" for the
166 215
  /// Bellman-Ford algorithm, which is convenient in the simplier cases and
167 216
  /// it can be used easier.
168 217
  ///
169 218
  /// \tparam GR The type of the digraph the algorithm runs on.
170 219
  /// The default type is \ref ListDigraph.
171 220
  /// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
172 221
  /// the lengths of the arcs. The default map type is
173 222
  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
174 223
  /// \tparam TR The traits class that defines various types used by the
175 224
  /// algorithm. By default, it is \ref BellmanFordDefaultTraits
176 225
  /// "BellmanFordDefaultTraits<GR, LEN>".
177 226
  /// In most cases, this parameter should not be set directly,
178 227
  /// consider to use the named template parameters instead.
179 228
#ifdef DOXYGEN
180 229
  template <typename GR, typename LEN, typename TR>
181 230
#else
182 231
  template <typename GR=ListDigraph,
183 232
            typename LEN=typename GR::template ArcMap<int>,
184 233
            typename TR=BellmanFordDefaultTraits<GR,LEN> >
185 234
#endif
186 235
  class BellmanFord {
187 236
  public:
188 237

	
189 238
    ///The type of the underlying digraph.
190 239
    typedef typename TR::Digraph Digraph;
191 240
    
192 241
    /// \brief The type of the arc lengths.
193 242
    typedef typename TR::LengthMap::Value Value;
194 243
    /// \brief The type of the map that stores the arc lengths.
195 244
    typedef typename TR::LengthMap LengthMap;
196 245
    /// \brief The type of the map that stores the last
197 246
    /// arcs of the shortest paths.
198 247
    typedef typename TR::PredMap PredMap;
199 248
    /// \brief The type of the map that stores the distances of the nodes.
200 249
    typedef typename TR::DistMap DistMap;
201 250
    /// The type of the paths.
202 251
    typedef PredMapPath<Digraph, PredMap> Path;
203 252
    ///\brief The \ref BellmanFordDefaultOperationTraits
204 253
    /// "operation traits class" of the algorithm.
205 254
    typedef typename TR::OperationTraits OperationTraits;
206 255

	
207 256
    ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
208 257
    typedef TR Traits;
209 258

	
210 259
  private:
211 260

	
212 261
    typedef typename Digraph::Node Node;
213 262
    typedef typename Digraph::NodeIt NodeIt;
214 263
    typedef typename Digraph::Arc Arc;
215 264
    typedef typename Digraph::OutArcIt OutArcIt;
216 265

	
217 266
    // Pointer to the underlying digraph.
218 267
    const Digraph *_gr;
219 268
    // Pointer to the length map
220 269
    const LengthMap *_length;
221 270
    // Pointer to the map of predecessors arcs.
222 271
    PredMap *_pred;
223 272
    // Indicates if _pred is locally allocated (true) or not.
224 273
    bool _local_pred;
225 274
    // Pointer to the map of distances.
226 275
    DistMap *_dist;
227 276
    // Indicates if _dist is locally allocated (true) or not.
228 277
    bool _local_dist;
229 278

	
230 279
    typedef typename Digraph::template NodeMap<bool> MaskMap;
231 280
    MaskMap *_mask;
232 281

	
233 282
    std::vector<Node> _process;
234 283

	
235 284
    // Creates the maps if necessary.
236 285
    void create_maps() {
237 286
      if(!_pred) {
238 287
	_local_pred = true;
239 288
	_pred = Traits::createPredMap(*_gr);
240 289
      }
241 290
      if(!_dist) {
242 291
	_local_dist = true;
243 292
	_dist = Traits::createDistMap(*_gr);
244 293
      }
245 294
      if(!_mask) {
246 295
        _mask = new MaskMap(*_gr);
247 296
      }
248 297
    }
249 298
    
250 299
  public :
251 300
 
252 301
    typedef BellmanFord Create;
253 302

	
254 303
    /// \name Named Template Parameters
255 304

	
256 305
    ///@{
257 306

	
258 307
    template <class T>
259 308
    struct SetPredMapTraits : public Traits {
260 309
      typedef T PredMap;
261 310
      static PredMap *createPredMap(const Digraph&) {
262 311
        LEMON_ASSERT(false, "PredMap is not initialized");
263 312
        return 0; // ignore warnings
264 313
      }
265 314
    };
266 315

	
267 316
    /// \brief \ref named-templ-param "Named parameter" for setting
268 317
    /// \c PredMap type.
269 318
    ///
270 319
    /// \ref named-templ-param "Named parameter" for setting
271 320
    /// \c PredMap type.
272 321
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
273 322
    template <class T>
274 323
    struct SetPredMap 
275 324
      : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
276 325
      typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
277 326
    };
278 327
    
279 328
    template <class T>
280 329
    struct SetDistMapTraits : public Traits {
281 330
      typedef T DistMap;
282 331
      static DistMap *createDistMap(const Digraph&) {
283 332
        LEMON_ASSERT(false, "DistMap is not initialized");
284 333
        return 0; // ignore warnings
285 334
      }
286 335
    };
287 336

	
288 337
    /// \brief \ref named-templ-param "Named parameter" for setting
289 338
    /// \c DistMap type.
290 339
    ///
291 340
    /// \ref named-templ-param "Named parameter" for setting
292 341
    /// \c DistMap type.
293 342
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
294 343
    template <class T>
295 344
    struct SetDistMap 
296 345
      : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
297 346
      typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
298 347
    };
299 348

	
300 349
    template <class T>
301 350
    struct SetOperationTraitsTraits : public Traits {
302 351
      typedef T OperationTraits;
... ...
@@ -648,385 +697,386 @@
648 697
      /// \brief Constructor.
649 698
      ///
650 699
      /// Constructor for getting the active nodes of the given BellmanFord
651 700
      /// instance. 
652 701
      ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
653 702
      {
654 703
        _index = _algorithm->_process.size() - 1;
655 704
      }
656 705

	
657 706
      /// \brief Invalid constructor.
658 707
      ///
659 708
      /// Invalid constructor.
660 709
      ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
661 710

	
662 711
      /// \brief Conversion to \c Node.
663 712
      ///
664 713
      /// Conversion to \c Node.
665 714
      operator Node() const { 
666 715
        return _index >= 0 ? _algorithm->_process[_index] : INVALID;
667 716
      }
668 717

	
669 718
      /// \brief Increment operator.
670 719
      ///
671 720
      /// Increment operator.
672 721
      ActiveIt& operator++() {
673 722
        --_index;
674 723
        return *this; 
675 724
      }
676 725

	
677 726
      bool operator==(const ActiveIt& it) const { 
678 727
        return static_cast<Node>(*this) == static_cast<Node>(it); 
679 728
      }
680 729
      bool operator!=(const ActiveIt& it) const { 
681 730
        return static_cast<Node>(*this) != static_cast<Node>(it); 
682 731
      }
683 732
      bool operator<(const ActiveIt& it) const { 
684 733
        return static_cast<Node>(*this) < static_cast<Node>(it); 
685 734
      }
686 735
      
687 736
    private:
688 737
      const BellmanFord* _algorithm;
689 738
      int _index;
690 739
    };
691 740
    
692 741
    /// \name Query Functions
693 742
    /// The result of the Bellman-Ford algorithm can be obtained using these
694 743
    /// functions.\n
695 744
    /// Either \ref run() or \ref init() should be called before using them.
696 745
    
697 746
    ///@{
698 747

	
699 748
    /// \brief The shortest path to the given node.
700 749
    ///    
701 750
    /// Gives back the shortest path to the given node from the root(s).
702 751
    ///
703 752
    /// \warning \c t should be reached from the root(s).
704 753
    ///
705 754
    /// \pre Either \ref run() or \ref init() must be called before
706 755
    /// using this function.
707 756
    Path path(Node t) const
708 757
    {
709 758
      return Path(*_gr, *_pred, t);
710 759
    }
711 760
	  
712 761
    /// \brief The distance of the given node from the root(s).
713 762
    ///
714 763
    /// Returns the distance of the given node from the root(s).
715 764
    ///
716 765
    /// \warning If node \c v is not reached from the root(s), then
717 766
    /// the return value of this function is undefined.
718 767
    ///
719 768
    /// \pre Either \ref run() or \ref init() must be called before
720 769
    /// using this function.
721 770
    Value dist(Node v) const { return (*_dist)[v]; }
722 771

	
723 772
    /// \brief Returns the 'previous arc' of the shortest path tree for
724 773
    /// the given node.
725 774
    ///
726 775
    /// This function returns the 'previous arc' of the shortest path
727 776
    /// tree for node \c v, i.e. it returns the last arc of a
728 777
    /// shortest path from a root to \c v. It is \c INVALID if \c v
729 778
    /// is not reached from the root(s) or if \c v is a root.
730 779
    ///
731 780
    /// The shortest path tree used here is equal to the shortest path
732 781
    /// tree used in \ref predNode() and \ref predMap().
733 782
    ///
734 783
    /// \pre Either \ref run() or \ref init() must be called before
735 784
    /// using this function.
736 785
    Arc predArc(Node v) const { return (*_pred)[v]; }
737 786

	
738 787
    /// \brief Returns the 'previous node' of the shortest path tree for
739 788
    /// the given node.
740 789
    ///
741 790
    /// This function returns the 'previous node' of the shortest path
742 791
    /// tree for node \c v, i.e. it returns the last but one node of
743 792
    /// a shortest path from a root to \c v. It is \c INVALID if \c v
744 793
    /// is not reached from the root(s) or if \c v is a root.
745 794
    ///
746 795
    /// The shortest path tree used here is equal to the shortest path
747 796
    /// tree used in \ref predArc() and \ref predMap().
748 797
    ///
749 798
    /// \pre Either \ref run() or \ref init() must be called before
750 799
    /// using this function.
751 800
    Node predNode(Node v) const { 
752 801
      return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]); 
753 802
    }
754 803
    
755 804
    /// \brief Returns a const reference to the node map that stores the
756 805
    /// distances of the nodes.
757 806
    ///
758 807
    /// Returns a const reference to the node map that stores the distances
759 808
    /// of the nodes calculated by the algorithm.
760 809
    ///
761 810
    /// \pre Either \ref run() or \ref init() must be called before
762 811
    /// using this function.
763 812
    const DistMap &distMap() const { return *_dist;}
764 813
 
765 814
    /// \brief Returns a const reference to the node map that stores the
766 815
    /// predecessor arcs.
767 816
    ///
768 817
    /// Returns a const reference to the node map that stores the predecessor
769 818
    /// arcs, which form the shortest path tree (forest).
770 819
    ///
771 820
    /// \pre Either \ref run() or \ref init() must be called before
772 821
    /// using this function.
773 822
    const PredMap &predMap() const { return *_pred; }
774 823
 
775 824
    /// \brief Checks if a node is reached from the root(s).
776 825
    ///
777 826
    /// Returns \c true if \c v is reached from the root(s).
778 827
    ///
779 828
    /// \pre Either \ref run() or \ref init() must be called before
780 829
    /// using this function.
781 830
    bool reached(Node v) const {
782 831
      return (*_dist)[v] != OperationTraits::infinity();
783 832
    }
784 833

	
785 834
    /// \brief Gives back a negative cycle.
786 835
    ///    
787 836
    /// This function gives back a directed cycle with negative total
788 837
    /// length if the algorithm has already found one.
789 838
    /// Otherwise it gives back an empty path.
790 839
    lemon::Path<Digraph> negativeCycle() const {
791 840
      typename Digraph::template NodeMap<int> state(*_gr, -1);
792 841
      lemon::Path<Digraph> cycle;
793 842
      for (int i = 0; i < int(_process.size()); ++i) {
794 843
        if (state[_process[i]] != -1) continue;
795 844
        for (Node v = _process[i]; (*_pred)[v] != INVALID;
796 845
             v = _gr->source((*_pred)[v])) {
797 846
          if (state[v] == i) {
798 847
            cycle.addFront((*_pred)[v]);
799 848
            for (Node u = _gr->source((*_pred)[v]); u != v;
800 849
                 u = _gr->source((*_pred)[u])) {
801 850
              cycle.addFront((*_pred)[u]);
802 851
            }
803 852
            return cycle;
804 853
          }
805 854
          else if (state[v] >= 0) {
806 855
            break;
807 856
          }
808 857
          state[v] = i;
809 858
        }
810 859
      }
811 860
      return cycle;
812 861
    }
813 862
    
814 863
    ///@}
815 864
  };
816 865
 
817 866
  /// \brief Default traits class of bellmanFord() function.
818 867
  ///
819 868
  /// Default traits class of bellmanFord() function.
820 869
  /// \tparam GR The type of the digraph.
821 870
  /// \tparam LEN The type of the length map.
822 871
  template <typename GR, typename LEN>
823 872
  struct BellmanFordWizardDefaultTraits {
824 873
    /// The type of the digraph the algorithm runs on. 
825 874
    typedef GR Digraph;
826 875

	
827 876
    /// \brief The type of the map that stores the arc lengths.
828 877
    ///
829 878
    /// The type of the map that stores the arc lengths.
830 879
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
831 880
    typedef LEN LengthMap;
832 881

	
833 882
    /// The type of the arc lengths.
834 883
    typedef typename LEN::Value Value;
835 884

	
836 885
    /// \brief Operation traits for Bellman-Ford algorithm.
837 886
    ///
838 887
    /// It defines the used operations and the infinity value for the
839 888
    /// given \c Value type.
840
    /// \see BellmanFordDefaultOperationTraits
889
    /// \see BellmanFordDefaultOperationTraits,
890
    /// BellmanFordToleranceOperationTraits
841 891
    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
842 892

	
843 893
    /// \brief The type of the map that stores the last
844 894
    /// arcs of the shortest paths.
845 895
    /// 
846 896
    /// The type of the map that stores the last arcs of the shortest paths.
847 897
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
848 898
    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
849 899

	
850 900
    /// \brief Instantiates a \c PredMap.
851 901
    /// 
852 902
    /// This function instantiates a \ref PredMap.
853 903
    /// \param g is the digraph to which we would like to define the
854 904
    /// \ref PredMap.
855 905
    static PredMap *createPredMap(const GR &g) {
856 906
      return new PredMap(g);
857 907
    }
858 908

	
859 909
    /// \brief The type of the map that stores the distances of the nodes.
860 910
    ///
861 911
    /// The type of the map that stores the distances of the nodes.
862 912
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
863 913
    typedef typename GR::template NodeMap<Value> DistMap;
864 914

	
865 915
    /// \brief Instantiates a \c DistMap.
866 916
    ///
867 917
    /// This function instantiates a \ref DistMap. 
868 918
    /// \param g is the digraph to which we would like to define the
869 919
    /// \ref DistMap.
870 920
    static DistMap *createDistMap(const GR &g) {
871 921
      return new DistMap(g);
872 922
    }
873 923

	
874 924
    ///The type of the shortest paths.
875 925

	
876 926
    ///The type of the shortest paths.
877 927
    ///It must meet the \ref concepts::Path "Path" concept.
878 928
    typedef lemon::Path<Digraph> Path;
879 929
  };
880 930
  
881 931
  /// \brief Default traits class used by BellmanFordWizard.
882 932
  ///
883 933
  /// Default traits class used by BellmanFordWizard.
884 934
  /// \tparam GR The type of the digraph.
885 935
  /// \tparam LEN The type of the length map.
886 936
  template <typename GR, typename LEN>
887 937
  class BellmanFordWizardBase 
888 938
    : public BellmanFordWizardDefaultTraits<GR, LEN> {
889 939

	
890 940
    typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
891 941
  protected:
892 942
    // Type of the nodes in the digraph.
893 943
    typedef typename Base::Digraph::Node Node;
894 944

	
895 945
    // Pointer to the underlying digraph.
896 946
    void *_graph;
897 947
    // Pointer to the length map
898 948
    void *_length;
899 949
    // Pointer to the map of predecessors arcs.
900 950
    void *_pred;
901 951
    // Pointer to the map of distances.
902 952
    void *_dist;
903 953
    //Pointer to the shortest path to the target node.
904 954
    void *_path;
905 955
    //Pointer to the distance of the target node.
906 956
    void *_di;
907 957

	
908 958
    public:
909 959
    /// Constructor.
910 960
    
911 961
    /// This constructor does not require parameters, it initiates
912 962
    /// all of the attributes to default values \c 0.
913 963
    BellmanFordWizardBase() :
914 964
      _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
915 965

	
916 966
    /// Constructor.
917 967
    
918 968
    /// This constructor requires two parameters,
919 969
    /// others are initiated to \c 0.
920 970
    /// \param gr The digraph the algorithm runs on.
921 971
    /// \param len The length map.
922 972
    BellmanFordWizardBase(const GR& gr, 
923 973
			  const LEN& len) :
924 974
      _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))), 
925 975
      _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))), 
926 976
      _pred(0), _dist(0), _path(0), _di(0) {}
927 977

	
928 978
  };
929 979
  
930 980
  /// \brief Auxiliary class for the function-type interface of the
931 981
  /// \ref BellmanFord "Bellman-Ford" algorithm.
932 982
  ///
933 983
  /// This auxiliary class is created to implement the
934 984
  /// \ref bellmanFord() "function-type interface" of the
935 985
  /// \ref BellmanFord "Bellman-Ford" algorithm.
936 986
  /// It does not have own \ref run() method, it uses the
937 987
  /// functions and features of the plain \ref BellmanFord.
938 988
  ///
939 989
  /// This class should only be used through the \ref bellmanFord()
940 990
  /// function, which makes it easier to use the algorithm.
941 991
  ///
942 992
  /// \tparam TR The traits class that defines various types used by the
943 993
  /// algorithm.
944 994
  template<class TR>
945 995
  class BellmanFordWizard : public TR {
946 996
    typedef TR Base;
947 997

	
948 998
    typedef typename TR::Digraph Digraph;
949 999

	
950 1000
    typedef typename Digraph::Node Node;
951 1001
    typedef typename Digraph::NodeIt NodeIt;
952 1002
    typedef typename Digraph::Arc Arc;
953 1003
    typedef typename Digraph::OutArcIt ArcIt;
954 1004
    
955 1005
    typedef typename TR::LengthMap LengthMap;
956 1006
    typedef typename LengthMap::Value Value;
957 1007
    typedef typename TR::PredMap PredMap;
958 1008
    typedef typename TR::DistMap DistMap;
959 1009
    typedef typename TR::Path Path;
960 1010

	
961 1011
  public:
962 1012
    /// Constructor.
963 1013
    BellmanFordWizard() : TR() {}
964 1014

	
965 1015
    /// \brief Constructor that requires parameters.
966 1016
    ///
967 1017
    /// Constructor that requires parameters.
968 1018
    /// These parameters will be the default values for the traits class.
969 1019
    /// \param gr The digraph the algorithm runs on.
970 1020
    /// \param len The length map.
971 1021
    BellmanFordWizard(const Digraph& gr, const LengthMap& len) 
972 1022
      : TR(gr, len) {}
973 1023

	
974 1024
    /// \brief Copy constructor
975 1025
    BellmanFordWizard(const TR &b) : TR(b) {}
976 1026

	
977 1027
    ~BellmanFordWizard() {}
978 1028

	
979 1029
    /// \brief Runs the Bellman-Ford algorithm from the given source node.
980 1030
    ///    
981 1031
    /// This method runs the Bellman-Ford algorithm from the given source
982 1032
    /// node in order to compute the shortest path to each node.
983 1033
    void run(Node s) {
984 1034
      BellmanFord<Digraph,LengthMap,TR> 
985 1035
	bf(*reinterpret_cast<const Digraph*>(Base::_graph), 
986 1036
           *reinterpret_cast<const LengthMap*>(Base::_length));
987 1037
      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
988 1038
      if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
989 1039
      bf.run(s);
990 1040
    }
991 1041

	
992 1042
    /// \brief Runs the Bellman-Ford algorithm to find the shortest path
993 1043
    /// between \c s and \c t.
994 1044
    ///
995 1045
    /// This method runs the Bellman-Ford algorithm from node \c s
996 1046
    /// in order to compute the shortest path to node \c t.
997 1047
    /// Actually, it computes the shortest path to each node, but using
998 1048
    /// this function you can retrieve the distance and the shortest path
999 1049
    /// for a single target node easier.
1000 1050
    ///
1001 1051
    /// \return \c true if \c t is reachable form \c s.
1002 1052
    bool run(Node s, Node t) {
1003 1053
      BellmanFord<Digraph,LengthMap,TR>
1004 1054
        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1005 1055
           *reinterpret_cast<const LengthMap*>(Base::_length));
1006 1056
      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1007 1057
      if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1008 1058
      bf.run(s);
1009 1059
      if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
1010 1060
      if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
1011 1061
      return bf.reached(t);
1012 1062
    }
1013 1063

	
1014 1064
    template<class T>
1015 1065
    struct SetPredMapBase : public Base {
1016 1066
      typedef T PredMap;
1017 1067
      static PredMap *createPredMap(const Digraph &) { return 0; };
1018 1068
      SetPredMapBase(const TR &b) : TR(b) {}
1019 1069
    };
1020 1070
    
1021 1071
    /// \brief \ref named-templ-param "Named parameter" for setting
1022 1072
    /// the predecessor map.
1023 1073
    ///
1024 1074
    /// \ref named-templ-param "Named parameter" for setting
1025 1075
    /// the map that stores the predecessor arcs of the nodes.
1026 1076
    template<class T>
1027 1077
    BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
1028 1078
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1029 1079
      return BellmanFordWizard<SetPredMapBase<T> >(*this);
1030 1080
    }
1031 1081
    
1032 1082
    template<class T>
Ignore white space 384 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#include <lemon/concepts/digraph.h>
20 20
#include <lemon/smart_graph.h>
21 21
#include <lemon/list_graph.h>
22 22
#include <lemon/lgf_reader.h>
23 23
#include <lemon/bellman_ford.h>
24 24
#include <lemon/path.h>
25 25

	
26 26
#include "graph_test.h"
27 27
#include "test_tools.h"
28 28

	
29 29
using namespace lemon;
30 30

	
31 31
char test_lgf[] =
32 32
  "@nodes\n"
33 33
  "label\n"
34 34
  "0\n"
35 35
  "1\n"
36 36
  "2\n"
37 37
  "3\n"
38 38
  "4\n"
39 39
  "@arcs\n"
40 40
  "    length\n"
41 41
  "0 1 3\n"
42 42
  "1 2 -3\n"
43 43
  "1 2 -5\n"
44 44
  "1 3 -2\n"
45 45
  "0 2 -1\n"
46 46
  "1 2 -4\n"
47 47
  "0 3 2\n"
48 48
  "4 2 -5\n"
49 49
  "2 3 1\n"
50 50
  "@attributes\n"
51 51
  "source 0\n"
52 52
  "target 3\n";
53 53

	
54 54

	
55 55
void checkBellmanFordCompile()
56 56
{
57 57
  typedef int Value;
58 58
  typedef concepts::Digraph Digraph;
59 59
  typedef concepts::ReadMap<Digraph::Arc,Value> LengthMap;
60 60
  typedef BellmanFord<Digraph, LengthMap> BF;
61 61
  typedef Digraph::Node Node;
62 62
  typedef Digraph::Arc Arc;
63 63

	
64 64
  Digraph gr;
65 65
  Node s, t, n;
66 66
  Arc e;
67 67
  Value l;
68 68
  int k=3;
69 69
  bool b;
70 70
  BF::DistMap d(gr);
71 71
  BF::PredMap p(gr);
72 72
  LengthMap length;
73 73
  concepts::Path<Digraph> pp;
74 74

	
75 75
  {
76 76
    BF bf_test(gr,length);
77 77
    const BF& const_bf_test = bf_test;
78 78

	
79 79
    bf_test.run(s);
80 80
    bf_test.run(s,k);
81 81

	
82 82
    bf_test.init();
83 83
    bf_test.addSource(s);
84 84
    bf_test.addSource(s, 1);
85 85
    b = bf_test.processNextRound();
86 86
    b = bf_test.processNextWeakRound();
87 87

	
88 88
    bf_test.start();
89 89
    bf_test.checkedStart();
90 90
    bf_test.limitedStart(k);
91 91

	
92 92
    l  = const_bf_test.dist(t);
93 93
    e  = const_bf_test.predArc(t);
94 94
    s  = const_bf_test.predNode(t);
95 95
    b  = const_bf_test.reached(t);
96 96
    d  = const_bf_test.distMap();
97 97
    p  = const_bf_test.predMap();
98 98
    pp = const_bf_test.path(t);
99 99
    pp = const_bf_test.negativeCycle();
100 100
    
101 101
    for (BF::ActiveIt it(const_bf_test); it != INVALID; ++it) {}
102 102
  }
103 103
  {
104 104
    BF::SetPredMap<concepts::ReadWriteMap<Node,Arc> >
105 105
      ::SetDistMap<concepts::ReadWriteMap<Node,Value> >
106 106
      ::SetOperationTraits<BellmanFordDefaultOperationTraits<Value> >
107
      ::SetOperationTraits<BellmanFordToleranceOperationTraits<Value, 0> >
107 108
      ::Create bf_test(gr,length);
108 109

	
109 110
    LengthMap length_map;
110 111
    concepts::ReadWriteMap<Node,Arc> pred_map;
111 112
    concepts::ReadWriteMap<Node,Value> dist_map;
112 113
    
113 114
    bf_test
114 115
      .lengthMap(length_map)
115 116
      .predMap(pred_map)
116 117
      .distMap(dist_map);
117 118

	
118 119
    bf_test.run(s);
119 120
    bf_test.run(s,k);
120 121

	
121 122
    bf_test.init();
122 123
    bf_test.addSource(s);
123 124
    bf_test.addSource(s, 1);
124 125
    b = bf_test.processNextRound();
125 126
    b = bf_test.processNextWeakRound();
126 127

	
127 128
    bf_test.start();
128 129
    bf_test.checkedStart();
129 130
    bf_test.limitedStart(k);
130 131

	
131 132
    l  = bf_test.dist(t);
132 133
    e  = bf_test.predArc(t);
133 134
    s  = bf_test.predNode(t);
134 135
    b  = bf_test.reached(t);
135 136
    pp = bf_test.path(t);
136 137
    pp = bf_test.negativeCycle();
137 138
  }
138 139
}
139 140

	
140 141
void checkBellmanFordFunctionCompile()
141 142
{
142 143
  typedef int Value;
143 144
  typedef concepts::Digraph Digraph;
144 145
  typedef Digraph::Arc Arc;
145 146
  typedef Digraph::Node Node;
146 147
  typedef concepts::ReadMap<Digraph::Arc,Value> LengthMap;
147 148

	
148 149
  Digraph g;
149 150
  bool b;
150 151
  bellmanFord(g,LengthMap()).run(Node());
151 152
  b = bellmanFord(g,LengthMap()).run(Node(),Node());
152 153
  bellmanFord(g,LengthMap())
153 154
    .predMap(concepts::ReadWriteMap<Node,Arc>())
154 155
    .distMap(concepts::ReadWriteMap<Node,Value>())
155 156
    .run(Node());
156 157
  b=bellmanFord(g,LengthMap())
157 158
    .predMap(concepts::ReadWriteMap<Node,Arc>())
158 159
    .distMap(concepts::ReadWriteMap<Node,Value>())
159 160
    .path(concepts::Path<Digraph>())
160 161
    .dist(Value())
161 162
    .run(Node(),Node());
162 163
}
163 164

	
164 165

	
165 166
template <typename Digraph, typename Value>
166 167
void checkBellmanFord() {
167 168
  TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
168 169
  typedef typename Digraph::template ArcMap<Value> LengthMap;
169 170

	
170 171
  Digraph gr;
171 172
  Node s, t;
172 173
  LengthMap length(gr);
173 174

	
174 175
  std::istringstream input(test_lgf);
175 176
  digraphReader(gr, input).
176 177
    arcMap("length", length).
177 178
    node("source", s).
178 179
    node("target", t).
179 180
    run();
180 181

	
181 182
  BellmanFord<Digraph, LengthMap>
182 183
    bf(gr, length);
183 184
  bf.run(s);
184 185
  Path<Digraph> p = bf.path(t);
185 186

	
186 187
  check(bf.reached(t) && bf.dist(t) == -1, "Bellman-Ford found a wrong path.");
187 188
  check(p.length() == 3, "path() found a wrong path.");
188 189
  check(checkPath(gr, p), "path() found a wrong path.");
189 190
  check(pathSource(gr, p) == s, "path() found a wrong path.");
190 191
  check(pathTarget(gr, p) == t, "path() found a wrong path.");
191 192
  
192 193
  ListPath<Digraph> path;
193 194
  Value dist;
194 195
  bool reached = bellmanFord(gr,length).path(path).dist(dist).run(s,t);
195 196

	
196 197
  check(reached && dist == -1, "Bellman-Ford found a wrong path.");
197 198
  check(path.length() == 3, "path() found a wrong path.");
198 199
  check(checkPath(gr, path), "path() found a wrong path.");
199 200
  check(pathSource(gr, path) == s, "path() found a wrong path.");
200 201
  check(pathTarget(gr, path) == t, "path() found a wrong path.");
201 202

	
202 203
  for(ArcIt e(gr); e!=INVALID; ++e) {
203 204
    Node u=gr.source(e);
204 205
    Node v=gr.target(e);
205 206
    check(!bf.reached(u) || (bf.dist(v) - bf.dist(u) <= length[e]),
206 207
          "Wrong output. dist(target)-dist(source)-arc_length=" <<
207 208
          bf.dist(v) - bf.dist(u) - length[e]);
208 209
  }
209 210

	
210 211
  for(NodeIt v(gr); v!=INVALID; ++v) {
211 212
    if (bf.reached(v)) {
212 213
      check(v==s || bf.predArc(v)!=INVALID, "Wrong tree.");
213 214
      if (bf.predArc(v)!=INVALID ) {
214 215
        Arc e=bf.predArc(v);
215 216
        Node u=gr.source(e);
216 217
        check(u==bf.predNode(v),"Wrong tree.");
217 218
        check(bf.dist(v) - bf.dist(u) == length[e],
218 219
              "Wrong distance! Difference: " <<
219 220
              bf.dist(v) - bf.dist(u) - length[e]);
220 221
      }
221 222
    }
222 223
  }
223 224
}
224 225

	
225 226
void checkBellmanFordNegativeCycle() {
226 227
  DIGRAPH_TYPEDEFS(SmartDigraph);
227 228

	
228 229
  SmartDigraph gr;
229 230
  IntArcMap length(gr);
230 231
  
231 232
  Node n1 = gr.addNode();
232 233
  Node n2 = gr.addNode();
233 234
  Node n3 = gr.addNode();
234 235
  Node n4 = gr.addNode();
235 236
  
236 237
  Arc a1 = gr.addArc(n1, n2);
237 238
  Arc a2 = gr.addArc(n2, n2);
238 239
  
239 240
  length[a1] = 2;
240 241
  length[a2] = -1;
241 242
  
242 243
  {
243 244
    BellmanFord<SmartDigraph, IntArcMap> bf(gr, length);
244 245
    bf.run(n1);
245 246
    StaticPath<SmartDigraph> p = bf.negativeCycle();
246 247
    check(p.length() == 1 && p.front() == p.back() && p.front() == a2,
247 248
          "Wrong negative cycle.");
248 249
  }
249 250
 
250 251
  length[a2] = 0;
251 252
  
252 253
  {
253 254
    BellmanFord<SmartDigraph, IntArcMap> bf(gr, length);
254 255
    bf.run(n1);
255 256
    check(bf.negativeCycle().empty(),
256 257
          "Negative cycle should not be found.");
257 258
  }
258 259
  
259 260
  length[gr.addArc(n1, n3)] = 5;
260 261
  length[gr.addArc(n4, n3)] = 1;
261 262
  length[gr.addArc(n2, n4)] = 2;
262 263
  length[gr.addArc(n3, n2)] = -4;
263 264
  
264 265
  {
265 266
    BellmanFord<SmartDigraph, IntArcMap> bf(gr, length);
266 267
    bf.init();
267 268
    bf.addSource(n1);
268 269
    for (int i = 0; i < 4; ++i) {
269 270
      check(bf.negativeCycle().empty(),
270 271
            "Negative cycle should not be found.");
271 272
      bf.processNextRound();
272 273
    }
273 274
    StaticPath<SmartDigraph> p = bf.negativeCycle();
274 275
    check(p.length() == 3, "Wrong negative cycle.");
275 276
    check(length[p.nth(0)] + length[p.nth(1)] + length[p.nth(2)] == -1,
276 277
          "Wrong negative cycle.");
277 278
  }
278 279
}
279 280

	
280 281
int main() {
281 282
  checkBellmanFord<ListDigraph, int>();
282 283
  checkBellmanFord<SmartDigraph, double>();
283 284
  checkBellmanFordNegativeCycle();
284 285
  return 0;
285 286
}
0 comments (0 inline)