↑ Collapse diff ↑
Show white space 4096 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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2011
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
namespace lemon {
20 20
/*!
21 21

	
22 22

	
23 23

	
24 24
\page lgf-format LEMON Graph Format (LGF)
25 25

	
26 26
The \e LGF is a <em>column oriented</em>
27 27
file format for storing graphs and associated data like
28 28
node and edge maps.
29 29

	
30 30
Each line with \c '#' first non-whitespace
31 31
character is considered as a comment line.
32 32

	
33 33
Otherwise the file consists of sections starting with
34 34
a header line. The header lines starts with an \c '@' character followed by the
35 35
type of section. The standard section types are \c \@nodes, \c
36 36
\@arcs and \c \@edges
37 37
and \@attributes. Each header line may also have an optional
38 38
\e name, which can be use to distinguish the sections of the same
39 39
type.
40 40

	
41 41
The standard sections are column oriented, each line consists of
42 42
<em>token</em>s separated by whitespaces. A token can be \e plain or
43 43
\e quoted. A plain token is just a sequence of non-whitespace characters,
44 44
while a quoted token is a
45 45
character sequence surrounded by double quotes, and it can also
46 46
contain whitespaces and escape sequences.
47 47

	
48 48
The \c \@nodes section describes a set of nodes and associated
49 49
maps. The first is a header line, its columns are the names of the
50 50
maps appearing in the following lines.
51 51
One of the maps must be called \c
52 52
"label", which plays special role in the file.
53 53
The following
54 54
non-empty lines until the next section describes nodes of the
55 55
graph. Each line contains the values of the node maps
56 56
associated to the current node.
57 57

	
58 58
\code
59 59
 @nodes
60 60
 label  coordinates  size    title
61 61
 1      (10,20)      10      "First node"
62 62
 2      (80,80)      8       "Second node"
63 63
 3      (40,10)      10      "Third node"
64 64
\endcode
65 65

	
66 66
The \c \@arcs section is very similar to the \c \@nodes section, it
67 67
again starts with a header line describing the names of the maps, but
68 68
the \c "label" map is not obligatory here. The following lines
69 69
describe the arcs. The first two tokens of each line are the source
70 70
and the target node of the arc, respectively, then come the map
71 71
values. The source and target tokens must be node labels.
72 72

	
73 73
\code
74 74
 @arcs
75 75
         capacity
76 76
 1   2   16
77 77
 1   3   12
78 78
 2   3   18
79 79
\endcode
80 80

	
81 81
If there is no map in the \c \@arcs section at all, then it must be
82 82
indicated by a sole '-' sign in the first line.
83 83

	
84 84
\code
85 85
 @arcs
86 86
         -
87 87
 1   2
88 88
 1   3
89 89
 2   3
90 90
\endcode
91 91

	
92 92
The \c \@edges is just a synonym of \c \@arcs. The \@arcs section can
93 93
also store the edge set of an undirected graph. In such case there is
94 94
a conventional method for store arc maps in the file, if two columns
95 95
have the same caption with \c '+' and \c '-' prefix, then these columns
96 96
can be regarded as the values of an arc map.
97 97

	
98 98
The \c \@attributes section contains key-value pairs, each line
99 99
consists of two tokens, an attribute name, and then an attribute
100 100
value. The value of the attribute could be also a label value of a
101 101
node or an edge, or even an edge label prefixed with \c '+' or \c '-',
102 102
which regards to the forward or backward directed arc of the
103 103
corresponding edge.
104 104

	
105 105
\code
106 106
 @attributes
107 107
 source 1
108 108
 target 3
109 109
 caption "LEMON test digraph"
110 110
\endcode
111 111

	
112 112
The \e LGF can contain extra sections, but there is no restriction on
113 113
the format of such sections.
114 114

	
115 115
*/
116 116
}
117 117

	
118 118
//  LocalWords:  whitespace whitespaces
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2011
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_GRAPH_ADAPTOR_EXTENDER_H
20 20
#define LEMON_BITS_GRAPH_ADAPTOR_EXTENDER_H
21 21

	
22 22
#include <lemon/core.h>
23 23
#include <lemon/error.h>
24 24

	
25 25
namespace lemon {
26 26

	
27 27
  template <typename _Digraph>
28 28
  class DigraphAdaptorExtender : public _Digraph {
29 29
    typedef _Digraph Parent;
30 30

	
31 31
  public:
32 32

	
33 33
    typedef _Digraph Digraph;
34 34
    typedef DigraphAdaptorExtender Adaptor;
35 35

	
36 36
    // Base extensions
37 37

	
38 38
    typedef typename Parent::Node Node;
39 39
    typedef typename Parent::Arc Arc;
40 40

	
41 41
    int maxId(Node) const {
42 42
      return Parent::maxNodeId();
43 43
    }
44 44

	
45 45
    int maxId(Arc) const {
46 46
      return Parent::maxArcId();
47 47
    }
48 48

	
49 49
    Node fromId(int id, Node) const {
50 50
      return Parent::nodeFromId(id);
51 51
    }
52 52

	
53 53
    Arc fromId(int id, Arc) const {
54 54
      return Parent::arcFromId(id);
55 55
    }
56 56

	
57 57
    Node oppositeNode(const Node &n, const Arc &e) const {
58 58
      if (n == Parent::source(e))
59 59
        return Parent::target(e);
60 60
      else if(n==Parent::target(e))
61 61
        return Parent::source(e);
62 62
      else
63 63
        return INVALID;
64 64
    }
65 65

	
66 66
    class NodeIt : public Node {
67 67
      const Adaptor* _adaptor;
68 68
    public:
69 69

	
70 70
      NodeIt() {}
71 71

	
72 72
      NodeIt(Invalid i) : Node(i) { }
73 73

	
74 74
      explicit NodeIt(const Adaptor& adaptor) : _adaptor(&adaptor) {
75 75
        _adaptor->first(static_cast<Node&>(*this));
76 76
      }
77 77

	
78 78
      NodeIt(const Adaptor& adaptor, const Node& node)
79 79
        : Node(node), _adaptor(&adaptor) {}
80 80

	
81 81
      NodeIt& operator++() {
82 82
        _adaptor->next(*this);
83 83
        return *this;
84 84
      }
85 85

	
86 86
    };
87 87

	
88 88

	
89 89
    class ArcIt : public Arc {
90 90
      const Adaptor* _adaptor;
91 91
    public:
92 92

	
93 93
      ArcIt() { }
94 94

	
95 95
      ArcIt(Invalid i) : Arc(i) { }
96 96

	
97 97
      explicit ArcIt(const Adaptor& adaptor) : _adaptor(&adaptor) {
98 98
        _adaptor->first(static_cast<Arc&>(*this));
99 99
      }
100 100

	
101 101
      ArcIt(const Adaptor& adaptor, const Arc& e) :
102 102
        Arc(e), _adaptor(&adaptor) { }
103 103

	
104 104
      ArcIt& operator++() {
105 105
        _adaptor->next(*this);
106 106
        return *this;
107 107
      }
108 108

	
109 109
    };
110 110

	
111 111

	
112 112
    class OutArcIt : public Arc {
113 113
      const Adaptor* _adaptor;
114 114
    public:
115 115

	
116 116
      OutArcIt() { }
117 117

	
118 118
      OutArcIt(Invalid i) : Arc(i) { }
119 119

	
120 120
      OutArcIt(const Adaptor& adaptor, const Node& node)
121 121
        : _adaptor(&adaptor) {
122 122
        _adaptor->firstOut(*this, node);
123 123
      }
124 124

	
125 125
      OutArcIt(const Adaptor& adaptor, const Arc& arc)
126 126
        : Arc(arc), _adaptor(&adaptor) {}
127 127

	
128 128
      OutArcIt& operator++() {
129 129
        _adaptor->nextOut(*this);
130 130
        return *this;
131 131
      }
132 132

	
133 133
    };
134 134

	
135 135

	
136 136
    class InArcIt : public Arc {
137 137
      const Adaptor* _adaptor;
138 138
    public:
139 139

	
140 140
      InArcIt() { }
141 141

	
142 142
      InArcIt(Invalid i) : Arc(i) { }
143 143

	
144 144
      InArcIt(const Adaptor& adaptor, const Node& node)
145 145
        : _adaptor(&adaptor) {
146 146
        _adaptor->firstIn(*this, node);
147 147
      }
148 148

	
149 149
      InArcIt(const Adaptor& adaptor, const Arc& arc) :
150 150
        Arc(arc), _adaptor(&adaptor) {}
151 151

	
152 152
      InArcIt& operator++() {
153 153
        _adaptor->nextIn(*this);
154 154
        return *this;
155 155
      }
156 156

	
157 157
    };
158 158

	
159 159
    Node baseNode(const OutArcIt &e) const {
160 160
      return Parent::source(e);
161 161
    }
162 162
    Node runningNode(const OutArcIt &e) const {
163 163
      return Parent::target(e);
164 164
    }
165 165

	
166 166
    Node baseNode(const InArcIt &e) const {
167 167
      return Parent::target(e);
168 168
    }
169 169
    Node runningNode(const InArcIt &e) const {
170 170
      return Parent::source(e);
171 171
    }
172 172

	
173 173
  };
174 174

	
175 175
  template <typename _Graph>
176 176
  class GraphAdaptorExtender : public _Graph {
177 177
    typedef _Graph Parent;
178 178

	
179 179
  public:
180 180

	
181 181
    typedef _Graph Graph;
182 182
    typedef GraphAdaptorExtender Adaptor;
183 183

	
184 184
    typedef True UndirectedTag;
185 185

	
186 186
    typedef typename Parent::Node Node;
187 187
    typedef typename Parent::Arc Arc;
188 188
    typedef typename Parent::Edge Edge;
189 189

	
190 190
    // Graph extension
191 191

	
192 192
    int maxId(Node) const {
193 193
      return Parent::maxNodeId();
194 194
    }
195 195

	
196 196
    int maxId(Arc) const {
197 197
      return Parent::maxArcId();
198 198
    }
199 199

	
200 200
    int maxId(Edge) const {
201 201
      return Parent::maxEdgeId();
202 202
    }
203 203

	
204 204
    Node fromId(int id, Node) const {
205 205
      return Parent::nodeFromId(id);
206 206
    }
207 207

	
208 208
    Arc fromId(int id, Arc) const {
209 209
      return Parent::arcFromId(id);
210 210
    }
211 211

	
212 212
    Edge fromId(int id, Edge) const {
213 213
      return Parent::edgeFromId(id);
214 214
    }
215 215

	
216 216
    Node oppositeNode(const Node &n, const Edge &e) const {
217 217
      if( n == Parent::u(e))
218 218
        return Parent::v(e);
219 219
      else if( n == Parent::v(e))
220 220
        return Parent::u(e);
221 221
      else
222 222
        return INVALID;
223 223
    }
224 224

	
225 225
    Arc oppositeArc(const Arc &a) const {
226 226
      return Parent::direct(a, !Parent::direction(a));
227 227
    }
228 228

	
229 229
    using Parent::direct;
230 230
    Arc direct(const Edge &e, const Node &s) const {
231 231
      return Parent::direct(e, Parent::u(e) == s);
232 232
    }
233 233

	
234 234

	
235 235
    class NodeIt : public Node {
236 236
      const Adaptor* _adaptor;
237 237
    public:
238 238

	
239 239
      NodeIt() {}
240 240

	
241 241
      NodeIt(Invalid i) : Node(i) { }
242 242

	
243 243
      explicit NodeIt(const Adaptor& adaptor) : _adaptor(&adaptor) {
244 244
        _adaptor->first(static_cast<Node&>(*this));
245 245
      }
246 246

	
247 247
      NodeIt(const Adaptor& adaptor, const Node& node)
248 248
        : Node(node), _adaptor(&adaptor) {}
249 249

	
250 250
      NodeIt& operator++() {
251 251
        _adaptor->next(*this);
252 252
        return *this;
253 253
      }
254 254

	
255 255
    };
256 256

	
257 257

	
258 258
    class ArcIt : public Arc {
259 259
      const Adaptor* _adaptor;
260 260
    public:
261 261

	
262 262
      ArcIt() { }
263 263

	
264 264
      ArcIt(Invalid i) : Arc(i) { }
265 265

	
266 266
      explicit ArcIt(const Adaptor& adaptor) : _adaptor(&adaptor) {
267 267
        _adaptor->first(static_cast<Arc&>(*this));
268 268
      }
269 269

	
270 270
      ArcIt(const Adaptor& adaptor, const Arc& e) :
271 271
        Arc(e), _adaptor(&adaptor) { }
272 272

	
273 273
      ArcIt& operator++() {
274 274
        _adaptor->next(*this);
275 275
        return *this;
276 276
      }
277 277

	
278 278
    };
279 279

	
280 280

	
281 281
    class OutArcIt : public Arc {
282 282
      const Adaptor* _adaptor;
283 283
    public:
284 284

	
285 285
      OutArcIt() { }
286 286

	
287 287
      OutArcIt(Invalid i) : Arc(i) { }
288 288

	
289 289
      OutArcIt(const Adaptor& adaptor, const Node& node)
290 290
        : _adaptor(&adaptor) {
291 291
        _adaptor->firstOut(*this, node);
292 292
      }
293 293

	
294 294
      OutArcIt(const Adaptor& adaptor, const Arc& arc)
295 295
        : Arc(arc), _adaptor(&adaptor) {}
296 296

	
297 297
      OutArcIt& operator++() {
298 298
        _adaptor->nextOut(*this);
299 299
        return *this;
300 300
      }
301 301

	
302 302
    };
303 303

	
304 304

	
305 305
    class InArcIt : public Arc {
306 306
      const Adaptor* _adaptor;
307 307
    public:
308 308

	
309 309
      InArcIt() { }
310 310

	
311 311
      InArcIt(Invalid i) : Arc(i) { }
312 312

	
313 313
      InArcIt(const Adaptor& adaptor, const Node& node)
314 314
        : _adaptor(&adaptor) {
315 315
        _adaptor->firstIn(*this, node);
316 316
      }
317 317

	
318 318
      InArcIt(const Adaptor& adaptor, const Arc& arc) :
319 319
        Arc(arc), _adaptor(&adaptor) {}
320 320

	
321 321
      InArcIt& operator++() {
322 322
        _adaptor->nextIn(*this);
323 323
        return *this;
324 324
      }
325 325

	
326 326
    };
327 327

	
328 328
    class EdgeIt : public Parent::Edge {
329 329
      const Adaptor* _adaptor;
330 330
    public:
331 331

	
332 332
      EdgeIt() { }
333 333

	
334 334
      EdgeIt(Invalid i) : Edge(i) { }
335 335

	
336 336
      explicit EdgeIt(const Adaptor& adaptor) : _adaptor(&adaptor) {
337 337
        _adaptor->first(static_cast<Edge&>(*this));
338 338
      }
339 339

	
340 340
      EdgeIt(const Adaptor& adaptor, const Edge& e) :
341 341
        Edge(e), _adaptor(&adaptor) { }
342 342

	
343 343
      EdgeIt& operator++() {
344 344
        _adaptor->next(*this);
345 345
        return *this;
346 346
      }
347 347

	
348 348
    };
349 349

	
350 350
    class IncEdgeIt : public Edge {
351 351
      friend class GraphAdaptorExtender;
352 352
      const Adaptor* _adaptor;
353 353
      bool direction;
354 354
    public:
355 355

	
356 356
      IncEdgeIt() { }
357 357

	
358 358
      IncEdgeIt(Invalid i) : Edge(i), direction(false) { }
359 359

	
360 360
      IncEdgeIt(const Adaptor& adaptor, const Node &n) : _adaptor(&adaptor) {
361 361
        _adaptor->firstInc(static_cast<Edge&>(*this), direction, n);
362 362
      }
363 363

	
364 364
      IncEdgeIt(const Adaptor& adaptor, const Edge &e, const Node &n)
365 365
        : _adaptor(&adaptor), Edge(e) {
366 366
        direction = (_adaptor->u(e) == n);
367 367
      }
368 368

	
369 369
      IncEdgeIt& operator++() {
370 370
        _adaptor->nextInc(*this, direction);
371 371
        return *this;
372 372
      }
373 373
    };
374 374

	
375 375
    Node baseNode(const OutArcIt &a) const {
376 376
      return Parent::source(a);
377 377
    }
378 378
    Node runningNode(const OutArcIt &a) const {
379 379
      return Parent::target(a);
380 380
    }
381 381

	
382 382
    Node baseNode(const InArcIt &a) const {
383 383
      return Parent::target(a);
384 384
    }
385 385
    Node runningNode(const InArcIt &a) const {
386 386
      return Parent::source(a);
387 387
    }
388 388

	
389 389
    Node baseNode(const IncEdgeIt &e) const {
390 390
      return e.direction ? Parent::u(e) : Parent::v(e);
391 391
    }
392 392
    Node runningNode(const IncEdgeIt &e) const {
393 393
      return e.direction ? Parent::v(e) : Parent::u(e);
394 394
    }
395 395

	
396 396
  };
397 397

	
398 398
}
399 399

	
400 400

	
401 401
#endif
Show white space 4096 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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2011
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_PATH_DUMP_H
20 20
#define LEMON_BITS_PATH_DUMP_H
21 21

	
22 22
#include <lemon/core.h>
23 23
#include <lemon/concept_check.h>
24 24

	
25 25
namespace lemon {
26 26

	
27 27
  template <typename _Digraph, typename _PredMap>
28 28
  class PredMapPath {
29 29
  public:
30 30
    typedef True RevPathTag;
31 31

	
32 32
    typedef _Digraph Digraph;
33 33
    typedef typename Digraph::Arc Arc;
34 34
    typedef _PredMap PredMap;
35 35

	
36 36
    PredMapPath(const Digraph& _digraph, const PredMap& _predMap,
37 37
                typename Digraph::Node _target)
38 38
      : digraph(_digraph), predMap(_predMap), target(_target) {}
39 39

	
40 40
    int length() const {
41 41
      int len = 0;
42 42
      typename Digraph::Node node = target;
43 43
      typename Digraph::Arc arc;
44 44
      while ((arc = predMap[node]) != INVALID) {
45 45
        node = digraph.source(arc);
46 46
        ++len;
47 47
      }
48 48
      return len;
49 49
    }
50 50

	
51 51
    bool empty() const {
52 52
      return predMap[target] == INVALID;
53 53
    }
54 54

	
55 55
    class RevArcIt {
56 56
    public:
57 57
      RevArcIt() {}
58 58
      RevArcIt(Invalid) : path(0), current(INVALID) {}
59 59
      RevArcIt(const PredMapPath& _path)
60 60
        : path(&_path), current(_path.target) {
61 61
        if (path->predMap[current] == INVALID) current = INVALID;
62 62
      }
63 63

	
64 64
      operator const typename Digraph::Arc() const {
65 65
        return path->predMap[current];
66 66
      }
67 67

	
68 68
      RevArcIt& operator++() {
69 69
        current = path->digraph.source(path->predMap[current]);
70 70
        if (path->predMap[current] == INVALID) current = INVALID;
71 71
        return *this;
72 72
      }
73 73

	
74 74
      bool operator==(const RevArcIt& e) const {
75 75
        return current == e.current;
76 76
      }
77 77

	
78 78
      bool operator!=(const RevArcIt& e) const {
79 79
        return current != e.current;
80 80
      }
81 81

	
82 82
      bool operator<(const RevArcIt& e) const {
83 83
        return current < e.current;
84 84
      }
85 85

	
86 86
    private:
87 87
      const PredMapPath* path;
88 88
      typename Digraph::Node current;
89 89
    };
90 90

	
91 91
  private:
92 92
    const Digraph& digraph;
93 93
    const PredMap& predMap;
94 94
    typename Digraph::Node target;
95 95
  };
96 96

	
97 97

	
98 98
  template <typename _Digraph, typename _PredMatrixMap>
99 99
  class PredMatrixMapPath {
100 100
  public:
101 101
    typedef True RevPathTag;
102 102

	
103 103
    typedef _Digraph Digraph;
104 104
    typedef typename Digraph::Arc Arc;
105 105
    typedef _PredMatrixMap PredMatrixMap;
106 106

	
107 107
    PredMatrixMapPath(const Digraph& _digraph,
108 108
                      const PredMatrixMap& _predMatrixMap,
109 109
                      typename Digraph::Node _source,
110 110
                      typename Digraph::Node _target)
111 111
      : digraph(_digraph), predMatrixMap(_predMatrixMap),
112 112
        source(_source), target(_target) {}
113 113

	
114 114
    int length() const {
115 115
      int len = 0;
116 116
      typename Digraph::Node node = target;
117 117
      typename Digraph::Arc arc;
118 118
      while ((arc = predMatrixMap(source, node)) != INVALID) {
119 119
        node = digraph.source(arc);
120 120
        ++len;
121 121
      }
122 122
      return len;
123 123
    }
124 124

	
125 125
    bool empty() const {
126 126
      return predMatrixMap(source, target) == INVALID;
127 127
    }
128 128

	
129 129
    class RevArcIt {
130 130
    public:
131 131
      RevArcIt() {}
132 132
      RevArcIt(Invalid) : path(0), current(INVALID) {}
133 133
      RevArcIt(const PredMatrixMapPath& _path)
134 134
        : path(&_path), current(_path.target) {
135 135
        if (path->predMatrixMap(path->source, current) == INVALID)
136 136
          current = INVALID;
137 137
      }
138 138

	
139 139
      operator const typename Digraph::Arc() const {
140 140
        return path->predMatrixMap(path->source, current);
141 141
      }
142 142

	
143 143
      RevArcIt& operator++() {
144 144
        current =
145 145
          path->digraph.source(path->predMatrixMap(path->source, current));
146 146
        if (path->predMatrixMap(path->source, current) == INVALID)
147 147
          current = INVALID;
148 148
        return *this;
149 149
      }
150 150

	
151 151
      bool operator==(const RevArcIt& e) const {
152 152
        return current == e.current;
153 153
      }
154 154

	
155 155
      bool operator!=(const RevArcIt& e) const {
156 156
        return current != e.current;
157 157
      }
158 158

	
159 159
      bool operator<(const RevArcIt& e) const {
160 160
        return current < e.current;
161 161
      }
162 162

	
163 163
    private:
164 164
      const PredMatrixMapPath* path;
165 165
      typename Digraph::Node current;
166 166
    };
167 167

	
168 168
  private:
169 169
    const Digraph& digraph;
170 170
    const PredMatrixMap& predMatrixMap;
171 171
    typename Digraph::Node source;
172 172
    typename Digraph::Node target;
173 173
  };
174 174

	
175 175
}
176 176

	
177 177
#endif
Show white space 4096 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
 * Copyright (C) 2003-2010
5
 * Copyright (C) 2003-2011
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
///\file
20 20
///\brief Some basic non-inline functions and static global data.
21 21

	
22 22
#include<lemon/bits/windows.h>
23 23

	
24 24
#ifdef WIN32
25 25
#ifndef WIN32_LEAN_AND_MEAN
26 26
#define WIN32_LEAN_AND_MEAN
27 27
#endif
28 28
#ifndef NOMINMAX
29 29
#define NOMINMAX
30 30
#endif
31 31
#ifdef UNICODE
32 32
#undef UNICODE
33 33
#endif
34 34
#include <windows.h>
35 35
#ifdef LOCALE_INVARIANT
36 36
#define MY_LOCALE LOCALE_INVARIANT
37 37
#else
38 38
#define MY_LOCALE LOCALE_NEUTRAL
39 39
#endif
40 40
#else
41 41
#include <unistd.h>
42 42
#include <ctime>
43 43
#ifndef WIN32
44 44
#include <sys/times.h>
45 45
#endif
46 46
#include <sys/time.h>
47 47
#endif
48 48

	
49 49
#include <cmath>
50 50
#include <sstream>
51 51

	
52 52
namespace lemon {
53 53
  namespace bits {
54 54
    void getWinProcTimes(double &rtime,
55 55
                         double &utime, double &stime,
56 56
                         double &cutime, double &cstime)
57 57
    {
58 58
#ifdef WIN32
59 59
      static const double ch = 4294967296.0e-7;
60 60
      static const double cl = 1.0e-7;
61 61

	
62 62
      FILETIME system;
63 63
      GetSystemTimeAsFileTime(&system);
64 64
      rtime = ch * system.dwHighDateTime + cl * system.dwLowDateTime;
65 65

	
66 66
      FILETIME create, exit, kernel, user;
67 67
      if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
68 68
        utime = ch * user.dwHighDateTime + cl * user.dwLowDateTime;
69 69
        stime = ch * kernel.dwHighDateTime + cl * kernel.dwLowDateTime;
70 70
        cutime = 0;
71 71
        cstime = 0;
72 72
      } else {
73 73
        rtime = 0;
74 74
        utime = 0;
75 75
        stime = 0;
76 76
        cutime = 0;
77 77
        cstime = 0;
78 78
      }
79 79
#else
80 80
      timeval tv;
81 81
      gettimeofday(&tv, 0);
82 82
      rtime=tv.tv_sec+double(tv.tv_usec)/1e6;
83 83

	
84 84
      tms ts;
85 85
      double tck=sysconf(_SC_CLK_TCK);
86 86
      times(&ts);
87 87
      utime=ts.tms_utime/tck;
88 88
      stime=ts.tms_stime/tck;
89 89
      cutime=ts.tms_cutime/tck;
90 90
      cstime=ts.tms_cstime/tck;
91 91
#endif
92 92
    }
93 93

	
94 94
    std::string getWinFormattedDate()
95 95
    {
96 96
      std::ostringstream os;
97 97
#ifdef WIN32
98 98
      SYSTEMTIME time;
99 99
      GetSystemTime(&time);
100 100
      char buf1[11], buf2[9], buf3[5];
101 101
          if (GetDateFormat(MY_LOCALE, 0, &time,
102 102
                        ("ddd MMM dd"), buf1, 11) &&
103 103
          GetTimeFormat(MY_LOCALE, 0, &time,
104 104
                        ("HH':'mm':'ss"), buf2, 9) &&
105 105
          GetDateFormat(MY_LOCALE, 0, &time,
106 106
                        ("yyyy"), buf3, 5)) {
107 107
        os << buf1 << ' ' << buf2 << ' ' << buf3;
108 108
      }
109 109
      else os << "unknown";
110 110
#else
111 111
      timeval tv;
112 112
      gettimeofday(&tv, 0);
113 113

	
114 114
      char cbuf[26];
115 115
      ctime_r(&tv.tv_sec,cbuf);
116 116
      os << cbuf;
117 117
#endif
118 118
      return os.str();
119 119
    }
120 120

	
121 121
    int getWinRndSeed()
122 122
    {
123 123
#ifdef WIN32
124 124
      FILETIME time;
125 125
      GetSystemTimeAsFileTime(&time);
126 126
      return GetCurrentProcessId() + time.dwHighDateTime + time.dwLowDateTime;
127 127
#else
128 128
      timeval tv;
129 129
      gettimeofday(&tv, 0);
130 130
      return getpid() + tv.tv_sec + tv.tv_usec;
131 131
#endif
132 132
    }
133 133
  }
134 134
}
Show white space 4096 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
 * Copyright (C) 2003-2010
5
 * Copyright (C) 2003-2011
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_COST_SCALING_H
20 20
#define LEMON_COST_SCALING_H
21 21

	
22 22
/// \ingroup min_cost_flow_algs
23 23
/// \file
24 24
/// \brief Cost scaling algorithm for finding a minimum cost flow.
25 25

	
26 26
#include <vector>
27 27
#include <deque>
28 28
#include <limits>
29 29

	
30 30
#include <lemon/core.h>
31 31
#include <lemon/maps.h>
32 32
#include <lemon/math.h>
33 33
#include <lemon/static_graph.h>
34 34
#include <lemon/circulation.h>
35 35
#include <lemon/bellman_ford.h>
36 36

	
37 37
namespace lemon {
38 38

	
39 39
  /// \brief Default traits class of CostScaling algorithm.
40 40
  ///
41 41
  /// Default traits class of CostScaling algorithm.
42 42
  /// \tparam GR Digraph type.
43 43
  /// \tparam V The number type used for flow amounts, capacity bounds
44 44
  /// and supply values. By default it is \c int.
45 45
  /// \tparam C The number type used for costs and potentials.
46 46
  /// By default it is the same as \c V.
47 47
#ifdef DOXYGEN
48 48
  template <typename GR, typename V = int, typename C = V>
49 49
#else
50 50
  template < typename GR, typename V = int, typename C = V,
51 51
             bool integer = std::numeric_limits<C>::is_integer >
52 52
#endif
53 53
  struct CostScalingDefaultTraits
54 54
  {
55 55
    /// The type of the digraph
56 56
    typedef GR Digraph;
57 57
    /// The type of the flow amounts, capacity bounds and supply values
58 58
    typedef V Value;
59 59
    /// The type of the arc costs
60 60
    typedef C Cost;
61 61

	
62 62
    /// \brief The large cost type used for internal computations
63 63
    ///
64 64
    /// The large cost type used for internal computations.
65 65
    /// It is \c long \c long if the \c Cost type is integer,
66 66
    /// otherwise it is \c double.
67 67
    /// \c Cost must be convertible to \c LargeCost.
68 68
    typedef double LargeCost;
69 69
  };
70 70

	
71 71
  // Default traits class for integer cost types
72 72
  template <typename GR, typename V, typename C>
73 73
  struct CostScalingDefaultTraits<GR, V, C, true>
74 74
  {
75 75
    typedef GR Digraph;
76 76
    typedef V Value;
77 77
    typedef C Cost;
78 78
#ifdef LEMON_HAVE_LONG_LONG
79 79
    typedef long long LargeCost;
80 80
#else
81 81
    typedef long LargeCost;
82 82
#endif
83 83
  };
84 84

	
85 85

	
86 86
  /// \addtogroup min_cost_flow_algs
87 87
  /// @{
88 88

	
89 89
  /// \brief Implementation of the Cost Scaling algorithm for
90 90
  /// finding a \ref min_cost_flow "minimum cost flow".
91 91
  ///
92 92
  /// \ref CostScaling implements a cost scaling algorithm that performs
93 93
  /// push/augment and relabel operations for finding a \ref min_cost_flow
94 94
  /// "minimum cost flow" \ref amo93networkflows, \ref goldberg90approximation,
95 95
  /// \ref goldberg97efficient, \ref bunnagel98efficient.
96 96
  /// It is a highly efficient primal-dual solution method, which
97 97
  /// can be viewed as the generalization of the \ref Preflow
98 98
  /// "preflow push-relabel" algorithm for the maximum flow problem.
99 99
  ///
100 100
  /// Most of the parameters of the problem (except for the digraph)
101 101
  /// can be given using separate functions, and the algorithm can be
102 102
  /// executed using the \ref run() function. If some parameters are not
103 103
  /// specified, then default values will be used.
104 104
  ///
105 105
  /// \tparam GR The digraph type the algorithm runs on.
106 106
  /// \tparam V The number type used for flow amounts, capacity bounds
107 107
  /// and supply values in the algorithm. By default, it is \c int.
108 108
  /// \tparam C The number type used for costs and potentials in the
109 109
  /// algorithm. By default, it is the same as \c V.
110 110
  /// \tparam TR The traits class that defines various types used by the
111 111
  /// algorithm. By default, it is \ref CostScalingDefaultTraits
112 112
  /// "CostScalingDefaultTraits<GR, V, C>".
113 113
  /// In most cases, this parameter should not be set directly,
114 114
  /// consider to use the named template parameters instead.
115 115
  ///
116 116
  /// \warning Both number types must be signed and all input data must
117 117
  /// be integer.
118 118
  /// \warning This algorithm does not support negative costs for such
119 119
  /// arcs that have infinite upper bound.
120 120
  ///
121 121
  /// \note %CostScaling provides three different internal methods,
122 122
  /// from which the most efficient one is used by default.
123 123
  /// For more information, see \ref Method.
124 124
#ifdef DOXYGEN
125 125
  template <typename GR, typename V, typename C, typename TR>
126 126
#else
127 127
  template < typename GR, typename V = int, typename C = V,
128 128
             typename TR = CostScalingDefaultTraits<GR, V, C> >
129 129
#endif
130 130
  class CostScaling
131 131
  {
132 132
  public:
133 133

	
134 134
    /// The type of the digraph
135 135
    typedef typename TR::Digraph Digraph;
136 136
    /// The type of the flow amounts, capacity bounds and supply values
137 137
    typedef typename TR::Value Value;
138 138
    /// The type of the arc costs
139 139
    typedef typename TR::Cost Cost;
140 140

	
141 141
    /// \brief The large cost type
142 142
    ///
143 143
    /// The large cost type used for internal computations.
144 144
    /// By default, it is \c long \c long if the \c Cost type is integer,
145 145
    /// otherwise it is \c double.
146 146
    typedef typename TR::LargeCost LargeCost;
147 147

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

	
151 151
  public:
152 152

	
153 153
    /// \brief Problem type constants for the \c run() function.
154 154
    ///
155 155
    /// Enum type containing the problem type constants that can be
156 156
    /// returned by the \ref run() function of the algorithm.
157 157
    enum ProblemType {
158 158
      /// The problem has no feasible solution (flow).
159 159
      INFEASIBLE,
160 160
      /// The problem has optimal solution (i.e. it is feasible and
161 161
      /// bounded), and the algorithm has found optimal flow and node
162 162
      /// potentials (primal and dual solutions).
163 163
      OPTIMAL,
164 164
      /// The digraph contains an arc of negative cost and infinite
165 165
      /// upper bound. It means that the objective function is unbounded
166 166
      /// on that arc, however, note that it could actually be bounded
167 167
      /// over the feasible flows, but this algroithm cannot handle
168 168
      /// these cases.
169 169
      UNBOUNDED
170 170
    };
171 171

	
172 172
    /// \brief Constants for selecting the internal method.
173 173
    ///
174 174
    /// Enum type containing constants for selecting the internal method
175 175
    /// for the \ref run() function.
176 176
    ///
177 177
    /// \ref CostScaling provides three internal methods that differ mainly
178 178
    /// in their base operations, which are used in conjunction with the
179 179
    /// relabel operation.
180 180
    /// By default, the so called \ref PARTIAL_AUGMENT
181 181
    /// "Partial Augment-Relabel" method is used, which proved to be
182 182
    /// the most efficient and the most robust on various test inputs.
183 183
    /// However, the other methods can be selected using the \ref run()
184 184
    /// function with the proper parameter.
185 185
    enum Method {
186 186
      /// Local push operations are used, i.e. flow is moved only on one
187 187
      /// admissible arc at once.
188 188
      PUSH,
189 189
      /// Augment operations are used, i.e. flow is moved on admissible
190 190
      /// paths from a node with excess to a node with deficit.
191 191
      AUGMENT,
192 192
      /// Partial augment operations are used, i.e. flow is moved on
193 193
      /// admissible paths started from a node with excess, but the
194 194
      /// lengths of these paths are limited. This method can be viewed
195 195
      /// as a combined version of the previous two operations.
196 196
      PARTIAL_AUGMENT
197 197
    };
198 198

	
199 199
  private:
200 200

	
201 201
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
202 202

	
203 203
    typedef std::vector<int> IntVector;
204 204
    typedef std::vector<Value> ValueVector;
205 205
    typedef std::vector<Cost> CostVector;
206 206
    typedef std::vector<LargeCost> LargeCostVector;
207 207
    typedef std::vector<char> BoolVector;
208 208
    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
209 209

	
210 210
  private:
211 211

	
212 212
    template <typename KT, typename VT>
213 213
    class StaticVectorMap {
214 214
    public:
215 215
      typedef KT Key;
216 216
      typedef VT Value;
217 217

	
218 218
      StaticVectorMap(std::vector<Value>& v) : _v(v) {}
219 219

	
220 220
      const Value& operator[](const Key& key) const {
221 221
        return _v[StaticDigraph::id(key)];
222 222
      }
223 223

	
224 224
      Value& operator[](const Key& key) {
225 225
        return _v[StaticDigraph::id(key)];
226 226
      }
227 227

	
228 228
      void set(const Key& key, const Value& val) {
229 229
        _v[StaticDigraph::id(key)] = val;
230 230
      }
231 231

	
232 232
    private:
233 233
      std::vector<Value>& _v;
234 234
    };
235 235

	
236 236
    typedef StaticVectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap;
237 237
    typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
238 238

	
239 239
  private:
240 240

	
241 241
    // Data related to the underlying digraph
242 242
    const GR &_graph;
243 243
    int _node_num;
244 244
    int _arc_num;
245 245
    int _res_node_num;
246 246
    int _res_arc_num;
247 247
    int _root;
248 248

	
249 249
    // Parameters of the problem
250 250
    bool _have_lower;
251 251
    Value _sum_supply;
252 252
    int _sup_node_num;
253 253

	
254 254
    // Data structures for storing the digraph
255 255
    IntNodeMap _node_id;
256 256
    IntArcMap _arc_idf;
257 257
    IntArcMap _arc_idb;
258 258
    IntVector _first_out;
259 259
    BoolVector _forward;
260 260
    IntVector _source;
261 261
    IntVector _target;
262 262
    IntVector _reverse;
263 263

	
264 264
    // Node and arc data
265 265
    ValueVector _lower;
266 266
    ValueVector _upper;
267 267
    CostVector _scost;
268 268
    ValueVector _supply;
269 269

	
270 270
    ValueVector _res_cap;
271 271
    LargeCostVector _cost;
272 272
    LargeCostVector _pi;
273 273
    ValueVector _excess;
274 274
    IntVector _next_out;
275 275
    std::deque<int> _active_nodes;
276 276

	
277 277
    // Data for scaling
278 278
    LargeCost _epsilon;
279 279
    int _alpha;
280 280

	
281 281
    IntVector _buckets;
282 282
    IntVector _bucket_next;
283 283
    IntVector _bucket_prev;
284 284
    IntVector _rank;
285 285
    int _max_rank;
286 286

	
287 287
    // Data for a StaticDigraph structure
288 288
    typedef std::pair<int, int> IntPair;
289 289
    StaticDigraph _sgr;
290 290
    std::vector<IntPair> _arc_vec;
291 291
    std::vector<LargeCost> _cost_vec;
292 292
    LargeCostArcMap _cost_map;
293 293
    LargeCostNodeMap _pi_map;
294 294

	
295 295
  public:
296 296

	
297 297
    /// \brief Constant for infinite upper bounds (capacities).
298 298
    ///
299 299
    /// Constant for infinite upper bounds (capacities).
300 300
    /// It is \c std::numeric_limits<Value>::infinity() if available,
301 301
    /// \c std::numeric_limits<Value>::max() otherwise.
302 302
    const Value INF;
303 303

	
304 304
  public:
305 305

	
306 306
    /// \name Named Template Parameters
307 307
    /// @{
308 308

	
309 309
    template <typename T>
310 310
    struct SetLargeCostTraits : public Traits {
311 311
      typedef T LargeCost;
312 312
    };
313 313

	
314 314
    /// \brief \ref named-templ-param "Named parameter" for setting
315 315
    /// \c LargeCost type.
316 316
    ///
317 317
    /// \ref named-templ-param "Named parameter" for setting \c LargeCost
318 318
    /// type, which is used for internal computations in the algorithm.
319 319
    /// \c Cost must be convertible to \c LargeCost.
320 320
    template <typename T>
321 321
    struct SetLargeCost
322 322
      : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
323 323
      typedef  CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
324 324
    };
325 325

	
326 326
    /// @}
327 327

	
328 328
  protected:
329 329

	
330 330
    CostScaling() {}
331 331

	
332 332
  public:
333 333

	
334 334
    /// \brief Constructor.
335 335
    ///
336 336
    /// The constructor of the class.
337 337
    ///
338 338
    /// \param graph The digraph the algorithm runs on.
339 339
    CostScaling(const GR& graph) :
340 340
      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
341 341
      _cost_map(_cost_vec), _pi_map(_pi),
342 342
      INF(std::numeric_limits<Value>::has_infinity ?
343 343
          std::numeric_limits<Value>::infinity() :
344 344
          std::numeric_limits<Value>::max())
345 345
    {
346 346
      // Check the number types
347 347
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
348 348
        "The flow type of CostScaling must be signed");
349 349
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
350 350
        "The cost type of CostScaling must be signed");
351 351

	
352 352
      // Reset data structures
353 353
      reset();
354 354
    }
355 355

	
356 356
    /// \name Parameters
357 357
    /// The parameters of the algorithm can be specified using these
358 358
    /// functions.
359 359

	
360 360
    /// @{
361 361

	
362 362
    /// \brief Set the lower bounds on the arcs.
363 363
    ///
364 364
    /// This function sets the lower bounds on the arcs.
365 365
    /// If it is not used before calling \ref run(), the lower bounds
366 366
    /// will be set to zero on all arcs.
367 367
    ///
368 368
    /// \param map An arc map storing the lower bounds.
369 369
    /// Its \c Value type must be convertible to the \c Value type
370 370
    /// of the algorithm.
371 371
    ///
372 372
    /// \return <tt>(*this)</tt>
373 373
    template <typename LowerMap>
374 374
    CostScaling& lowerMap(const LowerMap& map) {
375 375
      _have_lower = true;
376 376
      for (ArcIt a(_graph); a != INVALID; ++a) {
377 377
        _lower[_arc_idf[a]] = map[a];
378 378
        _lower[_arc_idb[a]] = map[a];
379 379
      }
380 380
      return *this;
381 381
    }
382 382

	
383 383
    /// \brief Set the upper bounds (capacities) on the arcs.
384 384
    ///
385 385
    /// This function sets the upper bounds (capacities) on the arcs.
386 386
    /// If it is not used before calling \ref run(), the upper bounds
387 387
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
388 388
    /// unbounded from above).
389 389
    ///
390 390
    /// \param map An arc map storing the upper bounds.
391 391
    /// Its \c Value type must be convertible to the \c Value type
392 392
    /// of the algorithm.
393 393
    ///
394 394
    /// \return <tt>(*this)</tt>
395 395
    template<typename UpperMap>
396 396
    CostScaling& upperMap(const UpperMap& map) {
397 397
      for (ArcIt a(_graph); a != INVALID; ++a) {
398 398
        _upper[_arc_idf[a]] = map[a];
399 399
      }
400 400
      return *this;
401 401
    }
402 402

	
403 403
    /// \brief Set the costs of the arcs.
404 404
    ///
405 405
    /// This function sets the costs of the arcs.
406 406
    /// If it is not used before calling \ref run(), the costs
407 407
    /// will be set to \c 1 on all arcs.
408 408
    ///
409 409
    /// \param map An arc map storing the costs.
410 410
    /// Its \c Value type must be convertible to the \c Cost type
411 411
    /// of the algorithm.
412 412
    ///
413 413
    /// \return <tt>(*this)</tt>
414 414
    template<typename CostMap>
415 415
    CostScaling& costMap(const CostMap& map) {
416 416
      for (ArcIt a(_graph); a != INVALID; ++a) {
417 417
        _scost[_arc_idf[a]] =  map[a];
418 418
        _scost[_arc_idb[a]] = -map[a];
419 419
      }
420 420
      return *this;
421 421
    }
422 422

	
423 423
    /// \brief Set the supply values of the nodes.
424 424
    ///
425 425
    /// This function sets the supply values of the nodes.
426 426
    /// If neither this function nor \ref stSupply() is used before
427 427
    /// calling \ref run(), the supply of each node will be set to zero.
428 428
    ///
429 429
    /// \param map A node map storing the supply values.
430 430
    /// Its \c Value type must be convertible to the \c Value type
431 431
    /// of the algorithm.
432 432
    ///
433 433
    /// \return <tt>(*this)</tt>
434 434
    template<typename SupplyMap>
435 435
    CostScaling& supplyMap(const SupplyMap& map) {
436 436
      for (NodeIt n(_graph); n != INVALID; ++n) {
437 437
        _supply[_node_id[n]] = map[n];
438 438
      }
439 439
      return *this;
440 440
    }
441 441

	
442 442
    /// \brief Set single source and target nodes and a supply value.
443 443
    ///
444 444
    /// This function sets a single source node and a single target node
445 445
    /// and the required flow value.
446 446
    /// If neither this function nor \ref supplyMap() is used before
447 447
    /// calling \ref run(), the supply of each node will be set to zero.
448 448
    ///
449 449
    /// Using this function has the same effect as using \ref supplyMap()
450 450
    /// with such a map in which \c k is assigned to \c s, \c -k is
451 451
    /// assigned to \c t and all other nodes have zero supply value.
452 452
    ///
453 453
    /// \param s The source node.
454 454
    /// \param t The target node.
455 455
    /// \param k The required amount of flow from node \c s to node \c t
456 456
    /// (i.e. the supply of \c s and the demand of \c t).
457 457
    ///
458 458
    /// \return <tt>(*this)</tt>
459 459
    CostScaling& stSupply(const Node& s, const Node& t, Value k) {
460 460
      for (int i = 0; i != _res_node_num; ++i) {
461 461
        _supply[i] = 0;
462 462
      }
463 463
      _supply[_node_id[s]] =  k;
464 464
      _supply[_node_id[t]] = -k;
465 465
      return *this;
466 466
    }
467 467

	
468 468
    /// @}
469 469

	
470 470
    /// \name Execution control
471 471
    /// The algorithm can be executed using \ref run().
472 472

	
473 473
    /// @{
474 474

	
475 475
    /// \brief Run the algorithm.
476 476
    ///
477 477
    /// This function runs the algorithm.
478 478
    /// The paramters can be specified using functions \ref lowerMap(),
479 479
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
480 480
    /// For example,
481 481
    /// \code
482 482
    ///   CostScaling<ListDigraph> cs(graph);
483 483
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
484 484
    ///     .supplyMap(sup).run();
485 485
    /// \endcode
486 486
    ///
487 487
    /// This function can be called more than once. All the given parameters
488 488
    /// are kept for the next call, unless \ref resetParams() or \ref reset()
489 489
    /// is used, thus only the modified parameters have to be set again.
490 490
    /// If the underlying digraph was also modified after the construction
491 491
    /// of the class (or the last \ref reset() call), then the \ref reset()
492 492
    /// function must be called.
493 493
    ///
494 494
    /// \param method The internal method that will be used in the
495 495
    /// algorithm. For more information, see \ref Method.
496 496
    /// \param factor The cost scaling factor. It must be larger than one.
497 497
    ///
498 498
    /// \return \c INFEASIBLE if no feasible flow exists,
499 499
    /// \n \c OPTIMAL if the problem has optimal solution
500 500
    /// (i.e. it is feasible and bounded), and the algorithm has found
501 501
    /// optimal flow and node potentials (primal and dual solutions),
502 502
    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
503 503
    /// and infinite upper bound. It means that the objective function
504 504
    /// is unbounded on that arc, however, note that it could actually be
505 505
    /// bounded over the feasible flows, but this algroithm cannot handle
506 506
    /// these cases.
507 507
    ///
508 508
    /// \see ProblemType, Method
509 509
    /// \see resetParams(), reset()
510 510
    ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
511 511
      _alpha = factor;
512 512
      ProblemType pt = init();
513 513
      if (pt != OPTIMAL) return pt;
514 514
      start(method);
515 515
      return OPTIMAL;
516 516
    }
517 517

	
518 518
    /// \brief Reset all the parameters that have been given before.
519 519
    ///
520 520
    /// This function resets all the paramaters that have been given
521 521
    /// before using functions \ref lowerMap(), \ref upperMap(),
522 522
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
523 523
    ///
524 524
    /// It is useful for multiple \ref run() calls. Basically, all the given
525 525
    /// parameters are kept for the next \ref run() call, unless
526 526
    /// \ref resetParams() or \ref reset() is used.
527 527
    /// If the underlying digraph was also modified after the construction
528 528
    /// of the class or the last \ref reset() call, then the \ref reset()
529 529
    /// function must be used, otherwise \ref resetParams() is sufficient.
530 530
    ///
531 531
    /// For example,
532 532
    /// \code
533 533
    ///   CostScaling<ListDigraph> cs(graph);
534 534
    ///
535 535
    ///   // First run
536 536
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
537 537
    ///     .supplyMap(sup).run();
538 538
    ///
539 539
    ///   // Run again with modified cost map (resetParams() is not called,
540 540
    ///   // so only the cost map have to be set again)
541 541
    ///   cost[e] += 100;
542 542
    ///   cs.costMap(cost).run();
543 543
    ///
544 544
    ///   // Run again from scratch using resetParams()
545 545
    ///   // (the lower bounds will be set to zero on all arcs)
546 546
    ///   cs.resetParams();
547 547
    ///   cs.upperMap(capacity).costMap(cost)
548 548
    ///     .supplyMap(sup).run();
549 549
    /// \endcode
550 550
    ///
551 551
    /// \return <tt>(*this)</tt>
552 552
    ///
553 553
    /// \see reset(), run()
554 554
    CostScaling& resetParams() {
555 555
      for (int i = 0; i != _res_node_num; ++i) {
556 556
        _supply[i] = 0;
557 557
      }
558 558
      int limit = _first_out[_root];
559 559
      for (int j = 0; j != limit; ++j) {
560 560
        _lower[j] = 0;
561 561
        _upper[j] = INF;
562 562
        _scost[j] = _forward[j] ? 1 : -1;
563 563
      }
564 564
      for (int j = limit; j != _res_arc_num; ++j) {
565 565
        _lower[j] = 0;
566 566
        _upper[j] = INF;
567 567
        _scost[j] = 0;
568 568
        _scost[_reverse[j]] = 0;
569 569
      }
570 570
      _have_lower = false;
571 571
      return *this;
572 572
    }
573 573

	
574 574
    /// \brief Reset all the parameters that have been given before.
575 575
    ///
576 576
    /// This function resets all the paramaters that have been given
577 577
    /// before using functions \ref lowerMap(), \ref upperMap(),
578 578
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
579 579
    ///
580 580
    /// It is useful for multiple run() calls. If this function is not
581 581
    /// used, all the parameters given before are kept for the next
582 582
    /// \ref run() call.
583 583
    /// However, the underlying digraph must not be modified after this
584 584
    /// class have been constructed, since it copies and extends the graph.
585 585
    /// \return <tt>(*this)</tt>
586 586
    CostScaling& reset() {
587 587
      // Resize vectors
588 588
      _node_num = countNodes(_graph);
589 589
      _arc_num = countArcs(_graph);
590 590
      _res_node_num = _node_num + 1;
591 591
      _res_arc_num = 2 * (_arc_num + _node_num);
592 592
      _root = _node_num;
593 593

	
594 594
      _first_out.resize(_res_node_num + 1);
595 595
      _forward.resize(_res_arc_num);
596 596
      _source.resize(_res_arc_num);
597 597
      _target.resize(_res_arc_num);
598 598
      _reverse.resize(_res_arc_num);
599 599

	
600 600
      _lower.resize(_res_arc_num);
601 601
      _upper.resize(_res_arc_num);
602 602
      _scost.resize(_res_arc_num);
603 603
      _supply.resize(_res_node_num);
604 604

	
605 605
      _res_cap.resize(_res_arc_num);
606 606
      _cost.resize(_res_arc_num);
607 607
      _pi.resize(_res_node_num);
608 608
      _excess.resize(_res_node_num);
609 609
      _next_out.resize(_res_node_num);
610 610

	
611 611
      _arc_vec.reserve(_res_arc_num);
612 612
      _cost_vec.reserve(_res_arc_num);
613 613

	
614 614
      // Copy the graph
615 615
      int i = 0, j = 0, k = 2 * _arc_num + _node_num;
616 616
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
617 617
        _node_id[n] = i;
618 618
      }
619 619
      i = 0;
620 620
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
621 621
        _first_out[i] = j;
622 622
        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
623 623
          _arc_idf[a] = j;
624 624
          _forward[j] = true;
625 625
          _source[j] = i;
626 626
          _target[j] = _node_id[_graph.runningNode(a)];
627 627
        }
628 628
        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
629 629
          _arc_idb[a] = j;
630 630
          _forward[j] = false;
631 631
          _source[j] = i;
632 632
          _target[j] = _node_id[_graph.runningNode(a)];
633 633
        }
634 634
        _forward[j] = false;
635 635
        _source[j] = i;
636 636
        _target[j] = _root;
637 637
        _reverse[j] = k;
638 638
        _forward[k] = true;
639 639
        _source[k] = _root;
640 640
        _target[k] = i;
641 641
        _reverse[k] = j;
642 642
        ++j; ++k;
643 643
      }
644 644
      _first_out[i] = j;
645 645
      _first_out[_res_node_num] = k;
646 646
      for (ArcIt a(_graph); a != INVALID; ++a) {
647 647
        int fi = _arc_idf[a];
648 648
        int bi = _arc_idb[a];
649 649
        _reverse[fi] = bi;
650 650
        _reverse[bi] = fi;
651 651
      }
652 652

	
653 653
      // Reset parameters
654 654
      resetParams();
655 655
      return *this;
656 656
    }
657 657

	
658 658
    /// @}
659 659

	
660 660
    /// \name Query Functions
661 661
    /// The results of the algorithm can be obtained using these
662 662
    /// functions.\n
663 663
    /// The \ref run() function must be called before using them.
664 664

	
665 665
    /// @{
666 666

	
667 667
    /// \brief Return the total cost of the found flow.
668 668
    ///
669 669
    /// This function returns the total cost of the found flow.
670 670
    /// Its complexity is O(e).
671 671
    ///
672 672
    /// \note The return type of the function can be specified as a
673 673
    /// template parameter. For example,
674 674
    /// \code
675 675
    ///   cs.totalCost<double>();
676 676
    /// \endcode
677 677
    /// It is useful if the total cost cannot be stored in the \c Cost
678 678
    /// type of the algorithm, which is the default return type of the
679 679
    /// function.
680 680
    ///
681 681
    /// \pre \ref run() must be called before using this function.
682 682
    template <typename Number>
683 683
    Number totalCost() const {
684 684
      Number c = 0;
685 685
      for (ArcIt a(_graph); a != INVALID; ++a) {
686 686
        int i = _arc_idb[a];
687 687
        c += static_cast<Number>(_res_cap[i]) *
688 688
             (-static_cast<Number>(_scost[i]));
689 689
      }
690 690
      return c;
691 691
    }
692 692

	
693 693
#ifndef DOXYGEN
694 694
    Cost totalCost() const {
695 695
      return totalCost<Cost>();
696 696
    }
697 697
#endif
698 698

	
699 699
    /// \brief Return the flow on the given arc.
700 700
    ///
701 701
    /// This function returns the flow on the given arc.
702 702
    ///
703 703
    /// \pre \ref run() must be called before using this function.
704 704
    Value flow(const Arc& a) const {
705 705
      return _res_cap[_arc_idb[a]];
706 706
    }
707 707

	
708 708
    /// \brief Return the flow map (the primal solution).
709 709
    ///
710 710
    /// This function copies the flow value on each arc into the given
711 711
    /// map. The \c Value type of the algorithm must be convertible to
712 712
    /// the \c Value type of the map.
713 713
    ///
714 714
    /// \pre \ref run() must be called before using this function.
715 715
    template <typename FlowMap>
716 716
    void flowMap(FlowMap &map) const {
717 717
      for (ArcIt a(_graph); a != INVALID; ++a) {
718 718
        map.set(a, _res_cap[_arc_idb[a]]);
719 719
      }
720 720
    }
721 721

	
722 722
    /// \brief Return the potential (dual value) of the given node.
723 723
    ///
724 724
    /// This function returns the potential (dual value) of the
725 725
    /// given node.
726 726
    ///
727 727
    /// \pre \ref run() must be called before using this function.
728 728
    Cost potential(const Node& n) const {
729 729
      return static_cast<Cost>(_pi[_node_id[n]]);
730 730
    }
731 731

	
732 732
    /// \brief Return the potential map (the dual solution).
733 733
    ///
734 734
    /// This function copies the potential (dual value) of each node
735 735
    /// into the given map.
736 736
    /// The \c Cost type of the algorithm must be convertible to the
737 737
    /// \c Value type of the map.
738 738
    ///
739 739
    /// \pre \ref run() must be called before using this function.
740 740
    template <typename PotentialMap>
741 741
    void potentialMap(PotentialMap &map) const {
742 742
      for (NodeIt n(_graph); n != INVALID; ++n) {
743 743
        map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
744 744
      }
745 745
    }
746 746

	
747 747
    /// @}
748 748

	
749 749
  private:
750 750

	
751 751
    // Initialize the algorithm
752 752
    ProblemType init() {
753 753
      if (_res_node_num <= 1) return INFEASIBLE;
754 754

	
755 755
      // Check the sum of supply values
756 756
      _sum_supply = 0;
757 757
      for (int i = 0; i != _root; ++i) {
758 758
        _sum_supply += _supply[i];
759 759
      }
760 760
      if (_sum_supply > 0) return INFEASIBLE;
761 761

	
762 762

	
763 763
      // Initialize vectors
764 764
      for (int i = 0; i != _res_node_num; ++i) {
765 765
        _pi[i] = 0;
766 766
        _excess[i] = _supply[i];
767 767
      }
768 768

	
769 769
      // Remove infinite upper bounds and check negative arcs
770 770
      const Value MAX = std::numeric_limits<Value>::max();
771 771
      int last_out;
772 772
      if (_have_lower) {
773 773
        for (int i = 0; i != _root; ++i) {
774 774
          last_out = _first_out[i+1];
775 775
          for (int j = _first_out[i]; j != last_out; ++j) {
776 776
            if (_forward[j]) {
777 777
              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
778 778
              if (c >= MAX) return UNBOUNDED;
779 779
              _excess[i] -= c;
780 780
              _excess[_target[j]] += c;
781 781
            }
782 782
          }
783 783
        }
784 784
      } else {
785 785
        for (int i = 0; i != _root; ++i) {
786 786
          last_out = _first_out[i+1];
787 787
          for (int j = _first_out[i]; j != last_out; ++j) {
788 788
            if (_forward[j] && _scost[j] < 0) {
789 789
              Value c = _upper[j];
790 790
              if (c >= MAX) return UNBOUNDED;
791 791
              _excess[i] -= c;
792 792
              _excess[_target[j]] += c;
793 793
            }
794 794
          }
795 795
        }
796 796
      }
797 797
      Value ex, max_cap = 0;
798 798
      for (int i = 0; i != _res_node_num; ++i) {
799 799
        ex = _excess[i];
800 800
        _excess[i] = 0;
801 801
        if (ex < 0) max_cap -= ex;
802 802
      }
803 803
      for (int j = 0; j != _res_arc_num; ++j) {
804 804
        if (_upper[j] >= MAX) _upper[j] = max_cap;
805 805
      }
806 806

	
807 807
      // Initialize the large cost vector and the epsilon parameter
808 808
      _epsilon = 0;
809 809
      LargeCost lc;
810 810
      for (int i = 0; i != _root; ++i) {
811 811
        last_out = _first_out[i+1];
812 812
        for (int j = _first_out[i]; j != last_out; ++j) {
813 813
          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
814 814
          _cost[j] = lc;
815 815
          if (lc > _epsilon) _epsilon = lc;
816 816
        }
817 817
      }
818 818
      _epsilon /= _alpha;
819 819

	
820 820
      // Initialize maps for Circulation and remove non-zero lower bounds
821 821
      ConstMap<Arc, Value> low(0);
822 822
      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
823 823
      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
824 824
      ValueArcMap cap(_graph), flow(_graph);
825 825
      ValueNodeMap sup(_graph);
826 826
      for (NodeIt n(_graph); n != INVALID; ++n) {
827 827
        sup[n] = _supply[_node_id[n]];
828 828
      }
829 829
      if (_have_lower) {
830 830
        for (ArcIt a(_graph); a != INVALID; ++a) {
831 831
          int j = _arc_idf[a];
832 832
          Value c = _lower[j];
833 833
          cap[a] = _upper[j] - c;
834 834
          sup[_graph.source(a)] -= c;
835 835
          sup[_graph.target(a)] += c;
836 836
        }
837 837
      } else {
838 838
        for (ArcIt a(_graph); a != INVALID; ++a) {
839 839
          cap[a] = _upper[_arc_idf[a]];
840 840
        }
841 841
      }
842 842

	
843 843
      _sup_node_num = 0;
844 844
      for (NodeIt n(_graph); n != INVALID; ++n) {
845 845
        if (sup[n] > 0) ++_sup_node_num;
846 846
      }
847 847

	
848 848
      // Find a feasible flow using Circulation
849 849
      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
850 850
        circ(_graph, low, cap, sup);
851 851
      if (!circ.flowMap(flow).run()) return INFEASIBLE;
852 852

	
853 853
      // Set residual capacities and handle GEQ supply type
854 854
      if (_sum_supply < 0) {
855 855
        for (ArcIt a(_graph); a != INVALID; ++a) {
856 856
          Value fa = flow[a];
857 857
          _res_cap[_arc_idf[a]] = cap[a] - fa;
858 858
          _res_cap[_arc_idb[a]] = fa;
859 859
          sup[_graph.source(a)] -= fa;
860 860
          sup[_graph.target(a)] += fa;
861 861
        }
862 862
        for (NodeIt n(_graph); n != INVALID; ++n) {
863 863
          _excess[_node_id[n]] = sup[n];
864 864
        }
865 865
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
866 866
          int u = _target[a];
867 867
          int ra = _reverse[a];
868 868
          _res_cap[a] = -_sum_supply + 1;
869 869
          _res_cap[ra] = -_excess[u];
870 870
          _cost[a] = 0;
871 871
          _cost[ra] = 0;
872 872
          _excess[u] = 0;
873 873
        }
874 874
      } else {
875 875
        for (ArcIt a(_graph); a != INVALID; ++a) {
876 876
          Value fa = flow[a];
877 877
          _res_cap[_arc_idf[a]] = cap[a] - fa;
878 878
          _res_cap[_arc_idb[a]] = fa;
879 879
        }
880 880
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
881 881
          int ra = _reverse[a];
882 882
          _res_cap[a] = 0;
883 883
          _res_cap[ra] = 0;
884 884
          _cost[a] = 0;
885 885
          _cost[ra] = 0;
886 886
        }
887 887
      }
888 888

	
889 889
      return OPTIMAL;
890 890
    }
891 891

	
892 892
    // Execute the algorithm and transform the results
893 893
    void start(Method method) {
894 894
      // Maximum path length for partial augment
895 895
      const int MAX_PATH_LENGTH = 4;
896 896

	
897 897
      // Initialize data structures for buckets
898 898
      _max_rank = _alpha * _res_node_num;
899 899
      _buckets.resize(_max_rank);
900 900
      _bucket_next.resize(_res_node_num + 1);
901 901
      _bucket_prev.resize(_res_node_num + 1);
902 902
      _rank.resize(_res_node_num + 1);
903 903

	
904 904
      // Execute the algorithm
905 905
      switch (method) {
906 906
        case PUSH:
907 907
          startPush();
908 908
          break;
909 909
        case AUGMENT:
910 910
          startAugment(_res_node_num - 1);
911 911
          break;
912 912
        case PARTIAL_AUGMENT:
913 913
          startAugment(MAX_PATH_LENGTH);
914 914
          break;
915 915
      }
916 916

	
917 917
      // Compute node potentials for the original costs
918 918
      _arc_vec.clear();
919 919
      _cost_vec.clear();
920 920
      for (int j = 0; j != _res_arc_num; ++j) {
921 921
        if (_res_cap[j] > 0) {
922 922
          _arc_vec.push_back(IntPair(_source[j], _target[j]));
923 923
          _cost_vec.push_back(_scost[j]);
924 924
        }
925 925
      }
926 926
      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
927 927

	
928 928
      typename BellmanFord<StaticDigraph, LargeCostArcMap>
929 929
        ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
930 930
      bf.distMap(_pi_map);
931 931
      bf.init(0);
932 932
      bf.start();
933 933

	
934 934
      // Handle non-zero lower bounds
935 935
      if (_have_lower) {
936 936
        int limit = _first_out[_root];
937 937
        for (int j = 0; j != limit; ++j) {
938 938
          if (!_forward[j]) _res_cap[j] += _lower[j];
939 939
        }
940 940
      }
941 941
    }
942 942

	
943 943
    // Initialize a cost scaling phase
944 944
    void initPhase() {
945 945
      // Saturate arcs not satisfying the optimality condition
946 946
      for (int u = 0; u != _res_node_num; ++u) {
947 947
        int last_out = _first_out[u+1];
948 948
        LargeCost pi_u = _pi[u];
949 949
        for (int a = _first_out[u]; a != last_out; ++a) {
950 950
          int v = _target[a];
951 951
          if (_res_cap[a] > 0 && _cost[a] + pi_u - _pi[v] < 0) {
952 952
            Value delta = _res_cap[a];
953 953
            _excess[u] -= delta;
954 954
            _excess[v] += delta;
955 955
            _res_cap[a] = 0;
956 956
            _res_cap[_reverse[a]] += delta;
957 957
          }
958 958
        }
959 959
      }
960 960

	
961 961
      // Find active nodes (i.e. nodes with positive excess)
962 962
      for (int u = 0; u != _res_node_num; ++u) {
963 963
        if (_excess[u] > 0) _active_nodes.push_back(u);
964 964
      }
965 965

	
966 966
      // Initialize the next arcs
967 967
      for (int u = 0; u != _res_node_num; ++u) {
968 968
        _next_out[u] = _first_out[u];
969 969
      }
970 970
    }
971 971

	
972 972
    // Early termination heuristic
973 973
    bool earlyTermination() {
974 974
      const double EARLY_TERM_FACTOR = 3.0;
975 975

	
976 976
      // Build a static residual graph
977 977
      _arc_vec.clear();
978 978
      _cost_vec.clear();
979 979
      for (int j = 0; j != _res_arc_num; ++j) {
980 980
        if (_res_cap[j] > 0) {
981 981
          _arc_vec.push_back(IntPair(_source[j], _target[j]));
982 982
          _cost_vec.push_back(_cost[j] + 1);
983 983
        }
984 984
      }
985 985
      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
986 986

	
987 987
      // Run Bellman-Ford algorithm to check if the current flow is optimal
988 988
      BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
989 989
      bf.init(0);
990 990
      bool done = false;
991 991
      int K = int(EARLY_TERM_FACTOR * std::sqrt(double(_res_node_num)));
992 992
      for (int i = 0; i < K && !done; ++i) {
993 993
        done = bf.processNextWeakRound();
994 994
      }
995 995
      return done;
996 996
    }
997 997

	
998 998
    // Global potential update heuristic
999 999
    void globalUpdate() {
1000 1000
      int bucket_end = _root + 1;
1001 1001

	
1002 1002
      // Initialize buckets
1003 1003
      for (int r = 0; r != _max_rank; ++r) {
1004 1004
        _buckets[r] = bucket_end;
1005 1005
      }
1006 1006
      Value total_excess = 0;
1007 1007
      for (int i = 0; i != _res_node_num; ++i) {
1008 1008
        if (_excess[i] < 0) {
1009 1009
          _rank[i] = 0;
1010 1010
          _bucket_next[i] = _buckets[0];
1011 1011
          _bucket_prev[_buckets[0]] = i;
1012 1012
          _buckets[0] = i;
1013 1013
        } else {
1014 1014
          total_excess += _excess[i];
1015 1015
          _rank[i] = _max_rank;
1016 1016
        }
1017 1017
      }
1018 1018
      if (total_excess == 0) return;
1019 1019

	
1020 1020
      // Search the buckets
1021 1021
      int r = 0;
1022 1022
      for ( ; r != _max_rank; ++r) {
1023 1023
        while (_buckets[r] != bucket_end) {
1024 1024
          // Remove the first node from the current bucket
1025 1025
          int u = _buckets[r];
1026 1026
          _buckets[r] = _bucket_next[u];
1027 1027

	
1028 1028
          // Search the incomming arcs of u
1029 1029
          LargeCost pi_u = _pi[u];
1030 1030
          int last_out = _first_out[u+1];
1031 1031
          for (int a = _first_out[u]; a != last_out; ++a) {
1032 1032
            int ra = _reverse[a];
1033 1033
            if (_res_cap[ra] > 0) {
1034 1034
              int v = _source[ra];
1035 1035
              int old_rank_v = _rank[v];
1036 1036
              if (r < old_rank_v) {
1037 1037
                // Compute the new rank of v
1038 1038
                LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1039 1039
                int new_rank_v = old_rank_v;
1040 1040
                if (nrc < LargeCost(_max_rank))
1041 1041
                  new_rank_v = r + 1 + int(nrc);
1042 1042

	
1043 1043
                // Change the rank of v
1044 1044
                if (new_rank_v < old_rank_v) {
1045 1045
                  _rank[v] = new_rank_v;
1046 1046
                  _next_out[v] = _first_out[v];
1047 1047

	
1048 1048
                  // Remove v from its old bucket
1049 1049
                  if (old_rank_v < _max_rank) {
1050 1050
                    if (_buckets[old_rank_v] == v) {
1051 1051
                      _buckets[old_rank_v] = _bucket_next[v];
1052 1052
                    } else {
1053 1053
                      _bucket_next[_bucket_prev[v]] = _bucket_next[v];
1054 1054
                      _bucket_prev[_bucket_next[v]] = _bucket_prev[v];
1055 1055
                    }
1056 1056
                  }
1057 1057

	
1058 1058
                  // Insert v to its new bucket
1059 1059
                  _bucket_next[v] = _buckets[new_rank_v];
1060 1060
                  _bucket_prev[_buckets[new_rank_v]] = v;
1061 1061
                  _buckets[new_rank_v] = v;
1062 1062
                }
1063 1063
              }
1064 1064
            }
1065 1065
          }
1066 1066

	
1067 1067
          // Finish search if there are no more active nodes
1068 1068
          if (_excess[u] > 0) {
1069 1069
            total_excess -= _excess[u];
1070 1070
            if (total_excess <= 0) break;
1071 1071
          }
1072 1072
        }
1073 1073
        if (total_excess <= 0) break;
1074 1074
      }
1075 1075

	
1076 1076
      // Relabel nodes
1077 1077
      for (int u = 0; u != _res_node_num; ++u) {
1078 1078
        int k = std::min(_rank[u], r);
1079 1079
        if (k > 0) {
1080 1080
          _pi[u] -= _epsilon * k;
1081 1081
          _next_out[u] = _first_out[u];
1082 1082
        }
1083 1083
      }
1084 1084
    }
1085 1085

	
1086 1086
    /// Execute the algorithm performing augment and relabel operations
1087 1087
    void startAugment(int max_length) {
1088 1088
      // Paramters for heuristics
1089 1089
      const int EARLY_TERM_EPSILON_LIMIT = 1000;
1090 1090
      const double GLOBAL_UPDATE_FACTOR = 3.0;
1091 1091

	
1092 1092
      const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1093 1093
        (_res_node_num + _sup_node_num * _sup_node_num));
1094 1094
      int next_update_limit = global_update_freq;
1095 1095

	
1096 1096
      int relabel_cnt = 0;
1097 1097

	
1098 1098
      // Perform cost scaling phases
1099 1099
      std::vector<int> path;
1100 1100
      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1101 1101
                                        1 : _epsilon / _alpha )
1102 1102
      {
1103 1103
        // Early termination heuristic
1104 1104
        if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1105 1105
          if (earlyTermination()) break;
1106 1106
        }
1107 1107

	
1108 1108
        // Initialize current phase
1109 1109
        initPhase();
1110 1110

	
1111 1111
        // Perform partial augment and relabel operations
1112 1112
        while (true) {
1113 1113
          // Select an active node (FIFO selection)
1114 1114
          while (_active_nodes.size() > 0 &&
1115 1115
                 _excess[_active_nodes.front()] <= 0) {
1116 1116
            _active_nodes.pop_front();
1117 1117
          }
1118 1118
          if (_active_nodes.size() == 0) break;
1119 1119
          int start = _active_nodes.front();
1120 1120

	
1121 1121
          // Find an augmenting path from the start node
1122 1122
          path.clear();
1123 1123
          int tip = start;
1124 1124
          while (_excess[tip] >= 0 && int(path.size()) < max_length) {
1125 1125
            int u;
1126 1126
            LargeCost min_red_cost, rc, pi_tip = _pi[tip];
1127 1127
            int last_out = _first_out[tip+1];
1128 1128
            for (int a = _next_out[tip]; a != last_out; ++a) {
1129 1129
              u = _target[a];
1130 1130
              if (_res_cap[a] > 0 && _cost[a] + pi_tip - _pi[u] < 0) {
1131 1131
                path.push_back(a);
1132 1132
                _next_out[tip] = a;
1133 1133
                tip = u;
1134 1134
                goto next_step;
1135 1135
              }
1136 1136
            }
1137 1137

	
1138 1138
            // Relabel tip node
1139 1139
            min_red_cost = std::numeric_limits<LargeCost>::max();
1140 1140
            if (tip != start) {
1141 1141
              int ra = _reverse[path.back()];
1142 1142
              min_red_cost = _cost[ra] + pi_tip - _pi[_target[ra]];
1143 1143
            }
1144 1144
            for (int a = _first_out[tip]; a != last_out; ++a) {
1145 1145
              rc = _cost[a] + pi_tip - _pi[_target[a]];
1146 1146
              if (_res_cap[a] > 0 && rc < min_red_cost) {
1147 1147
                min_red_cost = rc;
1148 1148
              }
1149 1149
            }
1150 1150
            _pi[tip] -= min_red_cost + _epsilon;
1151 1151
            _next_out[tip] = _first_out[tip];
1152 1152
            ++relabel_cnt;
1153 1153

	
1154 1154
            // Step back
1155 1155
            if (tip != start) {
1156 1156
              tip = _source[path.back()];
1157 1157
              path.pop_back();
1158 1158
            }
1159 1159

	
1160 1160
          next_step: ;
1161 1161
          }
1162 1162

	
1163 1163
          // Augment along the found path (as much flow as possible)
1164 1164
          Value delta;
1165 1165
          int pa, u, v = start;
1166 1166
          for (int i = 0; i != int(path.size()); ++i) {
1167 1167
            pa = path[i];
1168 1168
            u = v;
1169 1169
            v = _target[pa];
1170 1170
            delta = std::min(_res_cap[pa], _excess[u]);
1171 1171
            _res_cap[pa] -= delta;
1172 1172
            _res_cap[_reverse[pa]] += delta;
1173 1173
            _excess[u] -= delta;
1174 1174
            _excess[v] += delta;
1175 1175
            if (_excess[v] > 0 && _excess[v] <= delta)
1176 1176
              _active_nodes.push_back(v);
1177 1177
          }
1178 1178

	
1179 1179
          // Global update heuristic
1180 1180
          if (relabel_cnt >= next_update_limit) {
1181 1181
            globalUpdate();
1182 1182
            next_update_limit += global_update_freq;
1183 1183
          }
1184 1184
        }
1185 1185
      }
1186 1186
    }
1187 1187

	
1188 1188
    /// Execute the algorithm performing push and relabel operations
1189 1189
    void startPush() {
1190 1190
      // Paramters for heuristics
1191 1191
      const int EARLY_TERM_EPSILON_LIMIT = 1000;
1192 1192
      const double GLOBAL_UPDATE_FACTOR = 2.0;
1193 1193

	
1194 1194
      const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1195 1195
        (_res_node_num + _sup_node_num * _sup_node_num));
1196 1196
      int next_update_limit = global_update_freq;
1197 1197

	
1198 1198
      int relabel_cnt = 0;
1199 1199

	
1200 1200
      // Perform cost scaling phases
1201 1201
      BoolVector hyper(_res_node_num, false);
1202 1202
      LargeCostVector hyper_cost(_res_node_num);
1203 1203
      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1204 1204
                                        1 : _epsilon / _alpha )
1205 1205
      {
1206 1206
        // Early termination heuristic
1207 1207
        if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1208 1208
          if (earlyTermination()) break;
1209 1209
        }
1210 1210

	
1211 1211
        // Initialize current phase
1212 1212
        initPhase();
1213 1213

	
1214 1214
        // Perform push and relabel operations
1215 1215
        while (_active_nodes.size() > 0) {
1216 1216
          LargeCost min_red_cost, rc, pi_n;
1217 1217
          Value delta;
1218 1218
          int n, t, a, last_out = _res_arc_num;
1219 1219

	
1220 1220
        next_node:
1221 1221
          // Select an active node (FIFO selection)
1222 1222
          n = _active_nodes.front();
1223 1223
          last_out = _first_out[n+1];
1224 1224
          pi_n = _pi[n];
1225 1225

	
1226 1226
          // Perform push operations if there are admissible arcs
1227 1227
          if (_excess[n] > 0) {
1228 1228
            for (a = _next_out[n]; a != last_out; ++a) {
1229 1229
              if (_res_cap[a] > 0 &&
1230 1230
                  _cost[a] + pi_n - _pi[_target[a]] < 0) {
1231 1231
                delta = std::min(_res_cap[a], _excess[n]);
1232 1232
                t = _target[a];
1233 1233

	
1234 1234
                // Push-look-ahead heuristic
1235 1235
                Value ahead = -_excess[t];
1236 1236
                int last_out_t = _first_out[t+1];
1237 1237
                LargeCost pi_t = _pi[t];
1238 1238
                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1239 1239
                  if (_res_cap[ta] > 0 &&
1240 1240
                      _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1241 1241
                    ahead += _res_cap[ta];
1242 1242
                  if (ahead >= delta) break;
1243 1243
                }
1244 1244
                if (ahead < 0) ahead = 0;
1245 1245

	
1246 1246
                // Push flow along the arc
1247 1247
                if (ahead < delta && !hyper[t]) {
1248 1248
                  _res_cap[a] -= ahead;
1249 1249
                  _res_cap[_reverse[a]] += ahead;
1250 1250
                  _excess[n] -= ahead;
1251 1251
                  _excess[t] += ahead;
1252 1252
                  _active_nodes.push_front(t);
1253 1253
                  hyper[t] = true;
1254 1254
                  hyper_cost[t] = _cost[a] + pi_n - pi_t;
1255 1255
                  _next_out[n] = a;
1256 1256
                  goto next_node;
1257 1257
                } else {
1258 1258
                  _res_cap[a] -= delta;
1259 1259
                  _res_cap[_reverse[a]] += delta;
1260 1260
                  _excess[n] -= delta;
1261 1261
                  _excess[t] += delta;
1262 1262
                  if (_excess[t] > 0 && _excess[t] <= delta)
1263 1263
                    _active_nodes.push_back(t);
1264 1264
                }
1265 1265

	
1266 1266
                if (_excess[n] == 0) {
1267 1267
                  _next_out[n] = a;
1268 1268
                  goto remove_nodes;
1269 1269
                }
1270 1270
              }
1271 1271
            }
1272 1272
            _next_out[n] = a;
1273 1273
          }
1274 1274

	
1275 1275
          // Relabel the node if it is still active (or hyper)
1276 1276
          if (_excess[n] > 0 || hyper[n]) {
1277 1277
             min_red_cost = hyper[n] ? -hyper_cost[n] :
1278 1278
               std::numeric_limits<LargeCost>::max();
1279 1279
            for (int a = _first_out[n]; a != last_out; ++a) {
1280 1280
              rc = _cost[a] + pi_n - _pi[_target[a]];
1281 1281
              if (_res_cap[a] > 0 && rc < min_red_cost) {
1282 1282
                min_red_cost = rc;
1283 1283
              }
1284 1284
            }
1285 1285
            _pi[n] -= min_red_cost + _epsilon;
1286 1286
            _next_out[n] = _first_out[n];
1287 1287
            hyper[n] = false;
1288 1288
            ++relabel_cnt;
1289 1289
          }
1290 1290

	
1291 1291
          // Remove nodes that are not active nor hyper
1292 1292
        remove_nodes:
1293 1293
          while ( _active_nodes.size() > 0 &&
1294 1294
                  _excess[_active_nodes.front()] <= 0 &&
1295 1295
                  !hyper[_active_nodes.front()] ) {
1296 1296
            _active_nodes.pop_front();
1297 1297
          }
1298 1298

	
1299 1299
          // Global update heuristic
1300 1300
          if (relabel_cnt >= next_update_limit) {
1301 1301
            globalUpdate();
1302 1302
            for (int u = 0; u != _res_node_num; ++u)
1303 1303
              hyper[u] = false;
1304 1304
            next_update_limit += global_update_freq;
1305 1305
          }
1306 1306
        }
1307 1307
      }
1308 1308
    }
1309 1309

	
1310 1310
  }; //class CostScaling
1311 1311

	
1312 1312
  ///@}
1313 1313

	
1314 1314
} //namespace lemon
1315 1315

	
1316 1316
#endif //LEMON_COST_SCALING_H
Show white space 4096 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
 * Copyright (C) 2003-2010
5
 * Copyright (C) 2003-2011
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_MAPS_H
20 20
#define LEMON_MAPS_H
21 21

	
22 22
#include <iterator>
23 23
#include <functional>
24 24
#include <vector>
25 25
#include <map>
26 26

	
27 27
#include <lemon/core.h>
28 28

	
29 29
///\file
30 30
///\ingroup maps
31 31
///\brief Miscellaneous property maps
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  /// \addtogroup maps
36 36
  /// @{
37 37

	
38 38
  /// Base class of maps.
39 39

	
40 40
  /// Base class of maps. It provides the necessary type definitions
41 41
  /// required by the map %concepts.
42 42
  template<typename K, typename V>
43 43
  class MapBase {
44 44
  public:
45 45
    /// \brief The key type of the map.
46 46
    typedef K Key;
47 47
    /// \brief The value type of the map.
48 48
    /// (The type of objects associated with the keys).
49 49
    typedef V Value;
50 50
  };
51 51

	
52 52

	
53 53
  /// Null map. (a.k.a. DoNothingMap)
54 54

	
55 55
  /// This map can be used if you have to provide a map only for
56 56
  /// its type definitions, or if you have to provide a writable map,
57 57
  /// but data written to it is not required (i.e. it will be sent to
58 58
  /// <tt>/dev/null</tt>).
59 59
  /// It conforms to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
60 60
  ///
61 61
  /// \sa ConstMap
62 62
  template<typename K, typename V>
63 63
  class NullMap : public MapBase<K, V> {
64 64
  public:
65 65
    ///\e
66 66
    typedef K Key;
67 67
    ///\e
68 68
    typedef V Value;
69 69

	
70 70
    /// Gives back a default constructed element.
71 71
    Value operator[](const Key&) const { return Value(); }
72 72
    /// Absorbs the value.
73 73
    void set(const Key&, const Value&) {}
74 74
  };
75 75

	
76 76
  /// Returns a \c NullMap class
77 77

	
78 78
  /// This function just returns a \c NullMap class.
79 79
  /// \relates NullMap
80 80
  template <typename K, typename V>
81 81
  NullMap<K, V> nullMap() {
82 82
    return NullMap<K, V>();
83 83
  }
84 84

	
85 85

	
86 86
  /// Constant map.
87 87

	
88 88
  /// This \ref concepts::ReadMap "readable map" assigns a specified
89 89
  /// value to each key.
90 90
  ///
91 91
  /// In other aspects it is equivalent to \c NullMap.
92 92
  /// So it conforms to the \ref concepts::ReadWriteMap "ReadWriteMap"
93 93
  /// concept, but it absorbs the data written to it.
94 94
  ///
95 95
  /// The simplest way of using this map is through the constMap()
96 96
  /// function.
97 97
  ///
98 98
  /// \sa NullMap
99 99
  /// \sa IdentityMap
100 100
  template<typename K, typename V>
101 101
  class ConstMap : public MapBase<K, V> {
102 102
  private:
103 103
    V _value;
104 104
  public:
105 105
    ///\e
106 106
    typedef K Key;
107 107
    ///\e
108 108
    typedef V Value;
109 109

	
110 110
    /// Default constructor
111 111

	
112 112
    /// Default constructor.
113 113
    /// The value of the map will be default constructed.
114 114
    ConstMap() {}
115 115

	
116 116
    /// Constructor with specified initial value
117 117

	
118 118
    /// Constructor with specified initial value.
119 119
    /// \param v The initial value of the map.
120 120
    ConstMap(const Value &v) : _value(v) {}
121 121

	
122 122
    /// Gives back the specified value.
123 123
    Value operator[](const Key&) const { return _value; }
124 124

	
125 125
    /// Absorbs the value.
126 126
    void set(const Key&, const Value&) {}
127 127

	
128 128
    /// Sets the value that is assigned to each key.
129 129
    void setAll(const Value &v) {
130 130
      _value = v;
131 131
    }
132 132

	
133 133
    template<typename V1>
134 134
    ConstMap(const ConstMap<K, V1> &, const Value &v) : _value(v) {}
135 135
  };
136 136

	
137 137
  /// Returns a \c ConstMap class
138 138

	
139 139
  /// This function just returns a \c ConstMap class.
140 140
  /// \relates ConstMap
141 141
  template<typename K, typename V>
142 142
  inline ConstMap<K, V> constMap(const V &v) {
143 143
    return ConstMap<K, V>(v);
144 144
  }
145 145

	
146 146
  template<typename K, typename V>
147 147
  inline ConstMap<K, V> constMap() {
148 148
    return ConstMap<K, V>();
149 149
  }
150 150

	
151 151

	
152 152
  template<typename T, T v>
153 153
  struct Const {};
154 154

	
155 155
  /// Constant map with inlined constant value.
156 156

	
157 157
  /// This \ref concepts::ReadMap "readable map" assigns a specified
158 158
  /// value to each key.
159 159
  ///
160 160
  /// In other aspects it is equivalent to \c NullMap.
161 161
  /// So it conforms to the \ref concepts::ReadWriteMap "ReadWriteMap"
162 162
  /// concept, but it absorbs the data written to it.
163 163
  ///
164 164
  /// The simplest way of using this map is through the constMap()
165 165
  /// function.
166 166
  ///
167 167
  /// \sa NullMap
168 168
  /// \sa IdentityMap
169 169
  template<typename K, typename V, V v>
170 170
  class ConstMap<K, Const<V, v> > : public MapBase<K, V> {
171 171
  public:
172 172
    ///\e
173 173
    typedef K Key;
174 174
    ///\e
175 175
    typedef V Value;
176 176

	
177 177
    /// Constructor.
178 178
    ConstMap() {}
179 179

	
180 180
    /// Gives back the specified value.
181 181
    Value operator[](const Key&) const { return v; }
182 182

	
183 183
    /// Absorbs the value.
184 184
    void set(const Key&, const Value&) {}
185 185
  };
186 186

	
187 187
  /// Returns a \c ConstMap class with inlined constant value
188 188

	
189 189
  /// This function just returns a \c ConstMap class with inlined
190 190
  /// constant value.
191 191
  /// \relates ConstMap
192 192
  template<typename K, typename V, V v>
193 193
  inline ConstMap<K, Const<V, v> > constMap() {
194 194
    return ConstMap<K, Const<V, v> >();
195 195
  }
196 196

	
197 197

	
198 198
  /// Identity map.
199 199

	
200 200
  /// This \ref concepts::ReadMap "read-only map" gives back the given
201 201
  /// key as value without any modification.
202 202
  ///
203 203
  /// \sa ConstMap
204 204
  template <typename T>
205 205
  class IdentityMap : public MapBase<T, T> {
206 206
  public:
207 207
    ///\e
208 208
    typedef T Key;
209 209
    ///\e
210 210
    typedef T Value;
211 211

	
212 212
    /// Gives back the given value without any modification.
213 213
    Value operator[](const Key &k) const {
214 214
      return k;
215 215
    }
216 216
  };
217 217

	
218 218
  /// Returns an \c IdentityMap class
219 219

	
220 220
  /// This function just returns an \c IdentityMap class.
221 221
  /// \relates IdentityMap
222 222
  template<typename T>
223 223
  inline IdentityMap<T> identityMap() {
224 224
    return IdentityMap<T>();
225 225
  }
226 226

	
227 227

	
228 228
  /// \brief Map for storing values for integer keys from the range
229 229
  /// <tt>[0..size-1]</tt>.
230 230
  ///
231 231
  /// This map is essentially a wrapper for \c std::vector. It assigns
232 232
  /// values to integer keys from the range <tt>[0..size-1]</tt>.
233 233
  /// It can be used together with some data structures, e.g.
234 234
  /// heap types and \c UnionFind, when the used items are small
235 235
  /// integers. This map conforms to the \ref concepts::ReferenceMap
236 236
  /// "ReferenceMap" concept.
237 237
  ///
238 238
  /// The simplest way of using this map is through the rangeMap()
239 239
  /// function.
240 240
  template <typename V>
241 241
  class RangeMap : public MapBase<int, V> {
242 242
    template <typename V1>
243 243
    friend class RangeMap;
244 244
  private:
245 245

	
246 246
    typedef std::vector<V> Vector;
247 247
    Vector _vector;
248 248

	
249 249
  public:
250 250

	
251 251
    /// Key type
252 252
    typedef int Key;
253 253
    /// Value type
254 254
    typedef V Value;
255 255
    /// Reference type
256 256
    typedef typename Vector::reference Reference;
257 257
    /// Const reference type
258 258
    typedef typename Vector::const_reference ConstReference;
259 259

	
260 260
    typedef True ReferenceMapTag;
261 261

	
262 262
  public:
263 263

	
264 264
    /// Constructor with specified default value.
265 265
    RangeMap(int size = 0, const Value &value = Value())
266 266
      : _vector(size, value) {}
267 267

	
268 268
    /// Constructs the map from an appropriate \c std::vector.
269 269
    template <typename V1>
270 270
    RangeMap(const std::vector<V1>& vector)
271 271
      : _vector(vector.begin(), vector.end()) {}
272 272

	
273 273
    /// Constructs the map from another \c RangeMap.
274 274
    template <typename V1>
275 275
    RangeMap(const RangeMap<V1> &c)
276 276
      : _vector(c._vector.begin(), c._vector.end()) {}
277 277

	
278 278
    /// Returns the size of the map.
279 279
    int size() {
280 280
      return _vector.size();
281 281
    }
282 282

	
283 283
    /// Resizes the map.
284 284

	
285 285
    /// Resizes the underlying \c std::vector container, so changes the
286 286
    /// keyset of the map.
287 287
    /// \param size The new size of the map. The new keyset will be the
288 288
    /// range <tt>[0..size-1]</tt>.
289 289
    /// \param value The default value to assign to the new keys.
290 290
    void resize(int size, const Value &value = Value()) {
291 291
      _vector.resize(size, value);
292 292
    }
293 293

	
294 294
  private:
295 295

	
296 296
    RangeMap& operator=(const RangeMap&);
297 297

	
298 298
  public:
299 299

	
300 300
    ///\e
301 301
    Reference operator[](const Key &k) {
302 302
      return _vector[k];
303 303
    }
304 304

	
305 305
    ///\e
306 306
    ConstReference operator[](const Key &k) const {
307 307
      return _vector[k];
308 308
    }
309 309

	
310 310
    ///\e
311 311
    void set(const Key &k, const Value &v) {
312 312
      _vector[k] = v;
313 313
    }
314 314
  };
315 315

	
316 316
  /// Returns a \c RangeMap class
317 317

	
318 318
  /// This function just returns a \c RangeMap class.
319 319
  /// \relates RangeMap
320 320
  template<typename V>
321 321
  inline RangeMap<V> rangeMap(int size = 0, const V &value = V()) {
322 322
    return RangeMap<V>(size, value);
323 323
  }
324 324

	
325 325
  /// \brief Returns a \c RangeMap class created from an appropriate
326 326
  /// \c std::vector
327 327

	
328 328
  /// This function just returns a \c RangeMap class created from an
329 329
  /// appropriate \c std::vector.
330 330
  /// \relates RangeMap
331 331
  template<typename V>
332 332
  inline RangeMap<V> rangeMap(const std::vector<V> &vector) {
333 333
    return RangeMap<V>(vector);
334 334
  }
335 335

	
336 336

	
337 337
  /// Map type based on \c std::map
338 338

	
339 339
  /// This map is essentially a wrapper for \c std::map with addition
340 340
  /// that you can specify a default value for the keys that are not
341 341
  /// stored actually. This value can be different from the default
342 342
  /// contructed value (i.e. \c %Value()).
343 343
  /// This type conforms to the \ref concepts::ReferenceMap "ReferenceMap"
344 344
  /// concept.
345 345
  ///
346 346
  /// This map is useful if a default value should be assigned to most of
347 347
  /// the keys and different values should be assigned only to a few
348 348
  /// keys (i.e. the map is "sparse").
349 349
  /// The name of this type also refers to this important usage.
350 350
  ///
351 351
  /// Apart form that, this map can be used in many other cases since it
352 352
  /// is based on \c std::map, which is a general associative container.
353 353
  /// However, keep in mind that it is usually not as efficient as other
354 354
  /// maps.
355 355
  ///
356 356
  /// The simplest way of using this map is through the sparseMap()
357 357
  /// function.
358 358
  template <typename K, typename V, typename Comp = std::less<K> >
359 359
  class SparseMap : public MapBase<K, V> {
360 360
    template <typename K1, typename V1, typename C1>
361 361
    friend class SparseMap;
362 362
  public:
363 363

	
364 364
    /// Key type
365 365
    typedef K Key;
366 366
    /// Value type
367 367
    typedef V Value;
368 368
    /// Reference type
369 369
    typedef Value& Reference;
370 370
    /// Const reference type
371 371
    typedef const Value& ConstReference;
372 372

	
373 373
    typedef True ReferenceMapTag;
374 374

	
375 375
  private:
376 376

	
377 377
    typedef std::map<K, V, Comp> Map;
378 378
    Map _map;
379 379
    Value _value;
380 380

	
381 381
  public:
382 382

	
383 383
    /// \brief Constructor with specified default value.
384 384
    SparseMap(const Value &value = Value()) : _value(value) {}
385 385
    /// \brief Constructs the map from an appropriate \c std::map, and
386 386
    /// explicitly specifies a default value.
387 387
    template <typename V1, typename Comp1>
388 388
    SparseMap(const std::map<Key, V1, Comp1> &map,
389 389
              const Value &value = Value())
390 390
      : _map(map.begin(), map.end()), _value(value) {}
391 391

	
392 392
    /// \brief Constructs the map from another \c SparseMap.
393 393
    template<typename V1, typename Comp1>
394 394
    SparseMap(const SparseMap<Key, V1, Comp1> &c)
395 395
      : _map(c._map.begin(), c._map.end()), _value(c._value) {}
396 396

	
397 397
  private:
398 398

	
399 399
    SparseMap& operator=(const SparseMap&);
400 400

	
401 401
  public:
402 402

	
403 403
    ///\e
404 404
    Reference operator[](const Key &k) {
405 405
      typename Map::iterator it = _map.lower_bound(k);
406 406
      if (it != _map.end() && !_map.key_comp()(k, it->first))
407 407
        return it->second;
408 408
      else
409 409
        return _map.insert(it, std::make_pair(k, _value))->second;
410 410
    }
411 411

	
412 412
    ///\e
413 413
    ConstReference operator[](const Key &k) const {
414 414
      typename Map::const_iterator it = _map.find(k);
415 415
      if (it != _map.end())
416 416
        return it->second;
417 417
      else
418 418
        return _value;
419 419
    }
420 420

	
421 421
    ///\e
422 422
    void set(const Key &k, const Value &v) {
423 423
      typename Map::iterator it = _map.lower_bound(k);
424 424
      if (it != _map.end() && !_map.key_comp()(k, it->first))
425 425
        it->second = v;
426 426
      else
427 427
        _map.insert(it, std::make_pair(k, v));
428 428
    }
429 429

	
430 430
    ///\e
431 431
    void setAll(const Value &v) {
432 432
      _value = v;
433 433
      _map.clear();
434 434
    }
435 435
  };
436 436

	
437 437
  /// Returns a \c SparseMap class
438 438

	
439 439
  /// This function just returns a \c SparseMap class with specified
440 440
  /// default value.
441 441
  /// \relates SparseMap
442 442
  template<typename K, typename V, typename Compare>
443 443
  inline SparseMap<K, V, Compare> sparseMap(const V& value = V()) {
444 444
    return SparseMap<K, V, Compare>(value);
445 445
  }
446 446

	
447 447
  template<typename K, typename V>
448 448
  inline SparseMap<K, V, std::less<K> > sparseMap(const V& value = V()) {
449 449
    return SparseMap<K, V, std::less<K> >(value);
450 450
  }
451 451

	
452 452
  /// \brief Returns a \c SparseMap class created from an appropriate
453 453
  /// \c std::map
454 454

	
455 455
  /// This function just returns a \c SparseMap class created from an
456 456
  /// appropriate \c std::map.
457 457
  /// \relates SparseMap
458 458
  template<typename K, typename V, typename Compare>
459 459
  inline SparseMap<K, V, Compare>
460 460
    sparseMap(const std::map<K, V, Compare> &map, const V& value = V())
461 461
  {
462 462
    return SparseMap<K, V, Compare>(map, value);
463 463
  }
464 464

	
465 465
  /// @}
466 466

	
467 467
  /// \addtogroup map_adaptors
468 468
  /// @{
469 469

	
470 470
  /// Composition of two maps
471 471

	
472 472
  /// This \ref concepts::ReadMap "read-only map" returns the
473 473
  /// composition of two given maps. That is to say, if \c m1 is of
474 474
  /// type \c M1 and \c m2 is of \c M2, then for
475 475
  /// \code
476 476
  ///   ComposeMap<M1, M2> cm(m1,m2);
477 477
  /// \endcode
478 478
  /// <tt>cm[x]</tt> will be equal to <tt>m1[m2[x]]</tt>.
479 479
  ///
480 480
  /// The \c Key type of the map is inherited from \c M2 and the
481 481
  /// \c Value type is from \c M1.
482 482
  /// \c M2::Value must be convertible to \c M1::Key.
483 483
  ///
484 484
  /// The simplest way of using this map is through the composeMap()
485 485
  /// function.
486 486
  ///
487 487
  /// \sa CombineMap
488 488
  template <typename M1, typename M2>
489 489
  class ComposeMap : public MapBase<typename M2::Key, typename M1::Value> {
490 490
    const M1 &_m1;
491 491
    const M2 &_m2;
492 492
  public:
493 493
    ///\e
494 494
    typedef typename M2::Key Key;
495 495
    ///\e
496 496
    typedef typename M1::Value Value;
497 497

	
498 498
    /// Constructor
499 499
    ComposeMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
500 500

	
501 501
    ///\e
502 502
    typename MapTraits<M1>::ConstReturnValue
503 503
    operator[](const Key &k) const { return _m1[_m2[k]]; }
504 504
  };
505 505

	
506 506
  /// Returns a \c ComposeMap class
507 507

	
508 508
  /// This function just returns a \c ComposeMap class.
509 509
  ///
510 510
  /// If \c m1 and \c m2 are maps and the \c Value type of \c m2 is
511 511
  /// convertible to the \c Key of \c m1, then <tt>composeMap(m1,m2)[x]</tt>
512 512
  /// will be equal to <tt>m1[m2[x]]</tt>.
513 513
  ///
514 514
  /// \relates ComposeMap
515 515
  template <typename M1, typename M2>
516 516
  inline ComposeMap<M1, M2> composeMap(const M1 &m1, const M2 &m2) {
517 517
    return ComposeMap<M1, M2>(m1, m2);
518 518
  }
519 519

	
520 520

	
521 521
  /// Combination of two maps using an STL (binary) functor.
522 522

	
523 523
  /// This \ref concepts::ReadMap "read-only map" takes two maps and a
524 524
  /// binary functor and returns the combination of the two given maps
525 525
  /// using the functor.
526 526
  /// That is to say, if \c m1 is of type \c M1 and \c m2 is of \c M2
527 527
  /// and \c f is of \c F, then for
528 528
  /// \code
529 529
  ///   CombineMap<M1,M2,F,V> cm(m1,m2,f);
530 530
  /// \endcode
531 531
  /// <tt>cm[x]</tt> will be equal to <tt>f(m1[x],m2[x])</tt>.
532 532
  ///
533 533
  /// The \c Key type of the map is inherited from \c M1 (\c M1::Key
534 534
  /// must be convertible to \c M2::Key) and the \c Value type is \c V.
535 535
  /// \c M2::Value and \c M1::Value must be convertible to the
536 536
  /// corresponding input parameter of \c F and the return type of \c F
537 537
  /// must be convertible to \c V.
538 538
  ///
539 539
  /// The simplest way of using this map is through the combineMap()
540 540
  /// function.
541 541
  ///
542 542
  /// \sa ComposeMap
543 543
  template<typename M1, typename M2, typename F,
544 544
           typename V = typename F::result_type>
545 545
  class CombineMap : public MapBase<typename M1::Key, V> {
546 546
    const M1 &_m1;
547 547
    const M2 &_m2;
548 548
    F _f;
549 549
  public:
550 550
    ///\e
551 551
    typedef typename M1::Key Key;
552 552
    ///\e
553 553
    typedef V Value;
554 554

	
555 555
    /// Constructor
556 556
    CombineMap(const M1 &m1, const M2 &m2, const F &f = F())
557 557
      : _m1(m1), _m2(m2), _f(f) {}
558 558
    ///\e
559 559
    Value operator[](const Key &k) const { return _f(_m1[k],_m2[k]); }
560 560
  };
561 561

	
562 562
  /// Returns a \c CombineMap class
563 563

	
564 564
  /// This function just returns a \c CombineMap class.
565 565
  ///
566 566
  /// For example, if \c m1 and \c m2 are both maps with \c double
567 567
  /// values, then
568 568
  /// \code
569 569
  ///   combineMap(m1,m2,std::plus<double>())
570 570
  /// \endcode
571 571
  /// is equivalent to
572 572
  /// \code
573 573
  ///   addMap(m1,m2)
574 574
  /// \endcode
575 575
  ///
576 576
  /// This function is specialized for adaptable binary function
577 577
  /// classes and C++ functions.
578 578
  ///
579 579
  /// \relates CombineMap
580 580
  template<typename M1, typename M2, typename F, typename V>
581 581
  inline CombineMap<M1, M2, F, V>
582 582
  combineMap(const M1 &m1, const M2 &m2, const F &f) {
583 583
    return CombineMap<M1, M2, F, V>(m1,m2,f);
584 584
  }
585 585

	
586 586
  template<typename M1, typename M2, typename F>
587 587
  inline CombineMap<M1, M2, F, typename F::result_type>
588 588
  combineMap(const M1 &m1, const M2 &m2, const F &f) {
589 589
    return combineMap<M1, M2, F, typename F::result_type>(m1,m2,f);
590 590
  }
591 591

	
592 592
  template<typename M1, typename M2, typename K1, typename K2, typename V>
593 593
  inline CombineMap<M1, M2, V (*)(K1, K2), V>
594 594
  combineMap(const M1 &m1, const M2 &m2, V (*f)(K1, K2)) {
595 595
    return combineMap<M1, M2, V (*)(K1, K2), V>(m1,m2,f);
596 596
  }
597 597

	
598 598

	
599 599
  /// Converts an STL style (unary) functor to a map
600 600

	
601 601
  /// This \ref concepts::ReadMap "read-only map" returns the value
602 602
  /// of a given functor. Actually, it just wraps the functor and
603 603
  /// provides the \c Key and \c Value typedefs.
604 604
  ///
605 605
  /// Template parameters \c K and \c V will become its \c Key and
606 606
  /// \c Value. In most cases they have to be given explicitly because
607 607
  /// a functor typically does not provide \c argument_type and
608 608
  /// \c result_type typedefs.
609 609
  /// Parameter \c F is the type of the used functor.
610 610
  ///
611 611
  /// The simplest way of using this map is through the functorToMap()
612 612
  /// function.
613 613
  ///
614 614
  /// \sa MapToFunctor
615 615
  template<typename F,
616 616
           typename K = typename F::argument_type,
617 617
           typename V = typename F::result_type>
618 618
  class FunctorToMap : public MapBase<K, V> {
619 619
    F _f;
620 620
  public:
621 621
    ///\e
622 622
    typedef K Key;
623 623
    ///\e
624 624
    typedef V Value;
625 625

	
626 626
    /// Constructor
627 627
    FunctorToMap(const F &f = F()) : _f(f) {}
628 628
    ///\e
629 629
    Value operator[](const Key &k) const { return _f(k); }
630 630
  };
631 631

	
632 632
  /// Returns a \c FunctorToMap class
633 633

	
634 634
  /// This function just returns a \c FunctorToMap class.
635 635
  ///
636 636
  /// This function is specialized for adaptable binary function
637 637
  /// classes and C++ functions.
638 638
  ///
639 639
  /// \relates FunctorToMap
640 640
  template<typename K, typename V, typename F>
641 641
  inline FunctorToMap<F, K, V> functorToMap(const F &f) {
642 642
    return FunctorToMap<F, K, V>(f);
643 643
  }
644 644

	
645 645
  template <typename F>
646 646
  inline FunctorToMap<F, typename F::argument_type, typename F::result_type>
647 647
    functorToMap(const F &f)
648 648
  {
649 649
    return FunctorToMap<F, typename F::argument_type,
650 650
      typename F::result_type>(f);
651 651
  }
652 652

	
653 653
  template <typename K, typename V>
654 654
  inline FunctorToMap<V (*)(K), K, V> functorToMap(V (*f)(K)) {
655 655
    return FunctorToMap<V (*)(K), K, V>(f);
656 656
  }
657 657

	
658 658

	
659 659
  /// Converts a map to an STL style (unary) functor
660 660

	
661 661
  /// This class converts a map to an STL style (unary) functor.
662 662
  /// That is it provides an <tt>operator()</tt> to read its values.
663 663
  ///
664 664
  /// For the sake of convenience it also works as a usual
665 665
  /// \ref concepts::ReadMap "readable map", i.e. <tt>operator[]</tt>
666 666
  /// and the \c Key and \c Value typedefs also exist.
667 667
  ///
668 668
  /// The simplest way of using this map is through the mapToFunctor()
669 669
  /// function.
670 670
  ///
671 671
  ///\sa FunctorToMap
672 672
  template <typename M>
673 673
  class MapToFunctor : public MapBase<typename M::Key, typename M::Value> {
674 674
    const M &_m;
675 675
  public:
676 676
    ///\e
677 677
    typedef typename M::Key Key;
678 678
    ///\e
679 679
    typedef typename M::Value Value;
680 680

	
681 681
    typedef typename M::Key argument_type;
682 682
    typedef typename M::Value result_type;
683 683

	
684 684
    /// Constructor
685 685
    MapToFunctor(const M &m) : _m(m) {}
686 686
    ///\e
687 687
    Value operator()(const Key &k) const { return _m[k]; }
688 688
    ///\e
689 689
    Value operator[](const Key &k) const { return _m[k]; }
690 690
  };
691 691

	
692 692
  /// Returns a \c MapToFunctor class
693 693

	
694 694
  /// This function just returns a \c MapToFunctor class.
695 695
  /// \relates MapToFunctor
696 696
  template<typename M>
697 697
  inline MapToFunctor<M> mapToFunctor(const M &m) {
698 698
    return MapToFunctor<M>(m);
699 699
  }
700 700

	
701 701

	
702 702
  /// \brief Map adaptor to convert the \c Value type of a map to
703 703
  /// another type using the default conversion.
704 704

	
705 705
  /// Map adaptor to convert the \c Value type of a \ref concepts::ReadMap
706 706
  /// "readable map" to another type using the default conversion.
707 707
  /// The \c Key type of it is inherited from \c M and the \c Value
708 708
  /// type is \c V.
709 709
  /// This type conforms to the \ref concepts::ReadMap "ReadMap" concept.
710 710
  ///
711 711
  /// The simplest way of using this map is through the convertMap()
712 712
  /// function.
713 713
  template <typename M, typename V>
714 714
  class ConvertMap : public MapBase<typename M::Key, V> {
715 715
    const M &_m;
716 716
  public:
717 717
    ///\e
718 718
    typedef typename M::Key Key;
719 719
    ///\e
720 720
    typedef V Value;
721 721

	
722 722
    /// Constructor
723 723

	
724 724
    /// Constructor.
725 725
    /// \param m The underlying map.
726 726
    ConvertMap(const M &m) : _m(m) {}
727 727

	
728 728
    ///\e
729 729
    Value operator[](const Key &k) const { return _m[k]; }
730 730
  };
731 731

	
732 732
  /// Returns a \c ConvertMap class
733 733

	
734 734
  /// This function just returns a \c ConvertMap class.
735 735
  /// \relates ConvertMap
736 736
  template<typename V, typename M>
737 737
  inline ConvertMap<M, V> convertMap(const M &map) {
738 738
    return ConvertMap<M, V>(map);
739 739
  }
740 740

	
741 741

	
742 742
  /// Applies all map setting operations to two maps
743 743

	
744 744
  /// This map has two \ref concepts::WriteMap "writable map" parameters
745 745
  /// and each write request will be passed to both of them.
746 746
  /// If \c M1 is also \ref concepts::ReadMap "readable", then the read
747 747
  /// operations will return the corresponding values of \c M1.
748 748
  ///
749 749
  /// The \c Key and \c Value types are inherited from \c M1.
750 750
  /// The \c Key and \c Value of \c M2 must be convertible from those
751 751
  /// of \c M1.
752 752
  ///
753 753
  /// The simplest way of using this map is through the forkMap()
754 754
  /// function.
755 755
  template<typename  M1, typename M2>
756 756
  class ForkMap : public MapBase<typename M1::Key, typename M1::Value> {
757 757
    M1 &_m1;
758 758
    M2 &_m2;
759 759
  public:
760 760
    ///\e
761 761
    typedef typename M1::Key Key;
762 762
    ///\e
763 763
    typedef typename M1::Value Value;
764 764

	
765 765
    /// Constructor
766 766
    ForkMap(M1 &m1, M2 &m2) : _m1(m1), _m2(m2) {}
767 767
    /// Returns the value associated with the given key in the first map.
768 768
    Value operator[](const Key &k) const { return _m1[k]; }
769 769
    /// Sets the value associated with the given key in both maps.
770 770
    void set(const Key &k, const Value &v) { _m1.set(k,v); _m2.set(k,v); }
771 771
  };
772 772

	
773 773
  /// Returns a \c ForkMap class
774 774

	
775 775
  /// This function just returns a \c ForkMap class.
776 776
  /// \relates ForkMap
777 777
  template <typename M1, typename M2>
778 778
  inline ForkMap<M1,M2> forkMap(M1 &m1, M2 &m2) {
779 779
    return ForkMap<M1,M2>(m1,m2);
780 780
  }
781 781

	
782 782

	
783 783
  /// Sum of two maps
784 784

	
785 785
  /// This \ref concepts::ReadMap "read-only map" returns the sum
786 786
  /// of the values of the two given maps.
787 787
  /// Its \c Key and \c Value types are inherited from \c M1.
788 788
  /// The \c Key and \c Value of \c M2 must be convertible to those of
789 789
  /// \c M1.
790 790
  ///
791 791
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
792 792
  /// \code
793 793
  ///   AddMap<M1,M2> am(m1,m2);
794 794
  /// \endcode
795 795
  /// <tt>am[x]</tt> will be equal to <tt>m1[x]+m2[x]</tt>.
796 796
  ///
797 797
  /// The simplest way of using this map is through the addMap()
798 798
  /// function.
799 799
  ///
800 800
  /// \sa SubMap, MulMap, DivMap
801 801
  /// \sa ShiftMap, ShiftWriteMap
802 802
  template<typename M1, typename M2>
803 803
  class AddMap : public MapBase<typename M1::Key, typename M1::Value> {
804 804
    const M1 &_m1;
805 805
    const M2 &_m2;
806 806
  public:
807 807
    ///\e
808 808
    typedef typename M1::Key Key;
809 809
    ///\e
810 810
    typedef typename M1::Value Value;
811 811

	
812 812
    /// Constructor
813 813
    AddMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
814 814
    ///\e
815 815
    Value operator[](const Key &k) const { return _m1[k]+_m2[k]; }
816 816
  };
817 817

	
818 818
  /// Returns an \c AddMap class
819 819

	
820 820
  /// This function just returns an \c AddMap class.
821 821
  ///
822 822
  /// For example, if \c m1 and \c m2 are both maps with \c double
823 823
  /// values, then <tt>addMap(m1,m2)[x]</tt> will be equal to
824 824
  /// <tt>m1[x]+m2[x]</tt>.
825 825
  ///
826 826
  /// \relates AddMap
827 827
  template<typename M1, typename M2>
828 828
  inline AddMap<M1, M2> addMap(const M1 &m1, const M2 &m2) {
829 829
    return AddMap<M1, M2>(m1,m2);
830 830
  }
831 831

	
832 832

	
833 833
  /// Difference of two maps
834 834

	
835 835
  /// This \ref concepts::ReadMap "read-only map" returns the difference
836 836
  /// of the values of the two given maps.
837 837
  /// Its \c Key and \c Value types are inherited from \c M1.
838 838
  /// The \c Key and \c Value of \c M2 must be convertible to those of
839 839
  /// \c M1.
840 840
  ///
841 841
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
842 842
  /// \code
843 843
  ///   SubMap<M1,M2> sm(m1,m2);
844 844
  /// \endcode
845 845
  /// <tt>sm[x]</tt> will be equal to <tt>m1[x]-m2[x]</tt>.
846 846
  ///
847 847
  /// The simplest way of using this map is through the subMap()
848 848
  /// function.
849 849
  ///
850 850
  /// \sa AddMap, MulMap, DivMap
851 851
  template<typename M1, typename M2>
852 852
  class SubMap : public MapBase<typename M1::Key, typename M1::Value> {
853 853
    const M1 &_m1;
854 854
    const M2 &_m2;
855 855
  public:
856 856
    ///\e
857 857
    typedef typename M1::Key Key;
858 858
    ///\e
859 859
    typedef typename M1::Value Value;
860 860

	
861 861
    /// Constructor
862 862
    SubMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
863 863
    ///\e
864 864
    Value operator[](const Key &k) const { return _m1[k]-_m2[k]; }
865 865
  };
866 866

	
867 867
  /// Returns a \c SubMap class
868 868

	
869 869
  /// This function just returns a \c SubMap class.
870 870
  ///
871 871
  /// For example, if \c m1 and \c m2 are both maps with \c double
872 872
  /// values, then <tt>subMap(m1,m2)[x]</tt> will be equal to
873 873
  /// <tt>m1[x]-m2[x]</tt>.
874 874
  ///
875 875
  /// \relates SubMap
876 876
  template<typename M1, typename M2>
877 877
  inline SubMap<M1, M2> subMap(const M1 &m1, const M2 &m2) {
878 878
    return SubMap<M1, M2>(m1,m2);
879 879
  }
880 880

	
881 881

	
882 882
  /// Product of two maps
883 883

	
884 884
  /// This \ref concepts::ReadMap "read-only map" returns the product
885 885
  /// of the values of the two given maps.
886 886
  /// Its \c Key and \c Value types are inherited from \c M1.
887 887
  /// The \c Key and \c Value of \c M2 must be convertible to those of
888 888
  /// \c M1.
889 889
  ///
890 890
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
891 891
  /// \code
892 892
  ///   MulMap<M1,M2> mm(m1,m2);
893 893
  /// \endcode
894 894
  /// <tt>mm[x]</tt> will be equal to <tt>m1[x]*m2[x]</tt>.
895 895
  ///
896 896
  /// The simplest way of using this map is through the mulMap()
897 897
  /// function.
898 898
  ///
899 899
  /// \sa AddMap, SubMap, DivMap
900 900
  /// \sa ScaleMap, ScaleWriteMap
901 901
  template<typename M1, typename M2>
902 902
  class MulMap : public MapBase<typename M1::Key, typename M1::Value> {
903 903
    const M1 &_m1;
904 904
    const M2 &_m2;
905 905
  public:
906 906
    ///\e
907 907
    typedef typename M1::Key Key;
908 908
    ///\e
909 909
    typedef typename M1::Value Value;
910 910

	
911 911
    /// Constructor
912 912
    MulMap(const M1 &m1,const M2 &m2) : _m1(m1), _m2(m2) {}
913 913
    ///\e
914 914
    Value operator[](const Key &k) const { return _m1[k]*_m2[k]; }
915 915
  };
916 916

	
917 917
  /// Returns a \c MulMap class
918 918

	
919 919
  /// This function just returns a \c MulMap class.
920 920
  ///
921 921
  /// For example, if \c m1 and \c m2 are both maps with \c double
922 922
  /// values, then <tt>mulMap(m1,m2)[x]</tt> will be equal to
923 923
  /// <tt>m1[x]*m2[x]</tt>.
924 924
  ///
925 925
  /// \relates MulMap
926 926
  template<typename M1, typename M2>
927 927
  inline MulMap<M1, M2> mulMap(const M1 &m1,const M2 &m2) {
928 928
    return MulMap<M1, M2>(m1,m2);
929 929
  }
930 930

	
931 931

	
932 932
  /// Quotient of two maps
933 933

	
934 934
  /// This \ref concepts::ReadMap "read-only map" returns the quotient
935 935
  /// of the values of the two given maps.
936 936
  /// Its \c Key and \c Value types are inherited from \c M1.
937 937
  /// The \c Key and \c Value of \c M2 must be convertible to those of
938 938
  /// \c M1.
939 939
  ///
940 940
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
941 941
  /// \code
942 942
  ///   DivMap<M1,M2> dm(m1,m2);
943 943
  /// \endcode
944 944
  /// <tt>dm[x]</tt> will be equal to <tt>m1[x]/m2[x]</tt>.
945 945
  ///
946 946
  /// The simplest way of using this map is through the divMap()
947 947
  /// function.
948 948
  ///
949 949
  /// \sa AddMap, SubMap, MulMap
950 950
  template<typename M1, typename M2>
951 951
  class DivMap : public MapBase<typename M1::Key, typename M1::Value> {
952 952
    const M1 &_m1;
953 953
    const M2 &_m2;
954 954
  public:
955 955
    ///\e
956 956
    typedef typename M1::Key Key;
957 957
    ///\e
958 958
    typedef typename M1::Value Value;
959 959

	
960 960
    /// Constructor
961 961
    DivMap(const M1 &m1,const M2 &m2) : _m1(m1), _m2(m2) {}
962 962
    ///\e
963 963
    Value operator[](const Key &k) const { return _m1[k]/_m2[k]; }
964 964
  };
965 965

	
966 966
  /// Returns a \c DivMap class
967 967

	
968 968
  /// This function just returns a \c DivMap class.
969 969
  ///
970 970
  /// For example, if \c m1 and \c m2 are both maps with \c double
971 971
  /// values, then <tt>divMap(m1,m2)[x]</tt> will be equal to
972 972
  /// <tt>m1[x]/m2[x]</tt>.
973 973
  ///
974 974
  /// \relates DivMap
975 975
  template<typename M1, typename M2>
976 976
  inline DivMap<M1, M2> divMap(const M1 &m1,const M2 &m2) {
977 977
    return DivMap<M1, M2>(m1,m2);
978 978
  }
979 979

	
980 980

	
981 981
  /// Shifts a map with a constant.
982 982

	
983 983
  /// This \ref concepts::ReadMap "read-only map" returns the sum of
984 984
  /// the given map and a constant value (i.e. it shifts the map with
985 985
  /// the constant). Its \c Key and \c Value are inherited from \c M.
986 986
  ///
987 987
  /// Actually,
988 988
  /// \code
989 989
  ///   ShiftMap<M> sh(m,v);
990 990
  /// \endcode
991 991
  /// is equivalent to
992 992
  /// \code
993 993
  ///   ConstMap<M::Key, M::Value> cm(v);
994 994
  ///   AddMap<M, ConstMap<M::Key, M::Value> > sh(m,cm);
995 995
  /// \endcode
996 996
  ///
997 997
  /// The simplest way of using this map is through the shiftMap()
998 998
  /// function.
999 999
  ///
1000 1000
  /// \sa ShiftWriteMap
1001 1001
  template<typename M, typename C = typename M::Value>
1002 1002
  class ShiftMap : public MapBase<typename M::Key, typename M::Value> {
1003 1003
    const M &_m;
1004 1004
    C _v;
1005 1005
  public:
1006 1006
    ///\e
1007 1007
    typedef typename M::Key Key;
1008 1008
    ///\e
1009 1009
    typedef typename M::Value Value;
1010 1010

	
1011 1011
    /// Constructor
1012 1012

	
1013 1013
    /// Constructor.
1014 1014
    /// \param m The undelying map.
1015 1015
    /// \param v The constant value.
1016 1016
    ShiftMap(const M &m, const C &v) : _m(m), _v(v) {}
1017 1017
    ///\e
1018 1018
    Value operator[](const Key &k) const { return _m[k]+_v; }
1019 1019
  };
1020 1020

	
1021 1021
  /// Shifts a map with a constant (read-write version).
1022 1022

	
1023 1023
  /// This \ref concepts::ReadWriteMap "read-write map" returns the sum
1024 1024
  /// of the given map and a constant value (i.e. it shifts the map with
1025 1025
  /// the constant). Its \c Key and \c Value are inherited from \c M.
1026 1026
  /// It makes also possible to write the map.
1027 1027
  ///
1028 1028
  /// The simplest way of using this map is through the shiftWriteMap()
1029 1029
  /// function.
1030 1030
  ///
1031 1031
  /// \sa ShiftMap
1032 1032
  template<typename M, typename C = typename M::Value>
1033 1033
  class ShiftWriteMap : public MapBase<typename M::Key, typename M::Value> {
1034 1034
    M &_m;
1035 1035
    C _v;
1036 1036
  public:
1037 1037
    ///\e
1038 1038
    typedef typename M::Key Key;
1039 1039
    ///\e
1040 1040
    typedef typename M::Value Value;
1041 1041

	
1042 1042
    /// Constructor
1043 1043

	
1044 1044
    /// Constructor.
1045 1045
    /// \param m The undelying map.
1046 1046
    /// \param v The constant value.
1047 1047
    ShiftWriteMap(M &m, const C &v) : _m(m), _v(v) {}
1048 1048
    ///\e
1049 1049
    Value operator[](const Key &k) const { return _m[k]+_v; }
1050 1050
    ///\e
1051 1051
    void set(const Key &k, const Value &v) { _m.set(k, v-_v); }
1052 1052
  };
1053 1053

	
1054 1054
  /// Returns a \c ShiftMap class
1055 1055

	
1056 1056
  /// This function just returns a \c ShiftMap class.
1057 1057
  ///
1058 1058
  /// For example, if \c m is a map with \c double values and \c v is
1059 1059
  /// \c double, then <tt>shiftMap(m,v)[x]</tt> will be equal to
1060 1060
  /// <tt>m[x]+v</tt>.
1061 1061
  ///
1062 1062
  /// \relates ShiftMap
1063 1063
  template<typename M, typename C>
1064 1064
  inline ShiftMap<M, C> shiftMap(const M &m, const C &v) {
1065 1065
    return ShiftMap<M, C>(m,v);
1066 1066
  }
1067 1067

	
1068 1068
  /// Returns a \c ShiftWriteMap class
1069 1069

	
1070 1070
  /// This function just returns a \c ShiftWriteMap class.
1071 1071
  ///
1072 1072
  /// For example, if \c m is a map with \c double values and \c v is
1073 1073
  /// \c double, then <tt>shiftWriteMap(m,v)[x]</tt> will be equal to
1074 1074
  /// <tt>m[x]+v</tt>.
1075 1075
  /// Moreover it makes also possible to write the map.
1076 1076
  ///
1077 1077
  /// \relates ShiftWriteMap
1078 1078
  template<typename M, typename C>
1079 1079
  inline ShiftWriteMap<M, C> shiftWriteMap(M &m, const C &v) {
1080 1080
    return ShiftWriteMap<M, C>(m,v);
1081 1081
  }
1082 1082

	
1083 1083

	
1084 1084
  /// Scales a map with a constant.
1085 1085

	
1086 1086
  /// This \ref concepts::ReadMap "read-only map" returns the value of
1087 1087
  /// the given map multiplied from the left side with a constant value.
1088 1088
  /// Its \c Key and \c Value are inherited from \c M.
1089 1089
  ///
1090 1090
  /// Actually,
1091 1091
  /// \code
1092 1092
  ///   ScaleMap<M> sc(m,v);
1093 1093
  /// \endcode
1094 1094
  /// is equivalent to
1095 1095
  /// \code
1096 1096
  ///   ConstMap<M::Key, M::Value> cm(v);
1097 1097
  ///   MulMap<ConstMap<M::Key, M::Value>, M> sc(cm,m);
1098 1098
  /// \endcode
1099 1099
  ///
1100 1100
  /// The simplest way of using this map is through the scaleMap()
1101 1101
  /// function.
1102 1102
  ///
1103 1103
  /// \sa ScaleWriteMap
1104 1104
  template<typename M, typename C = typename M::Value>
1105 1105
  class ScaleMap : public MapBase<typename M::Key, typename M::Value> {
1106 1106
    const M &_m;
1107 1107
    C _v;
1108 1108
  public:
1109 1109
    ///\e
1110 1110
    typedef typename M::Key Key;
1111 1111
    ///\e
1112 1112
    typedef typename M::Value Value;
1113 1113

	
1114 1114
    /// Constructor
1115 1115

	
1116 1116
    /// Constructor.
1117 1117
    /// \param m The undelying map.
1118 1118
    /// \param v The constant value.
1119 1119
    ScaleMap(const M &m, const C &v) : _m(m), _v(v) {}
1120 1120
    ///\e
1121 1121
    Value operator[](const Key &k) const { return _v*_m[k]; }
1122 1122
  };
1123 1123

	
1124 1124
  /// Scales a map with a constant (read-write version).
1125 1125

	
1126 1126
  /// This \ref concepts::ReadWriteMap "read-write map" returns the value of
1127 1127
  /// the given map multiplied from the left side with a constant value.
1128 1128
  /// Its \c Key and \c Value are inherited from \c M.
1129 1129
  /// It can also be used as write map if the \c / operator is defined
1130 1130
  /// between \c Value and \c C and the given multiplier is not zero.
1131 1131
  ///
1132 1132
  /// The simplest way of using this map is through the scaleWriteMap()
1133 1133
  /// function.
1134 1134
  ///
1135 1135
  /// \sa ScaleMap
1136 1136
  template<typename M, typename C = typename M::Value>
1137 1137
  class ScaleWriteMap : public MapBase<typename M::Key, typename M::Value> {
1138 1138
    M &_m;
1139 1139
    C _v;
1140 1140
  public:
1141 1141
    ///\e
1142 1142
    typedef typename M::Key Key;
1143 1143
    ///\e
1144 1144
    typedef typename M::Value Value;
1145 1145

	
1146 1146
    /// Constructor
1147 1147

	
1148 1148
    /// Constructor.
1149 1149
    /// \param m The undelying map.
1150 1150
    /// \param v The constant value.
1151 1151
    ScaleWriteMap(M &m, const C &v) : _m(m), _v(v) {}
1152 1152
    ///\e
1153 1153
    Value operator[](const Key &k) const { return _v*_m[k]; }
1154 1154
    ///\e
1155 1155
    void set(const Key &k, const Value &v) { _m.set(k, v/_v); }
1156 1156
  };
1157 1157

	
1158 1158
  /// Returns a \c ScaleMap class
1159 1159

	
1160 1160
  /// This function just returns a \c ScaleMap class.
1161 1161
  ///
1162 1162
  /// For example, if \c m is a map with \c double values and \c v is
1163 1163
  /// \c double, then <tt>scaleMap(m,v)[x]</tt> will be equal to
1164 1164
  /// <tt>v*m[x]</tt>.
1165 1165
  ///
1166 1166
  /// \relates ScaleMap
1167 1167
  template<typename M, typename C>
1168 1168
  inline ScaleMap<M, C> scaleMap(const M &m, const C &v) {
1169 1169
    return ScaleMap<M, C>(m,v);
1170 1170
  }
1171 1171

	
1172 1172
  /// Returns a \c ScaleWriteMap class
1173 1173

	
1174 1174
  /// This function just returns a \c ScaleWriteMap class.
1175 1175
  ///
1176 1176
  /// For example, if \c m is a map with \c double values and \c v is
1177 1177
  /// \c double, then <tt>scaleWriteMap(m,v)[x]</tt> will be equal to
1178 1178
  /// <tt>v*m[x]</tt>.
1179 1179
  /// Moreover it makes also possible to write the map.
1180 1180
  ///
1181 1181
  /// \relates ScaleWriteMap
1182 1182
  template<typename M, typename C>
1183 1183
  inline ScaleWriteMap<M, C> scaleWriteMap(M &m, const C &v) {
1184 1184
    return ScaleWriteMap<M, C>(m,v);
1185 1185
  }
1186 1186

	
1187 1187

	
1188 1188
  /// Negative of a map
1189 1189

	
1190 1190
  /// This \ref concepts::ReadMap "read-only map" returns the negative
1191 1191
  /// of the values of the given map (using the unary \c - operator).
1192 1192
  /// Its \c Key and \c Value are inherited from \c M.
1193 1193
  ///
1194 1194
  /// If M::Value is \c int, \c double etc., then
1195 1195
  /// \code
1196 1196
  ///   NegMap<M> neg(m);
1197 1197
  /// \endcode
1198 1198
  /// is equivalent to
1199 1199
  /// \code
1200 1200
  ///   ScaleMap<M> neg(m,-1);
1201 1201
  /// \endcode
1202 1202
  ///
1203 1203
  /// The simplest way of using this map is through the negMap()
1204 1204
  /// function.
1205 1205
  ///
1206 1206
  /// \sa NegWriteMap
1207 1207
  template<typename M>
1208 1208
  class NegMap : public MapBase<typename M::Key, typename M::Value> {
1209 1209
    const M& _m;
1210 1210
  public:
1211 1211
    ///\e
1212 1212
    typedef typename M::Key Key;
1213 1213
    ///\e
1214 1214
    typedef typename M::Value Value;
1215 1215

	
1216 1216
    /// Constructor
1217 1217
    NegMap(const M &m) : _m(m) {}
1218 1218
    ///\e
1219 1219
    Value operator[](const Key &k) const { return -_m[k]; }
1220 1220
  };
1221 1221

	
1222 1222
  /// Negative of a map (read-write version)
1223 1223

	
1224 1224
  /// This \ref concepts::ReadWriteMap "read-write map" returns the
1225 1225
  /// negative of the values of the given map (using the unary \c -
1226 1226
  /// operator).
1227 1227
  /// Its \c Key and \c Value are inherited from \c M.
1228 1228
  /// It makes also possible to write the map.
1229 1229
  ///
1230 1230
  /// If M::Value is \c int, \c double etc., then
1231 1231
  /// \code
1232 1232
  ///   NegWriteMap<M> neg(m);
1233 1233
  /// \endcode
1234 1234
  /// is equivalent to
1235 1235
  /// \code
1236 1236
  ///   ScaleWriteMap<M> neg(m,-1);
1237 1237
  /// \endcode
1238 1238
  ///
1239 1239
  /// The simplest way of using this map is through the negWriteMap()
1240 1240
  /// function.
1241 1241
  ///
1242 1242
  /// \sa NegMap
1243 1243
  template<typename M>
1244 1244
  class NegWriteMap : public MapBase<typename M::Key, typename M::Value> {
1245 1245
    M &_m;
1246 1246
  public:
1247 1247
    ///\e
1248 1248
    typedef typename M::Key Key;
1249 1249
    ///\e
1250 1250
    typedef typename M::Value Value;
1251 1251

	
1252 1252
    /// Constructor
1253 1253
    NegWriteMap(M &m) : _m(m) {}
1254 1254
    ///\e
1255 1255
    Value operator[](const Key &k) const { return -_m[k]; }
1256 1256
    ///\e
1257 1257
    void set(const Key &k, const Value &v) { _m.set(k, -v); }
1258 1258
  };
1259 1259

	
1260 1260
  /// Returns a \c NegMap class
1261 1261

	
1262 1262
  /// This function just returns a \c NegMap class.
1263 1263
  ///
1264 1264
  /// For example, if \c m is a map with \c double values, then
1265 1265
  /// <tt>negMap(m)[x]</tt> will be equal to <tt>-m[x]</tt>.
1266 1266
  ///
1267 1267
  /// \relates NegMap
1268 1268
  template <typename M>
1269 1269
  inline NegMap<M> negMap(const M &m) {
1270 1270
    return NegMap<M>(m);
1271 1271
  }
1272 1272

	
1273 1273
  /// Returns a \c NegWriteMap class
1274 1274

	
1275 1275
  /// This function just returns a \c NegWriteMap class.
1276 1276
  ///
1277 1277
  /// For example, if \c m is a map with \c double values, then
1278 1278
  /// <tt>negWriteMap(m)[x]</tt> will be equal to <tt>-m[x]</tt>.
1279 1279
  /// Moreover it makes also possible to write the map.
1280 1280
  ///
1281 1281
  /// \relates NegWriteMap
1282 1282
  template <typename M>
1283 1283
  inline NegWriteMap<M> negWriteMap(M &m) {
1284 1284
    return NegWriteMap<M>(m);
1285 1285
  }
1286 1286

	
1287 1287

	
1288 1288
  /// Absolute value of a map
1289 1289

	
1290 1290
  /// This \ref concepts::ReadMap "read-only map" returns the absolute
1291 1291
  /// value of the values of the given map.
1292 1292
  /// Its \c Key and \c Value are inherited from \c M.
1293 1293
  /// \c Value must be comparable to \c 0 and the unary \c -
1294 1294
  /// operator must be defined for it, of course.
1295 1295
  ///
1296 1296
  /// The simplest way of using this map is through the absMap()
1297 1297
  /// function.
1298 1298
  template<typename M>
1299 1299
  class AbsMap : public MapBase<typename M::Key, typename M::Value> {
1300 1300
    const M &_m;
1301 1301
  public:
1302 1302
    ///\e
1303 1303
    typedef typename M::Key Key;
1304 1304
    ///\e
1305 1305
    typedef typename M::Value Value;
1306 1306

	
1307 1307
    /// Constructor
1308 1308
    AbsMap(const M &m) : _m(m) {}
1309 1309
    ///\e
1310 1310
    Value operator[](const Key &k) const {
1311 1311
      Value tmp = _m[k];
1312 1312
      return tmp >= 0 ? tmp : -tmp;
1313 1313
    }
1314 1314

	
1315 1315
  };
1316 1316

	
1317 1317
  /// Returns an \c AbsMap class
1318 1318

	
1319 1319
  /// This function just returns an \c AbsMap class.
1320 1320
  ///
1321 1321
  /// For example, if \c m is a map with \c double values, then
1322 1322
  /// <tt>absMap(m)[x]</tt> will be equal to <tt>m[x]</tt> if
1323 1323
  /// it is positive or zero and <tt>-m[x]</tt> if <tt>m[x]</tt> is
1324 1324
  /// negative.
1325 1325
  ///
1326 1326
  /// \relates AbsMap
1327 1327
  template<typename M>
1328 1328
  inline AbsMap<M> absMap(const M &m) {
1329 1329
    return AbsMap<M>(m);
1330 1330
  }
1331 1331

	
1332 1332
  /// @}
1333 1333

	
1334 1334
  // Logical maps and map adaptors:
1335 1335

	
1336 1336
  /// \addtogroup maps
1337 1337
  /// @{
1338 1338

	
1339 1339
  /// Constant \c true map.
1340 1340

	
1341 1341
  /// This \ref concepts::ReadMap "read-only map" assigns \c true to
1342 1342
  /// each key.
1343 1343
  ///
1344 1344
  /// Note that
1345 1345
  /// \code
1346 1346
  ///   TrueMap<K> tm;
1347 1347
  /// \endcode
1348 1348
  /// is equivalent to
1349 1349
  /// \code
1350 1350
  ///   ConstMap<K,bool> tm(true);
1351 1351
  /// \endcode
1352 1352
  ///
1353 1353
  /// \sa FalseMap
1354 1354
  /// \sa ConstMap
1355 1355
  template <typename K>
1356 1356
  class TrueMap : public MapBase<K, bool> {
1357 1357
  public:
1358 1358
    ///\e
1359 1359
    typedef K Key;
1360 1360
    ///\e
1361 1361
    typedef bool Value;
1362 1362

	
1363 1363
    /// Gives back \c true.
1364 1364
    Value operator[](const Key&) const { return true; }
1365 1365
  };
1366 1366

	
1367 1367
  /// Returns a \c TrueMap class
1368 1368

	
1369 1369
  /// This function just returns a \c TrueMap class.
1370 1370
  /// \relates TrueMap
1371 1371
  template<typename K>
1372 1372
  inline TrueMap<K> trueMap() {
1373 1373
    return TrueMap<K>();
1374 1374
  }
1375 1375

	
1376 1376

	
1377 1377
  /// Constant \c false map.
1378 1378

	
1379 1379
  /// This \ref concepts::ReadMap "read-only map" assigns \c false to
1380 1380
  /// each key.
1381 1381
  ///
1382 1382
  /// Note that
1383 1383
  /// \code
1384 1384
  ///   FalseMap<K> fm;
1385 1385
  /// \endcode
1386 1386
  /// is equivalent to
1387 1387
  /// \code
1388 1388
  ///   ConstMap<K,bool> fm(false);
1389 1389
  /// \endcode
1390 1390
  ///
1391 1391
  /// \sa TrueMap
1392 1392
  /// \sa ConstMap
1393 1393
  template <typename K>
1394 1394
  class FalseMap : public MapBase<K, bool> {
1395 1395
  public:
1396 1396
    ///\e
1397 1397
    typedef K Key;
1398 1398
    ///\e
1399 1399
    typedef bool Value;
1400 1400

	
1401 1401
    /// Gives back \c false.
1402 1402
    Value operator[](const Key&) const { return false; }
1403 1403
  };
1404 1404

	
1405 1405
  /// Returns a \c FalseMap class
1406 1406

	
1407 1407
  /// This function just returns a \c FalseMap class.
1408 1408
  /// \relates FalseMap
1409 1409
  template<typename K>
1410 1410
  inline FalseMap<K> falseMap() {
1411 1411
    return FalseMap<K>();
1412 1412
  }
1413 1413

	
1414 1414
  /// @}
1415 1415

	
1416 1416
  /// \addtogroup map_adaptors
1417 1417
  /// @{
1418 1418

	
1419 1419
  /// Logical 'and' of two maps
1420 1420

	
1421 1421
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1422 1422
  /// 'and' of the values of the two given maps.
1423 1423
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1424 1424
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1425 1425
  ///
1426 1426
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1427 1427
  /// \code
1428 1428
  ///   AndMap<M1,M2> am(m1,m2);
1429 1429
  /// \endcode
1430 1430
  /// <tt>am[x]</tt> will be equal to <tt>m1[x]&&m2[x]</tt>.
1431 1431
  ///
1432 1432
  /// The simplest way of using this map is through the andMap()
1433 1433
  /// function.
1434 1434
  ///
1435 1435
  /// \sa OrMap
1436 1436
  /// \sa NotMap, NotWriteMap
1437 1437
  template<typename M1, typename M2>
1438 1438
  class AndMap : public MapBase<typename M1::Key, bool> {
1439 1439
    const M1 &_m1;
1440 1440
    const M2 &_m2;
1441 1441
  public:
1442 1442
    ///\e
1443 1443
    typedef typename M1::Key Key;
1444 1444
    ///\e
1445 1445
    typedef bool Value;
1446 1446

	
1447 1447
    /// Constructor
1448 1448
    AndMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1449 1449
    ///\e
1450 1450
    Value operator[](const Key &k) const { return _m1[k]&&_m2[k]; }
1451 1451
  };
1452 1452

	
1453 1453
  /// Returns an \c AndMap class
1454 1454

	
1455 1455
  /// This function just returns an \c AndMap class.
1456 1456
  ///
1457 1457
  /// For example, if \c m1 and \c m2 are both maps with \c bool values,
1458 1458
  /// then <tt>andMap(m1,m2)[x]</tt> will be equal to
1459 1459
  /// <tt>m1[x]&&m2[x]</tt>.
1460 1460
  ///
1461 1461
  /// \relates AndMap
1462 1462
  template<typename M1, typename M2>
1463 1463
  inline AndMap<M1, M2> andMap(const M1 &m1, const M2 &m2) {
1464 1464
    return AndMap<M1, M2>(m1,m2);
1465 1465
  }
1466 1466

	
1467 1467

	
1468 1468
  /// Logical 'or' of two maps
1469 1469

	
1470 1470
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1471 1471
  /// 'or' of the values of the two given maps.
1472 1472
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1473 1473
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1474 1474
  ///
1475 1475
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1476 1476
  /// \code
1477 1477
  ///   OrMap<M1,M2> om(m1,m2);
1478 1478
  /// \endcode
1479 1479
  /// <tt>om[x]</tt> will be equal to <tt>m1[x]||m2[x]</tt>.
1480 1480
  ///
1481 1481
  /// The simplest way of using this map is through the orMap()
1482 1482
  /// function.
1483 1483
  ///
1484 1484
  /// \sa AndMap
1485 1485
  /// \sa NotMap, NotWriteMap
1486 1486
  template<typename M1, typename M2>
1487 1487
  class OrMap : public MapBase<typename M1::Key, bool> {
1488 1488
    const M1 &_m1;
1489 1489
    const M2 &_m2;
1490 1490
  public:
1491 1491
    ///\e
1492 1492
    typedef typename M1::Key Key;
1493 1493
    ///\e
1494 1494
    typedef bool Value;
1495 1495

	
1496 1496
    /// Constructor
1497 1497
    OrMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1498 1498
    ///\e
1499 1499
    Value operator[](const Key &k) const { return _m1[k]||_m2[k]; }
1500 1500
  };
1501 1501

	
1502 1502
  /// Returns an \c OrMap class
1503 1503

	
1504 1504
  /// This function just returns an \c OrMap class.
1505 1505
  ///
1506 1506
  /// For example, if \c m1 and \c m2 are both maps with \c bool values,
1507 1507
  /// then <tt>orMap(m1,m2)[x]</tt> will be equal to
1508 1508
  /// <tt>m1[x]||m2[x]</tt>.
1509 1509
  ///
1510 1510
  /// \relates OrMap
1511 1511
  template<typename M1, typename M2>
1512 1512
  inline OrMap<M1, M2> orMap(const M1 &m1, const M2 &m2) {
1513 1513
    return OrMap<M1, M2>(m1,m2);
1514 1514
  }
1515 1515

	
1516 1516

	
1517 1517
  /// Logical 'not' of a map
1518 1518

	
1519 1519
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1520 1520
  /// negation of the values of the given map.
1521 1521
  /// Its \c Key is inherited from \c M and its \c Value is \c bool.
1522 1522
  ///
1523 1523
  /// The simplest way of using this map is through the notMap()
1524 1524
  /// function.
1525 1525
  ///
1526 1526
  /// \sa NotWriteMap
1527 1527
  template <typename M>
1528 1528
  class NotMap : public MapBase<typename M::Key, bool> {
1529 1529
    const M &_m;
1530 1530
  public:
1531 1531
    ///\e
1532 1532
    typedef typename M::Key Key;
1533 1533
    ///\e
1534 1534
    typedef bool Value;
1535 1535

	
1536 1536
    /// Constructor
1537 1537
    NotMap(const M &m) : _m(m) {}
1538 1538
    ///\e
1539 1539
    Value operator[](const Key &k) const { return !_m[k]; }
1540 1540
  };
1541 1541

	
1542 1542
  /// Logical 'not' of a map (read-write version)
1543 1543

	
1544 1544
  /// This \ref concepts::ReadWriteMap "read-write map" returns the
1545 1545
  /// logical negation of the values of the given map.
1546 1546
  /// Its \c Key is inherited from \c M and its \c Value is \c bool.
1547 1547
  /// It makes also possible to write the map. When a value is set,
1548 1548
  /// the opposite value is set to the original map.
1549 1549
  ///
1550 1550
  /// The simplest way of using this map is through the notWriteMap()
1551 1551
  /// function.
1552 1552
  ///
1553 1553
  /// \sa NotMap
1554 1554
  template <typename M>
1555 1555
  class NotWriteMap : public MapBase<typename M::Key, bool> {
1556 1556
    M &_m;
1557 1557
  public:
1558 1558
    ///\e
1559 1559
    typedef typename M::Key Key;
1560 1560
    ///\e
1561 1561
    typedef bool Value;
1562 1562

	
1563 1563
    /// Constructor
1564 1564
    NotWriteMap(M &m) : _m(m) {}
1565 1565
    ///\e
1566 1566
    Value operator[](const Key &k) const { return !_m[k]; }
1567 1567
    ///\e
1568 1568
    void set(const Key &k, bool v) { _m.set(k, !v); }
1569 1569
  };
1570 1570

	
1571 1571
  /// Returns a \c NotMap class
1572 1572

	
1573 1573
  /// This function just returns a \c NotMap class.
1574 1574
  ///
1575 1575
  /// For example, if \c m is a map with \c bool values, then
1576 1576
  /// <tt>notMap(m)[x]</tt> will be equal to <tt>!m[x]</tt>.
1577 1577
  ///
1578 1578
  /// \relates NotMap
1579 1579
  template <typename M>
1580 1580
  inline NotMap<M> notMap(const M &m) {
1581 1581
    return NotMap<M>(m);
1582 1582
  }
1583 1583

	
1584 1584
  /// Returns a \c NotWriteMap class
1585 1585

	
1586 1586
  /// This function just returns a \c NotWriteMap class.
1587 1587
  ///
1588 1588
  /// For example, if \c m is a map with \c bool values, then
1589 1589
  /// <tt>notWriteMap(m)[x]</tt> will be equal to <tt>!m[x]</tt>.
1590 1590
  /// Moreover it makes also possible to write the map.
1591 1591
  ///
1592 1592
  /// \relates NotWriteMap
1593 1593
  template <typename M>
1594 1594
  inline NotWriteMap<M> notWriteMap(M &m) {
1595 1595
    return NotWriteMap<M>(m);
1596 1596
  }
1597 1597

	
1598 1598

	
1599 1599
  /// Combination of two maps using the \c == operator
1600 1600

	
1601 1601
  /// This \ref concepts::ReadMap "read-only map" assigns \c true to
1602 1602
  /// the keys for which the corresponding values of the two maps are
1603 1603
  /// equal.
1604 1604
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1605 1605
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1606 1606
  ///
1607 1607
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1608 1608
  /// \code
1609 1609
  ///   EqualMap<M1,M2> em(m1,m2);
1610 1610
  /// \endcode
1611 1611
  /// <tt>em[x]</tt> will be equal to <tt>m1[x]==m2[x]</tt>.
1612 1612
  ///
1613 1613
  /// The simplest way of using this map is through the equalMap()
1614 1614
  /// function.
1615 1615
  ///
1616 1616
  /// \sa LessMap
1617 1617
  template<typename M1, typename M2>
1618 1618
  class EqualMap : public MapBase<typename M1::Key, bool> {
1619 1619
    const M1 &_m1;
1620 1620
    const M2 &_m2;
1621 1621
  public:
1622 1622
    ///\e
1623 1623
    typedef typename M1::Key Key;
1624 1624
    ///\e
1625 1625
    typedef bool Value;
1626 1626

	
1627 1627
    /// Constructor
1628 1628
    EqualMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1629 1629
    ///\e
1630 1630
    Value operator[](const Key &k) const { return _m1[k]==_m2[k]; }
1631 1631
  };
1632 1632

	
1633 1633
  /// Returns an \c EqualMap class
1634 1634

	
1635 1635
  /// This function just returns an \c EqualMap class.
1636 1636
  ///
1637 1637
  /// For example, if \c m1 and \c m2 are maps with keys and values of
1638 1638
  /// the same type, then <tt>equalMap(m1,m2)[x]</tt> will be equal to
1639 1639
  /// <tt>m1[x]==m2[x]</tt>.
1640 1640
  ///
1641 1641
  /// \relates EqualMap
1642 1642
  template<typename M1, typename M2>
1643 1643
  inline EqualMap<M1, M2> equalMap(const M1 &m1, const M2 &m2) {
1644 1644
    return EqualMap<M1, M2>(m1,m2);
1645 1645
  }
1646 1646

	
1647 1647

	
1648 1648
  /// Combination of two maps using the \c < operator
1649 1649

	
1650 1650
  /// This \ref concepts::ReadMap "read-only map" assigns \c true to
1651 1651
  /// the keys for which the corresponding value of the first map is
1652 1652
  /// less then the value of the second map.
1653 1653
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1654 1654
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1655 1655
  ///
1656 1656
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1657 1657
  /// \code
1658 1658
  ///   LessMap<M1,M2> lm(m1,m2);
1659 1659
  /// \endcode
1660 1660
  /// <tt>lm[x]</tt> will be equal to <tt>m1[x]<m2[x]</tt>.
1661 1661
  ///
1662 1662
  /// The simplest way of using this map is through the lessMap()
1663 1663
  /// function.
1664 1664
  ///
1665 1665
  /// \sa EqualMap
1666 1666
  template<typename M1, typename M2>
1667 1667
  class LessMap : public MapBase<typename M1::Key, bool> {
1668 1668
    const M1 &_m1;
1669 1669
    const M2 &_m2;
1670 1670
  public:
1671 1671
    ///\e
1672 1672
    typedef typename M1::Key Key;
1673 1673
    ///\e
1674 1674
    typedef bool Value;
1675 1675

	
1676 1676
    /// Constructor
1677 1677
    LessMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1678 1678
    ///\e
1679 1679
    Value operator[](const Key &k) const { return _m1[k]<_m2[k]; }
1680 1680
  };
1681 1681

	
1682 1682
  /// Returns an \c LessMap class
1683 1683

	
1684 1684
  /// This function just returns an \c LessMap class.
1685 1685
  ///
1686 1686
  /// For example, if \c m1 and \c m2 are maps with keys and values of
1687 1687
  /// the same type, then <tt>lessMap(m1,m2)[x]</tt> will be equal to
1688 1688
  /// <tt>m1[x]<m2[x]</tt>.
1689 1689
  ///
1690 1690
  /// \relates LessMap
1691 1691
  template<typename M1, typename M2>
1692 1692
  inline LessMap<M1, M2> lessMap(const M1 &m1, const M2 &m2) {
1693 1693
    return LessMap<M1, M2>(m1,m2);
1694 1694
  }
1695 1695

	
1696 1696
  namespace _maps_bits {
1697 1697

	
1698 1698
    template <typename _Iterator, typename Enable = void>
1699 1699
    struct IteratorTraits {
1700 1700
      typedef typename std::iterator_traits<_Iterator>::value_type Value;
1701 1701
    };
1702 1702

	
1703 1703
    template <typename _Iterator>
1704 1704
    struct IteratorTraits<_Iterator,
1705 1705
      typename exists<typename _Iterator::container_type>::type>
1706 1706
    {
1707 1707
      typedef typename _Iterator::container_type::value_type Value;
1708 1708
    };
1709 1709

	
1710 1710
  }
1711 1711

	
1712 1712
  /// @}
1713 1713

	
1714 1714
  /// \addtogroup maps
1715 1715
  /// @{
1716 1716

	
1717 1717
  /// \brief Writable bool map for logging each \c true assigned element
1718 1718
  ///
1719 1719
  /// A \ref concepts::WriteMap "writable" bool map for logging
1720 1720
  /// each \c true assigned element, i.e it copies subsequently each
1721 1721
  /// keys set to \c true to the given iterator.
1722 1722
  /// The most important usage of it is storing certain nodes or arcs
1723 1723
  /// that were marked \c true by an algorithm.
1724 1724
  ///
1725 1725
  /// There are several algorithms that provide solutions through bool
1726 1726
  /// maps and most of them assign \c true at most once for each key.
1727 1727
  /// In these cases it is a natural request to store each \c true
1728 1728
  /// assigned elements (in order of the assignment), which can be
1729 1729
  /// easily done with LoggerBoolMap.
1730 1730
  ///
1731 1731
  /// The simplest way of using this map is through the loggerBoolMap()
1732 1732
  /// function.
1733 1733
  ///
1734 1734
  /// \tparam IT The type of the iterator.
1735 1735
  /// \tparam KEY The key type of the map. The default value set
1736 1736
  /// according to the iterator type should work in most cases.
1737 1737
  ///
1738 1738
  /// \note The container of the iterator must contain enough space
1739 1739
  /// for the elements or the iterator should be an inserter iterator.
1740 1740
#ifdef DOXYGEN
1741 1741
  template <typename IT, typename KEY>
1742 1742
#else
1743 1743
  template <typename IT,
1744 1744
            typename KEY = typename _maps_bits::IteratorTraits<IT>::Value>
1745 1745
#endif
1746 1746
  class LoggerBoolMap : public MapBase<KEY, bool> {
1747 1747
  public:
1748 1748

	
1749 1749
    ///\e
1750 1750
    typedef KEY Key;
1751 1751
    ///\e
1752 1752
    typedef bool Value;
1753 1753
    ///\e
1754 1754
    typedef IT Iterator;
1755 1755

	
1756 1756
    /// Constructor
1757 1757
    LoggerBoolMap(Iterator it)
1758 1758
      : _begin(it), _end(it) {}
1759 1759

	
1760 1760
    /// Gives back the given iterator set for the first key
1761 1761
    Iterator begin() const {
1762 1762
      return _begin;
1763 1763
    }
1764 1764

	
1765 1765
    /// Gives back the the 'after the last' iterator
1766 1766
    Iterator end() const {
1767 1767
      return _end;
1768 1768
    }
1769 1769

	
1770 1770
    /// The set function of the map
1771 1771
    void set(const Key& key, Value value) {
1772 1772
      if (value) {
1773 1773
        *_end++ = key;
1774 1774
      }
1775 1775
    }
1776 1776

	
1777 1777
  private:
1778 1778
    Iterator _begin;
1779 1779
    Iterator _end;
1780 1780
  };
1781 1781

	
1782 1782
  /// Returns a \c LoggerBoolMap class
1783 1783

	
1784 1784
  /// This function just returns a \c LoggerBoolMap class.
1785 1785
  ///
1786 1786
  /// The most important usage of it is storing certain nodes or arcs
1787 1787
  /// that were marked \c true by an algorithm.
1788 1788
  /// For example, it makes easier to store the nodes in the processing
1789 1789
  /// order of Dfs algorithm, as the following examples show.
1790 1790
  /// \code
1791 1791
  ///   std::vector<Node> v;
1792 1792
  ///   dfs(g).processedMap(loggerBoolMap(std::back_inserter(v))).run(s);
1793 1793
  /// \endcode
1794 1794
  /// \code
1795 1795
  ///   std::vector<Node> v(countNodes(g));
1796 1796
  ///   dfs(g).processedMap(loggerBoolMap(v.begin())).run(s);
1797 1797
  /// \endcode
1798 1798
  ///
1799 1799
  /// \note The container of the iterator must contain enough space
1800 1800
  /// for the elements or the iterator should be an inserter iterator.
1801 1801
  ///
1802 1802
  /// \note LoggerBoolMap is just \ref concepts::WriteMap "writable", so
1803 1803
  /// it cannot be used when a readable map is needed, for example, as
1804 1804
  /// \c ReachedMap for \c Bfs, \c Dfs and \c Dijkstra algorithms.
1805 1805
  ///
1806 1806
  /// \relates LoggerBoolMap
1807 1807
  template<typename Iterator>
1808 1808
  inline LoggerBoolMap<Iterator> loggerBoolMap(Iterator it) {
1809 1809
    return LoggerBoolMap<Iterator>(it);
1810 1810
  }
1811 1811

	
1812 1812
  /// @}
1813 1813

	
1814 1814
  /// \addtogroup graph_maps
1815 1815
  /// @{
1816 1816

	
1817 1817
  /// \brief Provides an immutable and unique id for each item in a graph.
1818 1818
  ///
1819 1819
  /// IdMap provides a unique and immutable id for each item of the
1820 1820
  /// same type (\c Node, \c Arc or \c Edge) in a graph. This id is
1821 1821
  ///  - \b unique: different items get different ids,
1822 1822
  ///  - \b immutable: the id of an item does not change (even if you
1823 1823
  ///    delete other nodes).
1824 1824
  ///
1825 1825
  /// Using this map you get access (i.e. can read) the inner id values of
1826 1826
  /// the items stored in the graph, which is returned by the \c id()
1827 1827
  /// function of the graph. This map can be inverted with its member
1828 1828
  /// class \c InverseMap or with the \c operator()() member.
1829 1829
  ///
1830 1830
  /// \tparam GR The graph type.
1831 1831
  /// \tparam K The key type of the map (\c GR::Node, \c GR::Arc or
1832 1832
  /// \c GR::Edge).
1833 1833
  ///
1834 1834
  /// \see RangeIdMap
1835 1835
  template <typename GR, typename K>
1836 1836
  class IdMap : public MapBase<K, int> {
1837 1837
  public:
1838 1838
    /// The graph type of IdMap.
1839 1839
    typedef GR Graph;
1840 1840
    typedef GR Digraph;
1841 1841
    /// The key type of IdMap (\c Node, \c Arc or \c Edge).
1842 1842
    typedef K Item;
1843 1843
    /// The key type of IdMap (\c Node, \c Arc or \c Edge).
1844 1844
    typedef K Key;
1845 1845
    /// The value type of IdMap.
1846 1846
    typedef int Value;
1847 1847

	
1848 1848
    /// \brief Constructor.
1849 1849
    ///
1850 1850
    /// Constructor of the map.
1851 1851
    explicit IdMap(const Graph& graph) : _graph(&graph) {}
1852 1852

	
1853 1853
    /// \brief Gives back the \e id of the item.
1854 1854
    ///
1855 1855
    /// Gives back the immutable and unique \e id of the item.
1856 1856
    int operator[](const Item& item) const { return _graph->id(item);}
1857 1857

	
1858 1858
    /// \brief Gives back the \e item by its id.
1859 1859
    ///
1860 1860
    /// Gives back the \e item by its id.
1861 1861
    Item operator()(int id) { return _graph->fromId(id, Item()); }
1862 1862

	
1863 1863
  private:
1864 1864
    const Graph* _graph;
1865 1865

	
1866 1866
  public:
1867 1867

	
1868 1868
    /// \brief The inverse map type of IdMap.
1869 1869
    ///
1870 1870
    /// The inverse map type of IdMap. The subscript operator gives back
1871 1871
    /// an item by its id.
1872 1872
    /// This type conforms to the \ref concepts::ReadMap "ReadMap" concept.
1873 1873
    /// \see inverse()
1874 1874
    class InverseMap {
1875 1875
    public:
1876 1876

	
1877 1877
      /// \brief Constructor.
1878 1878
      ///
1879 1879
      /// Constructor for creating an id-to-item map.
1880 1880
      explicit InverseMap(const Graph& graph) : _graph(&graph) {}
1881 1881

	
1882 1882
      /// \brief Constructor.
1883 1883
      ///
1884 1884
      /// Constructor for creating an id-to-item map.
1885 1885
      explicit InverseMap(const IdMap& map) : _graph(map._graph) {}
1886 1886

	
1887 1887
      /// \brief Gives back an item by its id.
1888 1888
      ///
1889 1889
      /// Gives back an item by its id.
1890 1890
      Item operator[](int id) const { return _graph->fromId(id, Item());}
1891 1891

	
1892 1892
    private:
1893 1893
      const Graph* _graph;
1894 1894
    };
1895 1895

	
1896 1896
    /// \brief Gives back the inverse of the map.
1897 1897
    ///
1898 1898
    /// Gives back the inverse of the IdMap.
1899 1899
    InverseMap inverse() const { return InverseMap(*_graph);}
1900 1900
  };
1901 1901

	
1902 1902
  /// \brief Returns an \c IdMap class.
1903 1903
  ///
1904 1904
  /// This function just returns an \c IdMap class.
1905 1905
  /// \relates IdMap
1906 1906
  template <typename K, typename GR>
1907 1907
  inline IdMap<GR, K> idMap(const GR& graph) {
1908 1908
    return IdMap<GR, K>(graph);
1909 1909
  }
1910 1910

	
1911 1911
  /// \brief General cross reference graph map type.
1912 1912

	
1913 1913
  /// This class provides simple invertable graph maps.
1914 1914
  /// It wraps a standard graph map (\c NodeMap, \c ArcMap or \c EdgeMap)
1915 1915
  /// and if a key is set to a new value, then stores it in the inverse map.
1916 1916
  /// The graph items can be accessed by their values either using
1917 1917
  /// \c InverseMap or \c operator()(), and the values of the map can be
1918 1918
  /// accessed with an STL compatible forward iterator (\c ValueIt).
1919 1919
  ///
1920 1920
  /// This map is intended to be used when all associated values are
1921 1921
  /// different (the map is actually invertable) or there are only a few
1922 1922
  /// items with the same value.
1923 1923
  /// Otherwise consider to use \c IterableValueMap, which is more
1924 1924
  /// suitable and more efficient for such cases. It provides iterators
1925 1925
  /// to traverse the items with the same associated value, but
1926 1926
  /// it does not have \c InverseMap.
1927 1927
  ///
1928 1928
  /// This type is not reference map, so it cannot be modified with
1929 1929
  /// the subscript operator.
1930 1930
  ///
1931 1931
  /// \tparam GR The graph type.
1932 1932
  /// \tparam K The key type of the map (\c GR::Node, \c GR::Arc or
1933 1933
  /// \c GR::Edge).
1934 1934
  /// \tparam V The value type of the map.
1935 1935
  ///
1936 1936
  /// \see IterableValueMap
1937 1937
  template <typename GR, typename K, typename V>
1938 1938
  class CrossRefMap
1939 1939
    : protected ItemSetTraits<GR, K>::template Map<V>::Type {
1940 1940
  private:
1941 1941

	
1942 1942
    typedef typename ItemSetTraits<GR, K>::
1943 1943
      template Map<V>::Type Map;
1944 1944

	
1945 1945
    typedef std::multimap<V, K> Container;
1946 1946
    Container _inv_map;
1947 1947

	
1948 1948
  public:
1949 1949

	
1950 1950
    /// The graph type of CrossRefMap.
1951 1951
    typedef GR Graph;
1952 1952
    typedef GR Digraph;
1953 1953
    /// The key type of CrossRefMap (\c Node, \c Arc or \c Edge).
1954 1954
    typedef K Item;
1955 1955
    /// The key type of CrossRefMap (\c Node, \c Arc or \c Edge).
1956 1956
    typedef K Key;
1957 1957
    /// The value type of CrossRefMap.
1958 1958
    typedef V Value;
1959 1959

	
1960 1960
    /// \brief Constructor.
1961 1961
    ///
1962 1962
    /// Construct a new CrossRefMap for the given graph.
1963 1963
    explicit CrossRefMap(const Graph& graph) : Map(graph) {}
1964 1964

	
1965 1965
    /// \brief Forward iterator for values.
1966 1966
    ///
1967 1967
    /// This iterator is an STL compatible forward
1968 1968
    /// iterator on the values of the map. The values can
1969 1969
    /// be accessed in the <tt>[beginValue, endValue)</tt> range.
1970 1970
    /// They are considered with multiplicity, so each value is
1971 1971
    /// traversed for each item it is assigned to.
1972 1972
    class ValueIt
1973 1973
      : public std::iterator<std::forward_iterator_tag, Value> {
1974 1974
      friend class CrossRefMap;
1975 1975
    private:
1976 1976
      ValueIt(typename Container::const_iterator _it)
1977 1977
        : it(_it) {}
1978 1978
    public:
1979 1979

	
1980 1980
      /// Constructor
1981 1981
      ValueIt() {}
1982 1982

	
1983 1983
      /// \e
1984 1984
      ValueIt& operator++() { ++it; return *this; }
1985 1985
      /// \e
1986 1986
      ValueIt operator++(int) {
1987 1987
        ValueIt tmp(*this);
1988 1988
        operator++();
1989 1989
        return tmp;
1990 1990
      }
1991 1991

	
1992 1992
      /// \e
1993 1993
      const Value& operator*() const { return it->first; }
1994 1994
      /// \e
1995 1995
      const Value* operator->() const { return &(it->first); }
1996 1996

	
1997 1997
      /// \e
1998 1998
      bool operator==(ValueIt jt) const { return it == jt.it; }
1999 1999
      /// \e
2000 2000
      bool operator!=(ValueIt jt) const { return it != jt.it; }
2001 2001

	
2002 2002
    private:
2003 2003
      typename Container::const_iterator it;
2004 2004
    };
2005 2005

	
2006 2006
    /// Alias for \c ValueIt
2007 2007
    typedef ValueIt ValueIterator;
2008 2008

	
2009 2009
    /// \brief Returns an iterator to the first value.
2010 2010
    ///
2011 2011
    /// Returns an STL compatible iterator to the
2012 2012
    /// first value of the map. The values of the
2013 2013
    /// map can be accessed in the <tt>[beginValue, endValue)</tt>
2014 2014
    /// range.
2015 2015
    ValueIt beginValue() const {
2016 2016
      return ValueIt(_inv_map.begin());
2017 2017
    }
2018 2018

	
2019 2019
    /// \brief Returns an iterator after the last value.
2020 2020
    ///
2021 2021
    /// Returns an STL compatible iterator after the
2022 2022
    /// last value of the map. The values of the
2023 2023
    /// map can be accessed in the <tt>[beginValue, endValue)</tt>
2024 2024
    /// range.
2025 2025
    ValueIt endValue() const {
2026 2026
      return ValueIt(_inv_map.end());
2027 2027
    }
2028 2028

	
2029 2029
    /// \brief Sets the value associated with the given key.
2030 2030
    ///
2031 2031
    /// Sets the value associated with the given key.
2032 2032
    void set(const Key& key, const Value& val) {
2033 2033
      Value oldval = Map::operator[](key);
2034 2034
      typename Container::iterator it;
2035 2035
      for (it = _inv_map.equal_range(oldval).first;
2036 2036
           it != _inv_map.equal_range(oldval).second; ++it) {
2037 2037
        if (it->second == key) {
2038 2038
          _inv_map.erase(it);
2039 2039
          break;
2040 2040
        }
2041 2041
      }
2042 2042
      _inv_map.insert(std::make_pair(val, key));
2043 2043
      Map::set(key, val);
2044 2044
    }
2045 2045

	
2046 2046
    /// \brief Returns the value associated with the given key.
2047 2047
    ///
2048 2048
    /// Returns the value associated with the given key.
2049 2049
    typename MapTraits<Map>::ConstReturnValue
2050 2050
    operator[](const Key& key) const {
2051 2051
      return Map::operator[](key);
2052 2052
    }
2053 2053

	
Show white space 4096 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
 * Copyright (C) 2003-2010
5
 * Copyright (C) 2003-2011
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_PREFLOW_H
20 20
#define LEMON_PREFLOW_H
21 21

	
22 22
#include <lemon/tolerance.h>
23 23
#include <lemon/elevator.h>
24 24

	
25 25
/// \file
26 26
/// \ingroup max_flow
27 27
/// \brief Implementation of the preflow algorithm.
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  /// \brief Default traits class of Preflow class.
32 32
  ///
33 33
  /// Default traits class of Preflow class.
34 34
  /// \tparam GR Digraph type.
35 35
  /// \tparam CAP Capacity map type.
36 36
  template <typename GR, typename CAP>
37 37
  struct PreflowDefaultTraits {
38 38

	
39 39
    /// \brief The type of the digraph the algorithm runs on.
40 40
    typedef GR Digraph;
41 41

	
42 42
    /// \brief The type of the map that stores the arc capacities.
43 43
    ///
44 44
    /// The type of the map that stores the arc capacities.
45 45
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
46 46
    typedef CAP CapacityMap;
47 47

	
48 48
    /// \brief The type of the flow values.
49 49
    typedef typename CapacityMap::Value Value;
50 50

	
51 51
    /// \brief The type of the map that stores the flow values.
52 52
    ///
53 53
    /// The type of the map that stores the flow values.
54 54
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
55 55
#ifdef DOXYGEN
56 56
    typedef GR::ArcMap<Value> FlowMap;
57 57
#else
58 58
    typedef typename Digraph::template ArcMap<Value> FlowMap;
59 59
#endif
60 60

	
61 61
    /// \brief Instantiates a FlowMap.
62 62
    ///
63 63
    /// This function instantiates a \ref FlowMap.
64 64
    /// \param digraph The digraph for which we would like to define
65 65
    /// the flow map.
66 66
    static FlowMap* createFlowMap(const Digraph& digraph) {
67 67
      return new FlowMap(digraph);
68 68
    }
69 69

	
70 70
    /// \brief The elevator type used by Preflow algorithm.
71 71
    ///
72 72
    /// The elevator type used by Preflow algorithm.
73 73
    ///
74 74
    /// \sa Elevator, LinkedElevator
75 75
#ifdef DOXYGEN
76 76
    typedef lemon::Elevator<GR, GR::Node> Elevator;
77 77
#else
78 78
    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
79 79
#endif
80 80

	
81 81
    /// \brief Instantiates an Elevator.
82 82
    ///
83 83
    /// This function instantiates an \ref Elevator.
84 84
    /// \param digraph The digraph for which we would like to define
85 85
    /// the elevator.
86 86
    /// \param max_level The maximum level of the elevator.
87 87
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
88 88
      return new Elevator(digraph, max_level);
89 89
    }
90 90

	
91 91
    /// \brief The tolerance used by the algorithm
92 92
    ///
93 93
    /// The tolerance used by the algorithm to handle inexact computation.
94 94
    typedef lemon::Tolerance<Value> Tolerance;
95 95

	
96 96
  };
97 97

	
98 98

	
99 99
  /// \ingroup max_flow
100 100
  ///
101 101
  /// \brief %Preflow algorithm class.
102 102
  ///
103 103
  /// This class provides an implementation of Goldberg-Tarjan's \e preflow
104 104
  /// \e push-relabel algorithm producing a \ref max_flow
105 105
  /// "flow of maximum value" in a digraph \ref clrs01algorithms,
106 106
  /// \ref amo93networkflows, \ref goldberg88newapproach.
107 107
  /// The preflow algorithms are the fastest known maximum
108 108
  /// flow algorithms. The current implementation uses a mixture of the
109 109
  /// \e "highest label" and the \e "bound decrease" heuristics.
110 110
  /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
111 111
  ///
112 112
  /// The algorithm consists of two phases. After the first phase
113 113
  /// the maximum flow value and the minimum cut is obtained. The
114 114
  /// second phase constructs a feasible maximum flow on each arc.
115 115
  ///
116 116
  /// \warning This implementation cannot handle infinite or very large
117 117
  /// capacities (e.g. the maximum value of \c CAP::Value).
118 118
  ///
119 119
  /// \tparam GR The type of the digraph the algorithm runs on.
120 120
  /// \tparam CAP The type of the capacity map. The default map
121 121
  /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
122 122
  /// \tparam TR The traits class that defines various types used by the
123 123
  /// algorithm. By default, it is \ref PreflowDefaultTraits
124 124
  /// "PreflowDefaultTraits<GR, CAP>".
125 125
  /// In most cases, this parameter should not be set directly,
126 126
  /// consider to use the named template parameters instead.
127 127
#ifdef DOXYGEN
128 128
  template <typename GR, typename CAP, typename TR>
129 129
#else
130 130
  template <typename GR,
131 131
            typename CAP = typename GR::template ArcMap<int>,
132 132
            typename TR = PreflowDefaultTraits<GR, CAP> >
133 133
#endif
134 134
  class Preflow {
135 135
  public:
136 136

	
137 137
    ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
138 138
    typedef TR Traits;
139 139
    ///The type of the digraph the algorithm runs on.
140 140
    typedef typename Traits::Digraph Digraph;
141 141
    ///The type of the capacity map.
142 142
    typedef typename Traits::CapacityMap CapacityMap;
143 143
    ///The type of the flow values.
144 144
    typedef typename Traits::Value Value;
145 145

	
146 146
    ///The type of the flow map.
147 147
    typedef typename Traits::FlowMap FlowMap;
148 148
    ///The type of the elevator.
149 149
    typedef typename Traits::Elevator Elevator;
150 150
    ///The type of the tolerance.
151 151
    typedef typename Traits::Tolerance Tolerance;
152 152

	
153 153
  private:
154 154

	
155 155
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
156 156

	
157 157
    const Digraph& _graph;
158 158
    const CapacityMap* _capacity;
159 159

	
160 160
    int _node_num;
161 161

	
162 162
    Node _source, _target;
163 163

	
164 164
    FlowMap* _flow;
165 165
    bool _local_flow;
166 166

	
167 167
    Elevator* _level;
168 168
    bool _local_level;
169 169

	
170 170
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
171 171
    ExcessMap* _excess;
172 172

	
173 173
    Tolerance _tolerance;
174 174

	
175 175
    bool _phase;
176 176

	
177 177

	
178 178
    void createStructures() {
179 179
      _node_num = countNodes(_graph);
180 180

	
181 181
      if (!_flow) {
182 182
        _flow = Traits::createFlowMap(_graph);
183 183
        _local_flow = true;
184 184
      }
185 185
      if (!_level) {
186 186
        _level = Traits::createElevator(_graph, _node_num);
187 187
        _local_level = true;
188 188
      }
189 189
      if (!_excess) {
190 190
        _excess = new ExcessMap(_graph);
191 191
      }
192 192
    }
193 193

	
194 194
    void destroyStructures() {
195 195
      if (_local_flow) {
196 196
        delete _flow;
197 197
      }
198 198
      if (_local_level) {
199 199
        delete _level;
200 200
      }
201 201
      if (_excess) {
202 202
        delete _excess;
203 203
      }
204 204
    }
205 205

	
206 206
  public:
207 207

	
208 208
    typedef Preflow Create;
209 209

	
210 210
    ///\name Named Template Parameters
211 211

	
212 212
    ///@{
213 213

	
214 214
    template <typename T>
215 215
    struct SetFlowMapTraits : public Traits {
216 216
      typedef T FlowMap;
217 217
      static FlowMap *createFlowMap(const Digraph&) {
218 218
        LEMON_ASSERT(false, "FlowMap is not initialized");
219 219
        return 0; // ignore warnings
220 220
      }
221 221
    };
222 222

	
223 223
    /// \brief \ref named-templ-param "Named parameter" for setting
224 224
    /// FlowMap type
225 225
    ///
226 226
    /// \ref named-templ-param "Named parameter" for setting FlowMap
227 227
    /// type.
228 228
    template <typename T>
229 229
    struct SetFlowMap
230 230
      : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<T> > {
231 231
      typedef Preflow<Digraph, CapacityMap,
232 232
                      SetFlowMapTraits<T> > Create;
233 233
    };
234 234

	
235 235
    template <typename T>
236 236
    struct SetElevatorTraits : public Traits {
237 237
      typedef T Elevator;
238 238
      static Elevator *createElevator(const Digraph&, int) {
239 239
        LEMON_ASSERT(false, "Elevator is not initialized");
240 240
        return 0; // ignore warnings
241 241
      }
242 242
    };
243 243

	
244 244
    /// \brief \ref named-templ-param "Named parameter" for setting
245 245
    /// Elevator type
246 246
    ///
247 247
    /// \ref named-templ-param "Named parameter" for setting Elevator
248 248
    /// type. If this named parameter is used, then an external
249 249
    /// elevator object must be passed to the algorithm using the
250 250
    /// \ref elevator(Elevator&) "elevator()" function before calling
251 251
    /// \ref run() or \ref init().
252 252
    /// \sa SetStandardElevator
253 253
    template <typename T>
254 254
    struct SetElevator
255 255
      : public Preflow<Digraph, CapacityMap, SetElevatorTraits<T> > {
256 256
      typedef Preflow<Digraph, CapacityMap,
257 257
                      SetElevatorTraits<T> > Create;
258 258
    };
259 259

	
260 260
    template <typename T>
261 261
    struct SetStandardElevatorTraits : public Traits {
262 262
      typedef T Elevator;
263 263
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
264 264
        return new Elevator(digraph, max_level);
265 265
      }
266 266
    };
267 267

	
268 268
    /// \brief \ref named-templ-param "Named parameter" for setting
269 269
    /// Elevator type with automatic allocation
270 270
    ///
271 271
    /// \ref named-templ-param "Named parameter" for setting Elevator
272 272
    /// type with automatic allocation.
273 273
    /// The Elevator should have standard constructor interface to be
274 274
    /// able to automatically created by the algorithm (i.e. the
275 275
    /// digraph and the maximum level should be passed to it).
276 276
    /// However, an external elevator object could also be passed to the
277 277
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
278 278
    /// before calling \ref run() or \ref init().
279 279
    /// \sa SetElevator
280 280
    template <typename T>
281 281
    struct SetStandardElevator
282 282
      : public Preflow<Digraph, CapacityMap,
283 283
                       SetStandardElevatorTraits<T> > {
284 284
      typedef Preflow<Digraph, CapacityMap,
285 285
                      SetStandardElevatorTraits<T> > Create;
286 286
    };
287 287

	
288 288
    /// @}
289 289

	
290 290
  protected:
291 291

	
292 292
    Preflow() {}
293 293

	
294 294
  public:
295 295

	
296 296

	
297 297
    /// \brief The constructor of the class.
298 298
    ///
299 299
    /// The constructor of the class.
300 300
    /// \param digraph The digraph the algorithm runs on.
301 301
    /// \param capacity The capacity of the arcs.
302 302
    /// \param source The source node.
303 303
    /// \param target The target node.
304 304
    Preflow(const Digraph& digraph, const CapacityMap& capacity,
305 305
            Node source, Node target)
306 306
      : _graph(digraph), _capacity(&capacity),
307 307
        _node_num(0), _source(source), _target(target),
308 308
        _flow(0), _local_flow(false),
309 309
        _level(0), _local_level(false),
310 310
        _excess(0), _tolerance(), _phase() {}
311 311

	
312 312
    /// \brief Destructor.
313 313
    ///
314 314
    /// Destructor.
315 315
    ~Preflow() {
316 316
      destroyStructures();
317 317
    }
318 318

	
319 319
    /// \brief Sets the capacity map.
320 320
    ///
321 321
    /// Sets the capacity map.
322 322
    /// \return <tt>(*this)</tt>
323 323
    Preflow& capacityMap(const CapacityMap& map) {
324 324
      _capacity = &map;
325 325
      return *this;
326 326
    }
327 327

	
328 328
    /// \brief Sets the flow map.
329 329
    ///
330 330
    /// Sets the flow map.
331 331
    /// If you don't use this function before calling \ref run() or
332 332
    /// \ref init(), an instance will be allocated automatically.
333 333
    /// The destructor deallocates this automatically allocated map,
334 334
    /// of course.
335 335
    /// \return <tt>(*this)</tt>
336 336
    Preflow& flowMap(FlowMap& map) {
337 337
      if (_local_flow) {
338 338
        delete _flow;
339 339
        _local_flow = false;
340 340
      }
341 341
      _flow = &map;
342 342
      return *this;
343 343
    }
344 344

	
345 345
    /// \brief Sets the source node.
346 346
    ///
347 347
    /// Sets the source node.
348 348
    /// \return <tt>(*this)</tt>
349 349
    Preflow& source(const Node& node) {
350 350
      _source = node;
351 351
      return *this;
352 352
    }
353 353

	
354 354
    /// \brief Sets the target node.
355 355
    ///
356 356
    /// Sets the target node.
357 357
    /// \return <tt>(*this)</tt>
358 358
    Preflow& target(const Node& node) {
359 359
      _target = node;
360 360
      return *this;
361 361
    }
362 362

	
363 363
    /// \brief Sets the elevator used by algorithm.
364 364
    ///
365 365
    /// Sets the elevator used by algorithm.
366 366
    /// If you don't use this function before calling \ref run() or
367 367
    /// \ref init(), an instance will be allocated automatically.
368 368
    /// The destructor deallocates this automatically allocated elevator,
369 369
    /// of course.
370 370
    /// \return <tt>(*this)</tt>
371 371
    Preflow& elevator(Elevator& elevator) {
372 372
      if (_local_level) {
373 373
        delete _level;
374 374
        _local_level = false;
375 375
      }
376 376
      _level = &elevator;
377 377
      return *this;
378 378
    }
379 379

	
380 380
    /// \brief Returns a const reference to the elevator.
381 381
    ///
382 382
    /// Returns a const reference to the elevator.
383 383
    ///
384 384
    /// \pre Either \ref run() or \ref init() must be called before
385 385
    /// using this function.
386 386
    const Elevator& elevator() const {
387 387
      return *_level;
388 388
    }
389 389

	
390 390
    /// \brief Sets the tolerance used by the algorithm.
391 391
    ///
392 392
    /// Sets the tolerance object used by the algorithm.
393 393
    /// \return <tt>(*this)</tt>
394 394
    Preflow& tolerance(const Tolerance& tolerance) {
395 395
      _tolerance = tolerance;
396 396
      return *this;
397 397
    }
398 398

	
399 399
    /// \brief Returns a const reference to the tolerance.
400 400
    ///
401 401
    /// Returns a const reference to the tolerance object used by
402 402
    /// the algorithm.
403 403
    const Tolerance& tolerance() const {
404 404
      return _tolerance;
405 405
    }
406 406

	
407 407
    /// \name Execution Control
408 408
    /// The simplest way to execute the preflow algorithm is to use
409 409
    /// \ref run() or \ref runMinCut().\n
410 410
    /// If you need better control on the initial solution or the execution,
411 411
    /// you have to call one of the \ref init() functions first, then
412 412
    /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
413 413

	
414 414
    ///@{
415 415

	
416 416
    /// \brief Initializes the internal data structures.
417 417
    ///
418 418
    /// Initializes the internal data structures and sets the initial
419 419
    /// flow to zero on each arc.
420 420
    void init() {
421 421
      createStructures();
422 422

	
423 423
      _phase = true;
424 424
      for (NodeIt n(_graph); n != INVALID; ++n) {
425 425
        (*_excess)[n] = 0;
426 426
      }
427 427

	
428 428
      for (ArcIt e(_graph); e != INVALID; ++e) {
429 429
        _flow->set(e, 0);
430 430
      }
431 431

	
432 432
      typename Digraph::template NodeMap<bool> reached(_graph, false);
433 433

	
434 434
      _level->initStart();
435 435
      _level->initAddItem(_target);
436 436

	
437 437
      std::vector<Node> queue;
438 438
      reached[_source] = true;
439 439

	
440 440
      queue.push_back(_target);
441 441
      reached[_target] = true;
442 442
      while (!queue.empty()) {
443 443
        _level->initNewLevel();
444 444
        std::vector<Node> nqueue;
445 445
        for (int i = 0; i < int(queue.size()); ++i) {
446 446
          Node n = queue[i];
447 447
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
448 448
            Node u = _graph.source(e);
449 449
            if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
450 450
              reached[u] = true;
451 451
              _level->initAddItem(u);
452 452
              nqueue.push_back(u);
453 453
            }
454 454
          }
455 455
        }
456 456
        queue.swap(nqueue);
457 457
      }
458 458
      _level->initFinish();
459 459

	
460 460
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
461 461
        if (_tolerance.positive((*_capacity)[e])) {
462 462
          Node u = _graph.target(e);
463 463
          if ((*_level)[u] == _level->maxLevel()) continue;
464 464
          _flow->set(e, (*_capacity)[e]);
465 465
          (*_excess)[u] += (*_capacity)[e];
466 466
          if (u != _target && !_level->active(u)) {
467 467
            _level->activate(u);
468 468
          }
469 469
        }
470 470
      }
471 471
    }
472 472

	
473 473
    /// \brief Initializes the internal data structures using the
474 474
    /// given flow map.
475 475
    ///
476 476
    /// Initializes the internal data structures and sets the initial
477 477
    /// flow to the given \c flowMap. The \c flowMap should contain a
478 478
    /// flow or at least a preflow, i.e. at each node excluding the
479 479
    /// source node the incoming flow should greater or equal to the
480 480
    /// outgoing flow.
481 481
    /// \return \c false if the given \c flowMap is not a preflow.
482 482
    template <typename FlowMap>
483 483
    bool init(const FlowMap& flowMap) {
484 484
      createStructures();
485 485

	
486 486
      for (ArcIt e(_graph); e != INVALID; ++e) {
487 487
        _flow->set(e, flowMap[e]);
488 488
      }
489 489

	
490 490
      for (NodeIt n(_graph); n != INVALID; ++n) {
491 491
        Value excess = 0;
492 492
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
493 493
          excess += (*_flow)[e];
494 494
        }
495 495
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
496 496
          excess -= (*_flow)[e];
497 497
        }
498 498
        if (excess < 0 && n != _source) return false;
499 499
        (*_excess)[n] = excess;
500 500
      }
501 501

	
502 502
      typename Digraph::template NodeMap<bool> reached(_graph, false);
503 503

	
504 504
      _level->initStart();
505 505
      _level->initAddItem(_target);
506 506

	
507 507
      std::vector<Node> queue;
508 508
      reached[_source] = true;
509 509

	
510 510
      queue.push_back(_target);
511 511
      reached[_target] = true;
512 512
      while (!queue.empty()) {
513 513
        _level->initNewLevel();
514 514
        std::vector<Node> nqueue;
515 515
        for (int i = 0; i < int(queue.size()); ++i) {
516 516
          Node n = queue[i];
517 517
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
518 518
            Node u = _graph.source(e);
519 519
            if (!reached[u] &&
520 520
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
521 521
              reached[u] = true;
522 522
              _level->initAddItem(u);
523 523
              nqueue.push_back(u);
524 524
            }
525 525
          }
526 526
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
527 527
            Node v = _graph.target(e);
528 528
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
529 529
              reached[v] = true;
530 530
              _level->initAddItem(v);
531 531
              nqueue.push_back(v);
532 532
            }
533 533
          }
534 534
        }
535 535
        queue.swap(nqueue);
536 536
      }
537 537
      _level->initFinish();
538 538

	
539 539
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
540 540
        Value rem = (*_capacity)[e] - (*_flow)[e];
541 541
        if (_tolerance.positive(rem)) {
542 542
          Node u = _graph.target(e);
543 543
          if ((*_level)[u] == _level->maxLevel()) continue;
544 544
          _flow->set(e, (*_capacity)[e]);
545 545
          (*_excess)[u] += rem;
546 546
        }
547 547
      }
548 548
      for (InArcIt e(_graph, _source); e != INVALID; ++e) {
549 549
        Value rem = (*_flow)[e];
550 550
        if (_tolerance.positive(rem)) {
551 551
          Node v = _graph.source(e);
552 552
          if ((*_level)[v] == _level->maxLevel()) continue;
553 553
          _flow->set(e, 0);
554 554
          (*_excess)[v] += rem;
555 555
        }
556 556
      }
557 557
      for (NodeIt n(_graph); n != INVALID; ++n) 
558 558
        if(n!=_source && n!=_target && _tolerance.positive((*_excess)[n]))
559 559
          _level->activate(n);
560 560
          
561 561
      return true;
562 562
    }
563 563

	
564 564
    /// \brief Starts the first phase of the preflow algorithm.
565 565
    ///
566 566
    /// The preflow algorithm consists of two phases, this method runs
567 567
    /// the first phase. After the first phase the maximum flow value
568 568
    /// and a minimum value cut can already be computed, although a
569 569
    /// maximum flow is not yet obtained. So after calling this method
570 570
    /// \ref flowValue() returns the value of a maximum flow and \ref
571 571
    /// minCut() returns a minimum cut.
572 572
    /// \pre One of the \ref init() functions must be called before
573 573
    /// using this function.
574 574
    void startFirstPhase() {
575 575
      _phase = true;
576 576

	
577 577
      while (true) {
578 578
        int num = _node_num;
579 579

	
580 580
        Node n = INVALID;
581 581
        int level = -1;
582 582

	
583 583
        while (num > 0) {
584 584
          n = _level->highestActive();
585 585
          if (n == INVALID) goto first_phase_done;
586 586
          level = _level->highestActiveLevel();
587 587
          --num;
588 588
          
589 589
          Value excess = (*_excess)[n];
590 590
          int new_level = _level->maxLevel();
591 591

	
592 592
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
593 593
            Value rem = (*_capacity)[e] - (*_flow)[e];
594 594
            if (!_tolerance.positive(rem)) continue;
595 595
            Node v = _graph.target(e);
596 596
            if ((*_level)[v] < level) {
597 597
              if (!_level->active(v) && v != _target) {
598 598
                _level->activate(v);
599 599
              }
600 600
              if (!_tolerance.less(rem, excess)) {
601 601
                _flow->set(e, (*_flow)[e] + excess);
602 602
                (*_excess)[v] += excess;
603 603
                excess = 0;
604 604
                goto no_more_push_1;
605 605
              } else {
606 606
                excess -= rem;
607 607
                (*_excess)[v] += rem;
608 608
                _flow->set(e, (*_capacity)[e]);
609 609
              }
610 610
            } else if (new_level > (*_level)[v]) {
611 611
              new_level = (*_level)[v];
612 612
            }
613 613
          }
614 614

	
615 615
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
616 616
            Value rem = (*_flow)[e];
617 617
            if (!_tolerance.positive(rem)) continue;
618 618
            Node v = _graph.source(e);
619 619
            if ((*_level)[v] < level) {
620 620
              if (!_level->active(v) && v != _target) {
621 621
                _level->activate(v);
622 622
              }
623 623
              if (!_tolerance.less(rem, excess)) {
624 624
                _flow->set(e, (*_flow)[e] - excess);
625 625
                (*_excess)[v] += excess;
626 626
                excess = 0;
627 627
                goto no_more_push_1;
628 628
              } else {
629 629
                excess -= rem;
630 630
                (*_excess)[v] += rem;
631 631
                _flow->set(e, 0);
632 632
              }
633 633
            } else if (new_level > (*_level)[v]) {
634 634
              new_level = (*_level)[v];
635 635
            }
636 636
          }
637 637

	
638 638
        no_more_push_1:
639 639

	
640 640
          (*_excess)[n] = excess;
641 641

	
642 642
          if (excess != 0) {
643 643
            if (new_level + 1 < _level->maxLevel()) {
644 644
              _level->liftHighestActive(new_level + 1);
645 645
            } else {
646 646
              _level->liftHighestActiveToTop();
647 647
            }
648 648
            if (_level->emptyLevel(level)) {
649 649
              _level->liftToTop(level);
650 650
            }
651 651
          } else {
652 652
            _level->deactivate(n);
653 653
          }
654 654
        }
655 655

	
656 656
        num = _node_num * 20;
657 657
        while (num > 0) {
658 658
          while (level >= 0 && _level->activeFree(level)) {
659 659
            --level;
660 660
          }
661 661
          if (level == -1) {
662 662
            n = _level->highestActive();
663 663
            level = _level->highestActiveLevel();
664 664
            if (n == INVALID) goto first_phase_done;
665 665
          } else {
666 666
            n = _level->activeOn(level);
667 667
          }
668 668
          --num;
669 669

	
670 670
          Value excess = (*_excess)[n];
671 671
          int new_level = _level->maxLevel();
672 672

	
673 673
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
674 674
            Value rem = (*_capacity)[e] - (*_flow)[e];
675 675
            if (!_tolerance.positive(rem)) continue;
676 676
            Node v = _graph.target(e);
677 677
            if ((*_level)[v] < level) {
678 678
              if (!_level->active(v) && v != _target) {
679 679
                _level->activate(v);
680 680
              }
681 681
              if (!_tolerance.less(rem, excess)) {
682 682
                _flow->set(e, (*_flow)[e] + excess);
683 683
                (*_excess)[v] += excess;
684 684
                excess = 0;
685 685
                goto no_more_push_2;
686 686
              } else {
687 687
                excess -= rem;
688 688
                (*_excess)[v] += rem;
689 689
                _flow->set(e, (*_capacity)[e]);
690 690
              }
691 691
            } else if (new_level > (*_level)[v]) {
692 692
              new_level = (*_level)[v];
693 693
            }
694 694
          }
695 695

	
696 696
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
697 697
            Value rem = (*_flow)[e];
698 698
            if (!_tolerance.positive(rem)) continue;
699 699
            Node v = _graph.source(e);
700 700
            if ((*_level)[v] < level) {
701 701
              if (!_level->active(v) && v != _target) {
702 702
                _level->activate(v);
703 703
              }
704 704
              if (!_tolerance.less(rem, excess)) {
705 705
                _flow->set(e, (*_flow)[e] - excess);
706 706
                (*_excess)[v] += excess;
707 707
                excess = 0;
708 708
                goto no_more_push_2;
709 709
              } else {
710 710
                excess -= rem;
711 711
                (*_excess)[v] += rem;
712 712
                _flow->set(e, 0);
713 713
              }
714 714
            } else if (new_level > (*_level)[v]) {
715 715
              new_level = (*_level)[v];
716 716
            }
717 717
          }
718 718

	
719 719
        no_more_push_2:
720 720

	
721 721
          (*_excess)[n] = excess;
722 722

	
723 723
          if (excess != 0) {
724 724
            if (new_level + 1 < _level->maxLevel()) {
725 725
              _level->liftActiveOn(level, new_level + 1);
726 726
            } else {
727 727
              _level->liftActiveToTop(level);
728 728
            }
729 729
            if (_level->emptyLevel(level)) {
730 730
              _level->liftToTop(level);
731 731
            }
732 732
          } else {
733 733
            _level->deactivate(n);
734 734
          }
735 735
        }
736 736
      }
737 737
    first_phase_done:;
738 738
    }
739 739

	
740 740
    /// \brief Starts the second phase of the preflow algorithm.
741 741
    ///
742 742
    /// The preflow algorithm consists of two phases, this method runs
743 743
    /// the second phase. After calling one of the \ref init() functions
744 744
    /// and \ref startFirstPhase() and then \ref startSecondPhase(),
745 745
    /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
746 746
    /// value of a maximum flow, \ref minCut() returns a minimum cut
747 747
    /// \pre One of the \ref init() functions and \ref startFirstPhase()
748 748
    /// must be called before using this function.
749 749
    void startSecondPhase() {
750 750
      _phase = false;
751 751

	
752 752
      typename Digraph::template NodeMap<bool> reached(_graph);
753 753
      for (NodeIt n(_graph); n != INVALID; ++n) {
754 754
        reached[n] = (*_level)[n] < _level->maxLevel();
755 755
      }
756 756

	
757 757
      _level->initStart();
758 758
      _level->initAddItem(_source);
759 759

	
760 760
      std::vector<Node> queue;
761 761
      queue.push_back(_source);
762 762
      reached[_source] = true;
763 763

	
764 764
      while (!queue.empty()) {
765 765
        _level->initNewLevel();
766 766
        std::vector<Node> nqueue;
767 767
        for (int i = 0; i < int(queue.size()); ++i) {
768 768
          Node n = queue[i];
769 769
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
770 770
            Node v = _graph.target(e);
771 771
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
772 772
              reached[v] = true;
773 773
              _level->initAddItem(v);
774 774
              nqueue.push_back(v);
775 775
            }
776 776
          }
777 777
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
778 778
            Node u = _graph.source(e);
779 779
            if (!reached[u] &&
780 780
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
781 781
              reached[u] = true;
782 782
              _level->initAddItem(u);
783 783
              nqueue.push_back(u);
784 784
            }
785 785
          }
786 786
        }
787 787
        queue.swap(nqueue);
788 788
      }
789 789
      _level->initFinish();
790 790

	
791 791
      for (NodeIt n(_graph); n != INVALID; ++n) {
792 792
        if (!reached[n]) {
793 793
          _level->dirtyTopButOne(n);
794 794
        } else if ((*_excess)[n] > 0 && _target != n) {
795 795
          _level->activate(n);
796 796
        }
797 797
      }
798 798

	
799 799
      Node n;
800 800
      while ((n = _level->highestActive()) != INVALID) {
801 801
        Value excess = (*_excess)[n];
802 802
        int level = _level->highestActiveLevel();
803 803
        int new_level = _level->maxLevel();
804 804

	
805 805
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
806 806
          Value rem = (*_capacity)[e] - (*_flow)[e];
807 807
          if (!_tolerance.positive(rem)) continue;
808 808
          Node v = _graph.target(e);
809 809
          if ((*_level)[v] < level) {
810 810
            if (!_level->active(v) && v != _source) {
811 811
              _level->activate(v);
812 812
            }
813 813
            if (!_tolerance.less(rem, excess)) {
814 814
              _flow->set(e, (*_flow)[e] + excess);
815 815
              (*_excess)[v] += excess;
816 816
              excess = 0;
817 817
              goto no_more_push;
818 818
            } else {
819 819
              excess -= rem;
820 820
              (*_excess)[v] += rem;
821 821
              _flow->set(e, (*_capacity)[e]);
822 822
            }
823 823
          } else if (new_level > (*_level)[v]) {
824 824
            new_level = (*_level)[v];
825 825
          }
826 826
        }
827 827

	
828 828
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
829 829
          Value rem = (*_flow)[e];
830 830
          if (!_tolerance.positive(rem)) continue;
831 831
          Node v = _graph.source(e);
832 832
          if ((*_level)[v] < level) {
833 833
            if (!_level->active(v) && v != _source) {
834 834
              _level->activate(v);
835 835
            }
836 836
            if (!_tolerance.less(rem, excess)) {
837 837
              _flow->set(e, (*_flow)[e] - excess);
838 838
              (*_excess)[v] += excess;
839 839
              excess = 0;
840 840
              goto no_more_push;
841 841
            } else {
842 842
              excess -= rem;
843 843
              (*_excess)[v] += rem;
844 844
              _flow->set(e, 0);
845 845
            }
846 846
          } else if (new_level > (*_level)[v]) {
847 847
            new_level = (*_level)[v];
848 848
          }
849 849
        }
850 850

	
851 851
      no_more_push:
852 852

	
853 853
        (*_excess)[n] = excess;
854 854

	
855 855
        if (excess != 0) {
856 856
          if (new_level + 1 < _level->maxLevel()) {
857 857
            _level->liftHighestActive(new_level + 1);
858 858
          } else {
859 859
            // Calculation error
860 860
            _level->liftHighestActiveToTop();
861 861
          }
862 862
          if (_level->emptyLevel(level)) {
863 863
            // Calculation error
864 864
            _level->liftToTop(level);
865 865
          }
866 866
        } else {
867 867
          _level->deactivate(n);
868 868
        }
869 869

	
870 870
      }
871 871
    }
872 872

	
873 873
    /// \brief Runs the preflow algorithm.
874 874
    ///
875 875
    /// Runs the preflow algorithm.
876 876
    /// \note pf.run() is just a shortcut of the following code.
877 877
    /// \code
878 878
    ///   pf.init();
879 879
    ///   pf.startFirstPhase();
880 880
    ///   pf.startSecondPhase();
881 881
    /// \endcode
882 882
    void run() {
883 883
      init();
884 884
      startFirstPhase();
885 885
      startSecondPhase();
886 886
    }
887 887

	
888 888
    /// \brief Runs the preflow algorithm to compute the minimum cut.
889 889
    ///
890 890
    /// Runs the preflow algorithm to compute the minimum cut.
891 891
    /// \note pf.runMinCut() is just a shortcut of the following code.
892 892
    /// \code
893 893
    ///   pf.init();
894 894
    ///   pf.startFirstPhase();
895 895
    /// \endcode
896 896
    void runMinCut() {
897 897
      init();
898 898
      startFirstPhase();
899 899
    }
900 900

	
901 901
    /// @}
902 902

	
903 903
    /// \name Query Functions
904 904
    /// The results of the preflow algorithm can be obtained using these
905 905
    /// functions.\n
906 906
    /// Either one of the \ref run() "run*()" functions or one of the
907 907
    /// \ref startFirstPhase() "start*()" functions should be called
908 908
    /// before using them.
909 909

	
910 910
    ///@{
911 911

	
912 912
    /// \brief Returns the value of the maximum flow.
913 913
    ///
914 914
    /// Returns the value of the maximum flow by returning the excess
915 915
    /// of the target node. This value equals to the value of
916 916
    /// the maximum flow already after the first phase of the algorithm.
917 917
    ///
918 918
    /// \pre Either \ref run() or \ref init() must be called before
919 919
    /// using this function.
920 920
    Value flowValue() const {
921 921
      return (*_excess)[_target];
922 922
    }
923 923

	
924 924
    /// \brief Returns the flow value on the given arc.
925 925
    ///
926 926
    /// Returns the flow value on the given arc. This method can
927 927
    /// be called after the second phase of the algorithm.
928 928
    ///
929 929
    /// \pre Either \ref run() or \ref init() must be called before
930 930
    /// using this function.
931 931
    Value flow(const Arc& arc) const {
932 932
      return (*_flow)[arc];
933 933
    }
934 934

	
935 935
    /// \brief Returns a const reference to the flow map.
936 936
    ///
937 937
    /// Returns a const reference to the arc map storing the found flow.
938 938
    /// This method can be called after the second phase of the algorithm.
939 939
    ///
940 940
    /// \pre Either \ref run() or \ref init() must be called before
941 941
    /// using this function.
942 942
    const FlowMap& flowMap() const {
943 943
      return *_flow;
944 944
    }
945 945

	
946 946
    /// \brief Returns \c true when the node is on the source side of the
947 947
    /// minimum cut.
948 948
    ///
949 949
    /// Returns true when the node is on the source side of the found
950 950
    /// minimum cut. This method can be called both after running \ref
951 951
    /// startFirstPhase() and \ref startSecondPhase().
952 952
    ///
953 953
    /// \pre Either \ref run() or \ref init() must be called before
954 954
    /// using this function.
955 955
    bool minCut(const Node& node) const {
956 956
      return ((*_level)[node] == _level->maxLevel()) == _phase;
957 957
    }
958 958

	
959 959
    /// \brief Gives back a minimum value cut.
960 960
    ///
961 961
    /// Sets \c cutMap to the characteristic vector of a minimum value
962 962
    /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
963 963
    /// node map with \c bool (or convertible) value type.
964 964
    ///
965 965
    /// This method can be called both after running \ref startFirstPhase()
966 966
    /// and \ref startSecondPhase(). The result after the second phase
967 967
    /// could be slightly different if inexact computation is used.
968 968
    ///
969 969
    /// \note This function calls \ref minCut() for each node, so it runs in
970 970
    /// O(n) time.
971 971
    ///
972 972
    /// \pre Either \ref run() or \ref init() must be called before
973 973
    /// using this function.
974 974
    template <typename CutMap>
975 975
    void minCutMap(CutMap& cutMap) const {
976 976
      for (NodeIt n(_graph); n != INVALID; ++n) {
977 977
        cutMap.set(n, minCut(n));
978 978
      }
979 979
    }
980 980

	
981 981
    /// @}
982 982
  };
983 983
}
984 984

	
985 985
#endif
Show white space 4096 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
 * Copyright (C) 2003-2010
5
 * Copyright (C) 2003-2011
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/dfs.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
  "5\n"
40 40
  "6\n"
41 41
  "@arcs\n"
42 42
  "     label\n"
43 43
  "0 1  0\n"
44 44
  "1 2  1\n"
45 45
  "2 3  2\n"
46 46
  "1 4  3\n"
47 47
  "4 2  4\n"
48 48
  "4 5  5\n"
49 49
  "5 0  6\n"
50 50
  "6 3  7\n"
51 51
  "@attributes\n"
52 52
  "source 0\n"
53 53
  "target 5\n"
54 54
  "source1 6\n"
55 55
  "target1 3\n";
56 56

	
57 57

	
58 58
void checkDfsCompile()
59 59
{
60 60
  typedef concepts::Digraph Digraph;
61 61
  typedef Dfs<Digraph> DType;
62 62
  typedef Digraph::Node Node;
63 63
  typedef Digraph::Arc Arc;
64 64

	
65 65
  Digraph G;
66 66
  Node s, t;
67 67
  Arc e;
68 68
  int l, i;
69 69
  bool b;
70 70
  DType::DistMap d(G);
71 71
  DType::PredMap p(G);
72 72
  Path<Digraph> pp;
73 73
  concepts::ReadMap<Arc,bool> am;
74 74

	
75 75
  {
76 76
    DType dfs_test(G);
77 77
    const DType& const_dfs_test = dfs_test;
78 78

	
79 79
    dfs_test.run(s);
80 80
    dfs_test.run(s,t);
81 81
    dfs_test.run();
82 82

	
83 83
    dfs_test.init();
84 84
    dfs_test.addSource(s);
85 85
    e = dfs_test.processNextArc();
86 86
    e = const_dfs_test.nextArc();
87 87
    b = const_dfs_test.emptyQueue();
88 88
    i = const_dfs_test.queueSize();
89 89

	
90 90
    dfs_test.start();
91 91
    dfs_test.start(t);
92 92
    dfs_test.start(am);
93 93

	
94 94
    l  = const_dfs_test.dist(t);
95 95
    e  = const_dfs_test.predArc(t);
96 96
    s  = const_dfs_test.predNode(t);
97 97
    b  = const_dfs_test.reached(t);
98 98
    d  = const_dfs_test.distMap();
99 99
    p  = const_dfs_test.predMap();
100 100
    pp = const_dfs_test.path(t);
101 101
  }
102 102
  {
103 103
    DType
104 104
      ::SetPredMap<concepts::ReadWriteMap<Node,Arc> >
105 105
      ::SetDistMap<concepts::ReadWriteMap<Node,int> >
106 106
      ::SetReachedMap<concepts::ReadWriteMap<Node,bool> >
107 107
      ::SetStandardProcessedMap
108 108
      ::SetProcessedMap<concepts::WriteMap<Node,bool> >
109 109
      ::Create dfs_test(G);
110 110

	
111 111
    concepts::ReadWriteMap<Node,Arc> pred_map;
112 112
    concepts::ReadWriteMap<Node,int> dist_map;
113 113
    concepts::ReadWriteMap<Node,bool> reached_map;
114 114
    concepts::WriteMap<Node,bool> processed_map;
115 115

	
116 116
    dfs_test
117 117
      .predMap(pred_map)
118 118
      .distMap(dist_map)
119 119
      .reachedMap(reached_map)
120 120
      .processedMap(processed_map);
121 121

	
122 122
    dfs_test.run(s);
123 123
    dfs_test.run(s,t);
124 124
    dfs_test.run();
125 125
    dfs_test.init();
126 126

	
127 127
    dfs_test.addSource(s);
128 128
    e = dfs_test.processNextArc();
129 129
    e = dfs_test.nextArc();
130 130
    b = dfs_test.emptyQueue();
131 131
    i = dfs_test.queueSize();
132 132

	
133 133
    dfs_test.start();
134 134
    dfs_test.start(t);
135 135
    dfs_test.start(am);
136 136

	
137 137
    l  = dfs_test.dist(t);
138 138
    e  = dfs_test.predArc(t);
139 139
    s  = dfs_test.predNode(t);
140 140
    b  = dfs_test.reached(t);
141 141
    pp = dfs_test.path(t);
142 142
  }
143 143
}
144 144

	
145 145
void checkDfsFunctionCompile()
146 146
{
147 147
  typedef int VType;
148 148
  typedef concepts::Digraph Digraph;
149 149
  typedef Digraph::Arc Arc;
150 150
  typedef Digraph::Node Node;
151 151

	
152 152
  Digraph g;
153 153
  bool b;
154 154
  dfs(g).run(Node());
155 155
  b=dfs(g).run(Node(),Node());
156 156
  dfs(g).run();
157 157
  dfs(g)
158 158
    .predMap(concepts::ReadWriteMap<Node,Arc>())
159 159
    .distMap(concepts::ReadWriteMap<Node,VType>())
160 160
    .reachedMap(concepts::ReadWriteMap<Node,bool>())
161 161
    .processedMap(concepts::WriteMap<Node,bool>())
162 162
    .run(Node());
163 163
  b=dfs(g)
164 164
    .predMap(concepts::ReadWriteMap<Node,Arc>())
165 165
    .distMap(concepts::ReadWriteMap<Node,VType>())
166 166
    .reachedMap(concepts::ReadWriteMap<Node,bool>())
167 167
    .processedMap(concepts::WriteMap<Node,bool>())
168 168
    .path(concepts::Path<Digraph>())
169 169
    .dist(VType())
170 170
    .run(Node(),Node());
171 171
  dfs(g)
172 172
    .predMap(concepts::ReadWriteMap<Node,Arc>())
173 173
    .distMap(concepts::ReadWriteMap<Node,VType>())
174 174
    .reachedMap(concepts::ReadWriteMap<Node,bool>())
175 175
    .processedMap(concepts::WriteMap<Node,bool>())
176 176
    .run();
177 177
}
178 178

	
179 179
template <class Digraph>
180 180
void checkDfs() {
181 181
  TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
182 182

	
183 183
  Digraph G;
184 184
  Node s, t;
185 185
  Node s1, t1;
186 186

	
187 187
  std::istringstream input(test_lgf);
188 188
  digraphReader(G, input).
189 189
    node("source", s).
190 190
    node("target", t).
191 191
    node("source1", s1).
192 192
    node("target1", t1).
193 193
    run();
194 194

	
195 195
  Dfs<Digraph> dfs_test(G);
196 196
  dfs_test.run(s);
197 197

	
198 198
  Path<Digraph> p = dfs_test.path(t);
199 199
  check(p.length() == dfs_test.dist(t),"path() found a wrong path.");
200 200
  check(checkPath(G, p),"path() found a wrong path.");
201 201
  check(pathSource(G, p) == s,"path() found a wrong path.");
202 202
  check(pathTarget(G, p) == t,"path() found a wrong path.");
203 203

	
204 204
  for(NodeIt v(G); v!=INVALID; ++v) {
205 205
    if (dfs_test.reached(v)) {
206 206
      check(v==s || dfs_test.predArc(v)!=INVALID, "Wrong tree.");
207 207
      if (dfs_test.predArc(v)!=INVALID ) {
208 208
        Arc e=dfs_test.predArc(v);
209 209
        Node u=G.source(e);
210 210
        check(u==dfs_test.predNode(v),"Wrong tree.");
211 211
        check(dfs_test.dist(v) - dfs_test.dist(u) == 1,
212 212
              "Wrong distance. (" << dfs_test.dist(u) << "->"
213 213
              << dfs_test.dist(v) << ")");
214 214
      }
215 215
    }
216 216
  }
217 217

	
218 218
  {
219 219
  Dfs<Digraph> dfs(G);
220 220
  check(dfs.run(s1,t1) && dfs.reached(t1),"Node 3 is reachable from Node 6.");
221 221
  }
222 222
  
223 223
  {
224 224
    NullMap<Node,Arc> myPredMap;
225 225
    dfs(G).predMap(myPredMap).run(s);
226 226
  }
227 227
}
228 228

	
229 229
int main()
230 230
{
231 231
  checkDfs<ListDigraph>();
232 232
  checkDfs<SmartDigraph>();
233 233
  return 0;
234 234
}
Show white space 4096 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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2011
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/smart_graph.h>
20 20
#include <lemon/list_graph.h>
21 21
#include <lemon/lgf_reader.h>
22 22
#include <lemon/error.h>
23 23

	
24 24
#include "test_tools.h"
25 25

	
26 26
using namespace std;
27 27
using namespace lemon;
28 28

	
29 29
void digraph_copy_test() {
30 30
  const int nn = 10;
31 31

	
32 32
  // Build a digraph
33 33
  SmartDigraph from;
34 34
  SmartDigraph::NodeMap<int> fnm(from);
35 35
  SmartDigraph::ArcMap<int> fam(from);
36 36
  SmartDigraph::Node fn = INVALID;
37 37
  SmartDigraph::Arc fa = INVALID;
38 38

	
39 39
  std::vector<SmartDigraph::Node> fnv;
40 40
  for (int i = 0; i < nn; ++i) {
41 41
    SmartDigraph::Node node = from.addNode();
42 42
    fnv.push_back(node);
43 43
    fnm[node] = i * i;
44 44
    if (i == 0) fn = node;
45 45
  }
46 46

	
47 47
  for (int i = 0; i < nn; ++i) {
48 48
    for (int j = 0; j < nn; ++j) {
49 49
      SmartDigraph::Arc arc = from.addArc(fnv[i], fnv[j]);
50 50
      fam[arc] = i + j * j;
51 51
      if (i == 0 && j == 0) fa = arc;
52 52
    }
53 53
  }
54 54

	
55 55
  // Test digraph copy
56 56
  ListDigraph to;
57 57
  ListDigraph::NodeMap<int> tnm(to);
58 58
  ListDigraph::ArcMap<int> tam(to);
59 59
  ListDigraph::Node tn;
60 60
  ListDigraph::Arc ta;
61 61

	
62 62
  SmartDigraph::NodeMap<ListDigraph::Node> nr(from);
63 63
  SmartDigraph::ArcMap<ListDigraph::Arc> er(from);
64 64

	
65 65
  ListDigraph::NodeMap<SmartDigraph::Node> ncr(to);
66 66
  ListDigraph::ArcMap<SmartDigraph::Arc> ecr(to);
67 67

	
68 68
  digraphCopy(from, to).
69 69
    nodeMap(fnm, tnm).arcMap(fam, tam).
70 70
    nodeRef(nr).arcRef(er).
71 71
    nodeCrossRef(ncr).arcCrossRef(ecr).
72 72
    node(fn, tn).arc(fa, ta).run();
73 73
  
74 74
  check(countNodes(from) == countNodes(to), "Wrong copy.");
75 75
  check(countArcs(from) == countArcs(to), "Wrong copy.");
76 76

	
77 77
  for (SmartDigraph::NodeIt it(from); it != INVALID; ++it) {
78 78
    check(ncr[nr[it]] == it, "Wrong copy.");
79 79
    check(fnm[it] == tnm[nr[it]], "Wrong copy.");
80 80
  }
81 81

	
82 82
  for (SmartDigraph::ArcIt it(from); it != INVALID; ++it) {
83 83
    check(ecr[er[it]] == it, "Wrong copy.");
84 84
    check(fam[it] == tam[er[it]], "Wrong copy.");
85 85
    check(nr[from.source(it)] == to.source(er[it]), "Wrong copy.");
86 86
    check(nr[from.target(it)] == to.target(er[it]), "Wrong copy.");
87 87
  }
88 88

	
89 89
  for (ListDigraph::NodeIt it(to); it != INVALID; ++it) {
90 90
    check(nr[ncr[it]] == it, "Wrong copy.");
91 91
  }
92 92

	
93 93
  for (ListDigraph::ArcIt it(to); it != INVALID; ++it) {
94 94
    check(er[ecr[it]] == it, "Wrong copy.");
95 95
  }
96 96
  check(tn == nr[fn], "Wrong copy.");
97 97
  check(ta == er[fa], "Wrong copy.");
98 98

	
99 99
  // Test repeated copy
100 100
  digraphCopy(from, to).run();
101 101
  
102 102
  check(countNodes(from) == countNodes(to), "Wrong copy.");
103 103
  check(countArcs(from) == countArcs(to), "Wrong copy.");
104 104
}
105 105

	
106 106
void graph_copy_test() {
107 107
  const int nn = 10;
108 108

	
109 109
  // Build a graph
110 110
  SmartGraph from;
111 111
  SmartGraph::NodeMap<int> fnm(from);
112 112
  SmartGraph::ArcMap<int> fam(from);
113 113
  SmartGraph::EdgeMap<int> fem(from);
114 114
  SmartGraph::Node fn = INVALID;
115 115
  SmartGraph::Arc fa = INVALID;
116 116
  SmartGraph::Edge fe = INVALID;
117 117

	
118 118
  std::vector<SmartGraph::Node> fnv;
119 119
  for (int i = 0; i < nn; ++i) {
120 120
    SmartGraph::Node node = from.addNode();
121 121
    fnv.push_back(node);
122 122
    fnm[node] = i * i;
123 123
    if (i == 0) fn = node;
124 124
  }
125 125

	
126 126
  for (int i = 0; i < nn; ++i) {
127 127
    for (int j = 0; j < nn; ++j) {
128 128
      SmartGraph::Edge edge = from.addEdge(fnv[i], fnv[j]);
129 129
      fem[edge] = i * i + j * j;
130 130
      fam[from.direct(edge, true)] = i + j * j;
131 131
      fam[from.direct(edge, false)] = i * i + j;
132 132
      if (i == 0 && j == 0) fa = from.direct(edge, true);
133 133
      if (i == 0 && j == 0) fe = edge;
134 134
    }
135 135
  }
136 136

	
137 137
  // Test graph copy
138 138
  ListGraph to;
139 139
  ListGraph::NodeMap<int> tnm(to);
140 140
  ListGraph::ArcMap<int> tam(to);
141 141
  ListGraph::EdgeMap<int> tem(to);
142 142
  ListGraph::Node tn;
143 143
  ListGraph::Arc ta;
144 144
  ListGraph::Edge te;
145 145

	
146 146
  SmartGraph::NodeMap<ListGraph::Node> nr(from);
147 147
  SmartGraph::ArcMap<ListGraph::Arc> ar(from);
148 148
  SmartGraph::EdgeMap<ListGraph::Edge> er(from);
149 149

	
150 150
  ListGraph::NodeMap<SmartGraph::Node> ncr(to);
151 151
  ListGraph::ArcMap<SmartGraph::Arc> acr(to);
152 152
  ListGraph::EdgeMap<SmartGraph::Edge> ecr(to);
153 153

	
154 154
  graphCopy(from, to).
155 155
    nodeMap(fnm, tnm).arcMap(fam, tam).edgeMap(fem, tem).
156 156
    nodeRef(nr).arcRef(ar).edgeRef(er).
157 157
    nodeCrossRef(ncr).arcCrossRef(acr).edgeCrossRef(ecr).
158 158
    node(fn, tn).arc(fa, ta).edge(fe, te).run();
159 159

	
160 160
  check(countNodes(from) == countNodes(to), "Wrong copy.");
161 161
  check(countEdges(from) == countEdges(to), "Wrong copy.");
162 162
  check(countArcs(from) == countArcs(to), "Wrong copy.");
163 163

	
164 164
  for (SmartGraph::NodeIt it(from); it != INVALID; ++it) {
165 165
    check(ncr[nr[it]] == it, "Wrong copy.");
166 166
    check(fnm[it] == tnm[nr[it]], "Wrong copy.");
167 167
  }
168 168

	
169 169
  for (SmartGraph::ArcIt it(from); it != INVALID; ++it) {
170 170
    check(acr[ar[it]] == it, "Wrong copy.");
171 171
    check(fam[it] == tam[ar[it]], "Wrong copy.");
172 172
    check(nr[from.source(it)] == to.source(ar[it]), "Wrong copy.");
173 173
    check(nr[from.target(it)] == to.target(ar[it]), "Wrong copy.");
174 174
  }
175 175

	
176 176
  for (SmartGraph::EdgeIt it(from); it != INVALID; ++it) {
177 177
    check(ecr[er[it]] == it, "Wrong copy.");
178 178
    check(fem[it] == tem[er[it]], "Wrong copy.");
179 179
    check(nr[from.u(it)] == to.u(er[it]) || nr[from.u(it)] == to.v(er[it]),
180 180
          "Wrong copy.");
181 181
    check(nr[from.v(it)] == to.u(er[it]) || nr[from.v(it)] == to.v(er[it]),
182 182
          "Wrong copy.");
183 183
    check((from.u(it) != from.v(it)) == (to.u(er[it]) != to.v(er[it])),
184 184
          "Wrong copy.");
185 185
  }
186 186

	
187 187
  for (ListGraph::NodeIt it(to); it != INVALID; ++it) {
188 188
    check(nr[ncr[it]] == it, "Wrong copy.");
189 189
  }
190 190

	
191 191
  for (ListGraph::ArcIt it(to); it != INVALID; ++it) {
192 192
    check(ar[acr[it]] == it, "Wrong copy.");
193 193
  }
194 194
  for (ListGraph::EdgeIt it(to); it != INVALID; ++it) {
195 195
    check(er[ecr[it]] == it, "Wrong copy.");
196 196
  }
197 197
  check(tn == nr[fn], "Wrong copy.");
198 198
  check(ta == ar[fa], "Wrong copy.");
199 199
  check(te == er[fe], "Wrong copy.");
200 200

	
201 201
  // Test repeated copy
202 202
  graphCopy(from, to).run();
203 203
  
204 204
  check(countNodes(from) == countNodes(to), "Wrong copy.");
205 205
  check(countEdges(from) == countEdges(to), "Wrong copy.");
206 206
  check(countArcs(from) == countArcs(to), "Wrong copy.");
207 207
}
208 208

	
209 209

	
210 210
int main() {
211 211
  digraph_copy_test();
212 212
  graph_copy_test();
213 213

	
214 214
  return 0;
215 215
}
Show white space 4096 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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2011
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 <iostream>
20 20
#include <fstream>
21 21
#include <string>
22 22
#include <vector>
23 23

	
24 24
#include <lemon/concept_check.h>
25 25
#include <lemon/concepts/heap.h>
26 26

	
27 27
#include <lemon/smart_graph.h>
28 28
#include <lemon/lgf_reader.h>
29 29
#include <lemon/dijkstra.h>
30 30
#include <lemon/maps.h>
31 31

	
32 32
#include <lemon/bin_heap.h>
33 33
#include <lemon/quad_heap.h>
34 34
#include <lemon/dheap.h>
35 35
#include <lemon/fib_heap.h>
36 36
#include <lemon/pairing_heap.h>
37 37
#include <lemon/radix_heap.h>
38 38
#include <lemon/binomial_heap.h>
39 39
#include <lemon/bucket_heap.h>
40 40

	
41 41
#include "test_tools.h"
42 42

	
43 43
using namespace lemon;
44 44
using namespace lemon::concepts;
45 45

	
46 46
typedef ListDigraph Digraph;
47 47
DIGRAPH_TYPEDEFS(Digraph);
48 48

	
49 49
char test_lgf[] =
50 50
  "@nodes\n"
51 51
  "label\n"
52 52
  "0\n"
53 53
  "1\n"
54 54
  "2\n"
55 55
  "3\n"
56 56
  "4\n"
57 57
  "5\n"
58 58
  "6\n"
59 59
  "7\n"
60 60
  "8\n"
61 61
  "9\n"
62 62
  "@arcs\n"
63 63
  "                label   capacity\n"
64 64
  "0       5       0       94\n"
65 65
  "3       9       1       11\n"
66 66
  "8       7       2       83\n"
67 67
  "1       2       3       94\n"
68 68
  "5       7       4       35\n"
69 69
  "7       4       5       84\n"
70 70
  "9       5       6       38\n"
71 71
  "0       4       7       96\n"
72 72
  "6       7       8       6\n"
73 73
  "3       1       9       27\n"
74 74
  "5       2       10      77\n"
75 75
  "5       6       11      69\n"
76 76
  "6       5       12      41\n"
77 77
  "4       6       13      70\n"
78 78
  "3       2       14      45\n"
79 79
  "7       9       15      93\n"
80 80
  "5       9       16      50\n"
81 81
  "9       0       17      94\n"
82 82
  "9       6       18      67\n"
83 83
  "0       9       19      86\n"
84 84
  "@attributes\n"
85 85
  "source 3\n";
86 86

	
87 87
int test_seq[] = { 2, 28, 19, 27, 33, 25, 13, 41, 10, 26,  1,  9,  4, 34};
88 88
int test_inc[] = {20, 28, 34, 16,  0, 46, 44,  0, 42, 32, 14,  8,  6, 37};
89 89

	
90 90
int test_len = sizeof(test_seq) / sizeof(test_seq[0]);
91 91

	
92 92
template <typename Heap>
93 93
void heapSortTest() {
94 94
  RangeMap<int> map(test_len, -1);
95 95
  Heap heap(map);
96 96

	
97 97
  std::vector<int> v(test_len);
98 98
  for (int i = 0; i < test_len; ++i) {
99 99
    v[i] = test_seq[i];
100 100
    heap.push(i, v[i]);
101 101
  }
102 102
  std::sort(v.begin(), v.end());
103 103
  for (int i = 0; i < test_len; ++i) {
104 104
    check(v[i] == heap.prio(), "Wrong order in heap sort.");
105 105
    heap.pop();
106 106
  }
107 107
}
108 108

	
109 109
template <typename Heap>
110 110
void heapIncreaseTest() {
111 111
  RangeMap<int> map(test_len, -1);
112 112

	
113 113
  Heap heap(map);
114 114

	
115 115
  std::vector<int> v(test_len);
116 116
  for (int i = 0; i < test_len; ++i) {
117 117
    v[i] = test_seq[i];
118 118
    heap.push(i, v[i]);
119 119
  }
120 120
  for (int i = 0; i < test_len; ++i) {
121 121
    v[i] += test_inc[i];
122 122
    heap.increase(i, v[i]);
123 123
  }
124 124
  std::sort(v.begin(), v.end());
125 125
  for (int i = 0; i < test_len; ++i) {
126 126
    check(v[i] == heap.prio(), "Wrong order in heap increase test.");
127 127
    heap.pop();
128 128
  }
129 129
}
130 130

	
131 131
template <typename Heap>
132 132
void dijkstraHeapTest(const Digraph& digraph, const IntArcMap& length,
133 133
                      Node source) {
134 134

	
135 135
  typename Dijkstra<Digraph, IntArcMap>::template SetStandardHeap<Heap>::
136 136
    Create dijkstra(digraph, length);
137 137

	
138 138
  dijkstra.run(source);
139 139

	
140 140
  for(ArcIt a(digraph); a != INVALID; ++a) {
141 141
    Node s = digraph.source(a);
142 142
    Node t = digraph.target(a);
143 143
    if (dijkstra.reached(s)) {
144 144
      check( dijkstra.dist(t) - dijkstra.dist(s) <= length[a],
145 145
             "Error in shortest path tree.");
146 146
    }
147 147
  }
148 148

	
149 149
  for(NodeIt n(digraph); n != INVALID; ++n) {
150 150
    if ( dijkstra.reached(n) && dijkstra.predArc(n) != INVALID ) {
151 151
      Arc a = dijkstra.predArc(n);
152 152
      Node s = digraph.source(a);
153 153
      check( dijkstra.dist(n) - dijkstra.dist(s) == length[a],
154 154
             "Error in shortest path tree.");
155 155
    }
156 156
  }
157 157

	
158 158
}
159 159

	
160 160
int main() {
161 161

	
162 162
  typedef int Item;
163 163
  typedef int Prio;
164 164
  typedef RangeMap<int> ItemIntMap;
165 165

	
166 166
  Digraph digraph;
167 167
  IntArcMap length(digraph);
168 168
  Node source;
169 169

	
170 170
  std::istringstream input(test_lgf);
171 171
  digraphReader(digraph, input).
172 172
    arcMap("capacity", length).
173 173
    node("source", source).
174 174
    run();
175 175

	
176 176
  // BinHeap
177 177
  {
178 178
    typedef BinHeap<Prio, ItemIntMap> IntHeap;
179 179
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
180 180
    heapSortTest<IntHeap>();
181 181
    heapIncreaseTest<IntHeap>();
182 182

	
183 183
    typedef BinHeap<Prio, IntNodeMap > NodeHeap;
184 184
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
185 185
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
186 186
  }
187 187

	
188 188
  // QuadHeap
189 189
  {
190 190
    typedef QuadHeap<Prio, ItemIntMap> IntHeap;
191 191
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
192 192
    heapSortTest<IntHeap>();
193 193
    heapIncreaseTest<IntHeap>();
194 194

	
195 195
    typedef QuadHeap<Prio, IntNodeMap > NodeHeap;
196 196
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
197 197
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
198 198
  }
199 199

	
200 200
  // DHeap
201 201
  {
202 202
    typedef DHeap<Prio, ItemIntMap> IntHeap;
203 203
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
204 204
    heapSortTest<IntHeap>();
205 205
    heapIncreaseTest<IntHeap>();
206 206

	
207 207
    typedef DHeap<Prio, IntNodeMap > NodeHeap;
208 208
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
209 209
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
210 210
  }
211 211

	
212 212
  // FibHeap
213 213
  {
214 214
    typedef FibHeap<Prio, ItemIntMap> IntHeap;
215 215
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
216 216
    heapSortTest<IntHeap>();
217 217
    heapIncreaseTest<IntHeap>();
218 218

	
219 219
    typedef FibHeap<Prio, IntNodeMap > NodeHeap;
220 220
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
221 221
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
222 222
  }
223 223

	
224 224
  // PairingHeap
225 225
  {
226 226
    typedef PairingHeap<Prio, ItemIntMap> IntHeap;
227 227
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
228 228
    heapSortTest<IntHeap>();
229 229
    heapIncreaseTest<IntHeap>();
230 230

	
231 231
    typedef PairingHeap<Prio, IntNodeMap > NodeHeap;
232 232
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
233 233
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
234 234
  }
235 235

	
236 236
  // RadixHeap
237 237
  {
238 238
    typedef RadixHeap<ItemIntMap> IntHeap;
239 239
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
240 240
    heapSortTest<IntHeap>();
241 241
    heapIncreaseTest<IntHeap>();
242 242

	
243 243
    typedef RadixHeap<IntNodeMap > NodeHeap;
244 244
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
245 245
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
246 246
  }
247 247

	
248 248
  // BinomialHeap
249 249
  {
250 250
    typedef BinomialHeap<Prio, ItemIntMap> IntHeap;
251 251
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
252 252
    heapSortTest<IntHeap>();
253 253
    heapIncreaseTest<IntHeap>();
254 254

	
255 255
    typedef BinomialHeap<Prio, IntNodeMap > NodeHeap;
256 256
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
257 257
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
258 258
  }
259 259

	
260 260
  // BucketHeap, SimpleBucketHeap
261 261
  {
262 262
    typedef BucketHeap<ItemIntMap> IntHeap;
263 263
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
264 264
    heapSortTest<IntHeap>();
265 265
    heapIncreaseTest<IntHeap>();
266 266

	
267 267
    typedef BucketHeap<IntNodeMap > NodeHeap;
268 268
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
269 269
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
270 270

	
271 271
    typedef SimpleBucketHeap<ItemIntMap> SimpleIntHeap;
272 272
    heapSortTest<SimpleIntHeap>();
273 273
  }
274 274

	
275 275
  {
276 276
    typedef FibHeap<Prio, ItemIntMap> IntHeap;
277 277
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
278 278
    heapSortTest<IntHeap>();
279 279
    heapIncreaseTest<IntHeap>();
280 280

	
281 281
    typedef FibHeap<Prio, IntNodeMap > NodeHeap;
282 282
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
283 283
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
284 284
  }
285 285

	
286 286
  {
287 287
    typedef RadixHeap<ItemIntMap> IntHeap;
288 288
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
289 289
    heapSortTest<IntHeap>();
290 290
    heapIncreaseTest<IntHeap>();
291 291

	
292 292
    typedef RadixHeap<IntNodeMap > NodeHeap;
293 293
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
294 294
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
295 295
  }
296 296

	
297 297
  {
298 298
    typedef BucketHeap<ItemIntMap> IntHeap;
299 299
    checkConcept<Heap<Prio, ItemIntMap>, IntHeap>();
300 300
    heapSortTest<IntHeap>();
301 301
    heapIncreaseTest<IntHeap>();
302 302

	
303 303
    typedef BucketHeap<IntNodeMap > NodeHeap;
304 304
    checkConcept<Heap<Prio, IntNodeMap >, NodeHeap>();
305 305
    dijkstraHeapTest<NodeHeap>(digraph, length, source);
306 306
  }
307 307

	
308 308

	
309 309
  return 0;
310 310
}
Show white space 4096 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
 * Copyright (C) 2003-2010
5
 * Copyright (C) 2003-2011
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 <deque>
20 20
#include <set>
21 21

	
22 22
#include <lemon/concept_check.h>
23 23
#include <lemon/concepts/maps.h>
24 24
#include <lemon/maps.h>
25 25
#include <lemon/list_graph.h>
26 26
#include <lemon/smart_graph.h>
27 27
#include <lemon/adaptors.h>
28 28
#include <lemon/dfs.h>
29 29
#include <algorithm>
30 30

	
31 31
#include "test_tools.h"
32 32

	
33 33
using namespace lemon;
34 34
using namespace lemon::concepts;
35 35

	
36 36
struct A {};
37 37
inline bool operator<(A, A) { return true; }
38 38
struct B {};
39 39

	
40 40
class C {
41 41
  int _x;
42 42
public:
43 43
  C(int x) : _x(x) {}
44 44
  int get() const { return _x; }
45 45
};
46 46
inline bool operator<(C c1, C c2) { return c1.get() < c2.get(); }
47 47
inline bool operator==(C c1, C c2) { return c1.get() == c2.get(); }
48 48

	
49 49
C createC(int x) { return C(x); }
50 50

	
51 51
template <typename T>
52 52
class Less {
53 53
  T _t;
54 54
public:
55 55
  Less(T t): _t(t) {}
56 56
  bool operator()(const T& t) const { return t < _t; }
57 57
};
58 58

	
59 59
class F {
60 60
public:
61 61
  typedef A argument_type;
62 62
  typedef B result_type;
63 63

	
64 64
  B operator()(const A&) const { return B(); }
65 65
private:
66 66
  F& operator=(const F&);
67 67
};
68 68

	
69 69
int func(A) { return 3; }
70 70

	
71 71
int binc(int a, B) { return a+1; }
72 72

	
73 73
template <typename T>
74 74
class Sum {
75 75
  T& _sum;
76 76
public:
77 77
  Sum(T& sum) : _sum(sum) {}
78 78
  void operator()(const T& t) { _sum += t; }
79 79
};
80 80

	
81 81
typedef ReadMap<A, double> DoubleMap;
82 82
typedef ReadWriteMap<A, double> DoubleWriteMap;
83 83
typedef ReferenceMap<A, double, double&, const double&> DoubleRefMap;
84 84

	
85 85
typedef ReadMap<A, bool> BoolMap;
86 86
typedef ReadWriteMap<A, bool> BoolWriteMap;
87 87
typedef ReferenceMap<A, bool, bool&, const bool&> BoolRefMap;
88 88

	
89 89
int main()
90 90
{
91 91
  // Map concepts
92 92
  checkConcept<ReadMap<A,B>, ReadMap<A,B> >();
93 93
  checkConcept<ReadMap<A,C>, ReadMap<A,C> >();
94 94
  checkConcept<WriteMap<A,B>, WriteMap<A,B> >();
95 95
  checkConcept<WriteMap<A,C>, WriteMap<A,C> >();
96 96
  checkConcept<ReadWriteMap<A,B>, ReadWriteMap<A,B> >();
97 97
  checkConcept<ReadWriteMap<A,C>, ReadWriteMap<A,C> >();
98 98
  checkConcept<ReferenceMap<A,B,B&,const B&>, ReferenceMap<A,B,B&,const B&> >();
99 99
  checkConcept<ReferenceMap<A,C,C&,const C&>, ReferenceMap<A,C,C&,const C&> >();
100 100

	
101 101
  // NullMap
102 102
  {
103 103
    checkConcept<ReadWriteMap<A,B>, NullMap<A,B> >();
104 104
    NullMap<A,B> map1;
105 105
    NullMap<A,B> map2 = map1;
106 106
    map1 = nullMap<A,B>();
107 107
  }
108 108

	
109 109
  // ConstMap
110 110
  {
111 111
    checkConcept<ReadWriteMap<A,B>, ConstMap<A,B> >();
112 112
    checkConcept<ReadWriteMap<A,C>, ConstMap<A,C> >();
113 113
    ConstMap<A,B> map1;
114 114
    ConstMap<A,B> map2 = B();
115 115
    ConstMap<A,B> map3 = map1;
116 116
    map1 = constMap<A>(B());
117 117
    map1 = constMap<A,B>();
118 118
    map1.setAll(B());
119 119
    ConstMap<A,C> map4(C(1));
120 120
    ConstMap<A,C> map5 = map4;
121 121
    map4 = constMap<A>(C(2));
122 122
    map4.setAll(C(3));
123 123

	
124 124
    checkConcept<ReadWriteMap<A,int>, ConstMap<A,int> >();
125 125
    check(constMap<A>(10)[A()] == 10, "Something is wrong with ConstMap");
126 126

	
127 127
    checkConcept<ReadWriteMap<A,int>, ConstMap<A,Const<int,10> > >();
128 128
    ConstMap<A,Const<int,10> > map6;
129 129
    ConstMap<A,Const<int,10> > map7 = map6;
130 130
    map6 = constMap<A,int,10>();
131 131
    map7 = constMap<A,Const<int,10> >();
132 132
    check(map6[A()] == 10 && map7[A()] == 10,
133 133
          "Something is wrong with ConstMap");
134 134
  }
135 135

	
136 136
  // IdentityMap
137 137
  {
138 138
    checkConcept<ReadMap<A,A>, IdentityMap<A> >();
139 139
    IdentityMap<A> map1;
140 140
    IdentityMap<A> map2 = map1;
141 141
    map1 = identityMap<A>();
142 142

	
143 143
    checkConcept<ReadMap<double,double>, IdentityMap<double> >();
144 144
    check(identityMap<double>()[1.0] == 1.0 &&
145 145
          identityMap<double>()[3.14] == 3.14,
146 146
          "Something is wrong with IdentityMap");
147 147
  }
148 148

	
149 149
  // RangeMap
150 150
  {
151 151
    checkConcept<ReferenceMap<int,B,B&,const B&>, RangeMap<B> >();
152 152
    RangeMap<B> map1;
153 153
    RangeMap<B> map2(10);
154 154
    RangeMap<B> map3(10,B());
155 155
    RangeMap<B> map4 = map1;
156 156
    RangeMap<B> map5 = rangeMap<B>();
157 157
    RangeMap<B> map6 = rangeMap<B>(10);
158 158
    RangeMap<B> map7 = rangeMap(10,B());
159 159

	
160 160
    checkConcept< ReferenceMap<int, double, double&, const double&>,
161 161
                  RangeMap<double> >();
162 162
    std::vector<double> v(10, 0);
163 163
    v[5] = 100;
164 164
    RangeMap<double> map8(v);
165 165
    RangeMap<double> map9 = rangeMap(v);
166 166
    check(map9.size() == 10 && map9[2] == 0 && map9[5] == 100,
167 167
          "Something is wrong with RangeMap");
168 168
  }
169 169

	
170 170
  // SparseMap
171 171
  {
172 172
    checkConcept<ReferenceMap<A,B,B&,const B&>, SparseMap<A,B> >();
173 173
    SparseMap<A,B> map1;
174 174
    SparseMap<A,B> map2 = B();
175 175
    SparseMap<A,B> map3 = sparseMap<A,B>();
176 176
    SparseMap<A,B> map4 = sparseMap<A>(B());
177 177

	
178 178
    checkConcept< ReferenceMap<double, int, int&, const int&>,
179 179
                  SparseMap<double, int> >();
180 180
    std::map<double, int> m;
181 181
    SparseMap<double, int> map5(m);
182 182
    SparseMap<double, int> map6(m,10);
183 183
    SparseMap<double, int> map7 = sparseMap(m);
184 184
    SparseMap<double, int> map8 = sparseMap(m,10);
185 185

	
186 186
    check(map5[1.0] == 0 && map5[3.14] == 0 &&
187 187
          map6[1.0] == 10 && map6[3.14] == 10,
188 188
          "Something is wrong with SparseMap");
189 189
    map5[1.0] = map6[3.14] = 100;
190 190
    check(map5[1.0] == 100 && map5[3.14] == 0 &&
191 191
          map6[1.0] == 10 && map6[3.14] == 100,
192 192
          "Something is wrong with SparseMap");
193 193
  }
194 194

	
195 195
  // ComposeMap
196 196
  {
197 197
    typedef ComposeMap<DoubleMap, ReadMap<B,A> > CompMap;
198 198
    checkConcept<ReadMap<B,double>, CompMap>();
199 199
    CompMap map1 = CompMap(DoubleMap(),ReadMap<B,A>());
200 200
    CompMap map2 = composeMap(DoubleMap(), ReadMap<B,A>());
201 201

	
202 202
    SparseMap<double, bool> m1(false); m1[3.14] = true;
203 203
    RangeMap<double> m2(2); m2[0] = 3.0; m2[1] = 3.14;
204 204
    check(!composeMap(m1,m2)[0] && composeMap(m1,m2)[1],
205 205
          "Something is wrong with ComposeMap")
206 206
  }
207 207

	
208 208
  // CombineMap
209 209
  {
210 210
    typedef CombineMap<DoubleMap, DoubleMap, std::plus<double> > CombMap;
211 211
    checkConcept<ReadMap<A,double>, CombMap>();
212 212
    CombMap map1 = CombMap(DoubleMap(), DoubleMap());
213 213
    CombMap map2 = combineMap(DoubleMap(), DoubleMap(), std::plus<double>());
214 214

	
215 215
    check(combineMap(constMap<B,int,2>(), identityMap<B>(), &binc)[B()] == 3,
216 216
          "Something is wrong with CombineMap");
217 217
  }
218 218

	
219 219
  // FunctorToMap, MapToFunctor
220 220
  {
221 221
    checkConcept<ReadMap<A,B>, FunctorToMap<F,A,B> >();
222 222
    checkConcept<ReadMap<A,B>, FunctorToMap<F> >();
223 223
    FunctorToMap<F> map1;
224 224
    FunctorToMap<F> map2 = FunctorToMap<F>(F());
225 225
    B b = functorToMap(F())[A()];
226 226

	
227 227
    checkConcept<ReadMap<A,B>, MapToFunctor<ReadMap<A,B> > >();
228 228
    MapToFunctor<ReadMap<A,B> > map =
229 229
      MapToFunctor<ReadMap<A,B> >(ReadMap<A,B>());
230 230

	
231 231
    check(functorToMap(&func)[A()] == 3,
232 232
          "Something is wrong with FunctorToMap");
233 233
    check(mapToFunctor(constMap<A,int>(2))(A()) == 2,
234 234
          "Something is wrong with MapToFunctor");
235 235
    check(mapToFunctor(functorToMap(&func))(A()) == 3 &&
236 236
          mapToFunctor(functorToMap(&func))[A()] == 3,
237 237
          "Something is wrong with FunctorToMap or MapToFunctor");
238 238
    check(functorToMap(mapToFunctor(constMap<A,int>(2)))[A()] == 2,
239 239
          "Something is wrong with FunctorToMap or MapToFunctor");
240 240
  }
241 241

	
242 242
  // ConvertMap
243 243
  {
244 244
    checkConcept<ReadMap<double,double>,
245 245
      ConvertMap<ReadMap<double, int>, double> >();
246 246
    ConvertMap<RangeMap<bool>, int> map1(rangeMap(1, true));
247 247
    ConvertMap<RangeMap<bool>, int> map2 = convertMap<int>(rangeMap(2, false));
248 248
  }
249 249

	
250 250
  // ForkMap
251 251
  {
252 252
    checkConcept<DoubleWriteMap, ForkMap<DoubleWriteMap, DoubleWriteMap> >();
253 253

	
254 254
    typedef RangeMap<double> RM;
255 255
    typedef SparseMap<int, double> SM;
256 256
    RM m1(10, -1);
257 257
    SM m2(-1);
258 258
    checkConcept<ReadWriteMap<int, double>, ForkMap<RM, SM> >();
259 259
    checkConcept<ReadWriteMap<int, double>, ForkMap<SM, RM> >();
260 260
    ForkMap<RM, SM> map1(m1,m2);
261 261
    ForkMap<SM, RM> map2 = forkMap(m2,m1);
262 262
    map2.set(5, 10);
263 263
    check(m1[1] == -1 && m1[5] == 10 && m2[1] == -1 &&
264 264
          m2[5] == 10 && map2[1] == -1 && map2[5] == 10,
265 265
          "Something is wrong with ForkMap");
266 266
  }
267 267

	
268 268
  // Arithmetic maps:
269 269
  // - AddMap, SubMap, MulMap, DivMap
270 270
  // - ShiftMap, ShiftWriteMap, ScaleMap, ScaleWriteMap
271 271
  // - NegMap, NegWriteMap, AbsMap
272 272
  {
273 273
    checkConcept<DoubleMap, AddMap<DoubleMap,DoubleMap> >();
274 274
    checkConcept<DoubleMap, SubMap<DoubleMap,DoubleMap> >();
275 275
    checkConcept<DoubleMap, MulMap<DoubleMap,DoubleMap> >();
276 276
    checkConcept<DoubleMap, DivMap<DoubleMap,DoubleMap> >();
277 277

	
278 278
    ConstMap<int, double> c1(1.0), c2(3.14);
279 279
    IdentityMap<int> im;
280 280
    ConvertMap<IdentityMap<int>, double> id(im);
281 281
    check(addMap(c1,id)[0] == 1.0  && addMap(c1,id)[10] == 11.0,
282 282
          "Something is wrong with AddMap");
283 283
    check(subMap(id,c1)[0] == -1.0 && subMap(id,c1)[10] == 9.0,
284 284
          "Something is wrong with SubMap");
285 285
    check(mulMap(id,c2)[0] == 0    && mulMap(id,c2)[2]  == 6.28,
286 286
          "Something is wrong with MulMap");
287 287
    check(divMap(c2,id)[1] == 3.14 && divMap(c2,id)[2]  == 1.57,
288 288
          "Something is wrong with DivMap");
289 289

	
290 290
    checkConcept<DoubleMap, ShiftMap<DoubleMap> >();
291 291
    checkConcept<DoubleWriteMap, ShiftWriteMap<DoubleWriteMap> >();
292 292
    checkConcept<DoubleMap, ScaleMap<DoubleMap> >();
293 293
    checkConcept<DoubleWriteMap, ScaleWriteMap<DoubleWriteMap> >();
294 294
    checkConcept<DoubleMap, NegMap<DoubleMap> >();
295 295
    checkConcept<DoubleWriteMap, NegWriteMap<DoubleWriteMap> >();
296 296
    checkConcept<DoubleMap, AbsMap<DoubleMap> >();
297 297

	
298 298
    check(shiftMap(id, 2.0)[1] == 3.0 && shiftMap(id, 2.0)[10] == 12.0,
299 299
          "Something is wrong with ShiftMap");
300 300
    check(shiftWriteMap(id, 2.0)[1] == 3.0 &&
301 301
          shiftWriteMap(id, 2.0)[10] == 12.0,
302 302
          "Something is wrong with ShiftWriteMap");
303 303
    check(scaleMap(id, 2.0)[1] == 2.0 && scaleMap(id, 2.0)[10] == 20.0,
304 304
          "Something is wrong with ScaleMap");
305 305
    check(scaleWriteMap(id, 2.0)[1] == 2.0 &&
306 306
          scaleWriteMap(id, 2.0)[10] == 20.0,
307 307
          "Something is wrong with ScaleWriteMap");
308 308
    check(negMap(id)[1] == -1.0 && negMap(id)[-10] == 10.0,
309 309
          "Something is wrong with NegMap");
310 310
    check(negWriteMap(id)[1] == -1.0 && negWriteMap(id)[-10] == 10.0,
311 311
          "Something is wrong with NegWriteMap");
312 312
    check(absMap(id)[1] == 1.0 && absMap(id)[-10] == 10.0,
313 313
          "Something is wrong with AbsMap");
314 314
  }
315 315

	
316 316
  // Logical maps:
317 317
  // - TrueMap, FalseMap
318 318
  // - AndMap, OrMap
319 319
  // - NotMap, NotWriteMap
320 320
  // - EqualMap, LessMap
321 321
  {
322 322
    checkConcept<BoolMap, TrueMap<A> >();
323 323
    checkConcept<BoolMap, FalseMap<A> >();
324 324
    checkConcept<BoolMap, AndMap<BoolMap,BoolMap> >();
325 325
    checkConcept<BoolMap, OrMap<BoolMap,BoolMap> >();
326 326
    checkConcept<BoolMap, NotMap<BoolMap> >();
327 327
    checkConcept<BoolWriteMap, NotWriteMap<BoolWriteMap> >();
328 328
    checkConcept<BoolMap, EqualMap<DoubleMap,DoubleMap> >();
329 329
    checkConcept<BoolMap, LessMap<DoubleMap,DoubleMap> >();
330 330

	
331 331
    TrueMap<int> tm;
332 332
    FalseMap<int> fm;
333 333
    RangeMap<bool> rm(2);
334 334
    rm[0] = true; rm[1] = false;
335 335
    check(andMap(tm,rm)[0] && !andMap(tm,rm)[1] &&
336 336
          !andMap(fm,rm)[0] && !andMap(fm,rm)[1],
337 337
          "Something is wrong with AndMap");
338 338
    check(orMap(tm,rm)[0] && orMap(tm,rm)[1] &&
339 339
          orMap(fm,rm)[0] && !orMap(fm,rm)[1],
340 340
          "Something is wrong with OrMap");
341 341
    check(!notMap(rm)[0] && notMap(rm)[1],
342 342
          "Something is wrong with NotMap");
343 343
    check(!notWriteMap(rm)[0] && notWriteMap(rm)[1],
344 344
          "Something is wrong with NotWriteMap");
345 345

	
346 346
    ConstMap<int, double> cm(2.0);
347 347
    IdentityMap<int> im;
348 348
    ConvertMap<IdentityMap<int>, double> id(im);
349 349
    check(lessMap(id,cm)[1] && !lessMap(id,cm)[2] && !lessMap(id,cm)[3],
350 350
          "Something is wrong with LessMap");
351 351
    check(!equalMap(id,cm)[1] && equalMap(id,cm)[2] && !equalMap(id,cm)[3],
352 352
          "Something is wrong with EqualMap");
353 353
  }
354 354

	
355 355
  // LoggerBoolMap
356 356
  {
357 357
    typedef std::vector<int> vec;
358 358
    checkConcept<WriteMap<int, bool>, LoggerBoolMap<vec::iterator> >();
359 359
    checkConcept<WriteMap<int, bool>,
360 360
                 LoggerBoolMap<std::back_insert_iterator<vec> > >();
361 361

	
362 362
    vec v1;
363 363
    vec v2(10);
364 364
    LoggerBoolMap<std::back_insert_iterator<vec> >
365 365
      map1(std::back_inserter(v1));
366 366
    LoggerBoolMap<vec::iterator> map2(v2.begin());
367 367
    map1.set(10, false);
368 368
    map1.set(20, true);   map2.set(20, true);
369 369
    map1.set(30, false);  map2.set(40, false);
370 370
    map1.set(50, true);   map2.set(50, true);
371 371
    map1.set(60, true);   map2.set(60, true);
372 372
    check(v1.size() == 3 && v2.size() == 10 &&
373 373
          v1[0]==20 && v1[1]==50 && v1[2]==60 &&
374 374
          v2[0]==20 && v2[1]==50 && v2[2]==60,
375 375
          "Something is wrong with LoggerBoolMap");
376 376

	
377 377
    int i = 0;
378 378
    for ( LoggerBoolMap<vec::iterator>::Iterator it = map2.begin();
379 379
          it != map2.end(); ++it )
380 380
      check(v1[i++] == *it, "Something is wrong with LoggerBoolMap");
381 381

	
382 382
    typedef ListDigraph Graph;
383 383
    DIGRAPH_TYPEDEFS(Graph);
384 384
    Graph gr;
385 385

	
386 386
    Node n0 = gr.addNode();
387 387
    Node n1 = gr.addNode();
388 388
    Node n2 = gr.addNode();
389 389
    Node n3 = gr.addNode();
390 390

	
391 391
    gr.addArc(n3, n0);
392 392
    gr.addArc(n3, n2);
393 393
    gr.addArc(n0, n2);
394 394
    gr.addArc(n2, n1);
395 395
    gr.addArc(n0, n1);
396 396

	
397 397
    {
398 398
      std::vector<Node> v;
399 399
      dfs(gr).processedMap(loggerBoolMap(std::back_inserter(v))).run();
400 400

	
401 401
      check(v.size()==4 && v[0]==n1 && v[1]==n2 && v[2]==n0 && v[3]==n3,
402 402
            "Something is wrong with LoggerBoolMap");
403 403
    }
404 404
    {
405 405
      std::vector<Node> v(countNodes(gr));
406 406
      dfs(gr).processedMap(loggerBoolMap(v.begin())).run();
407 407

	
408 408
      check(v.size()==4 && v[0]==n1 && v[1]==n2 && v[2]==n0 && v[3]==n3,
409 409
            "Something is wrong with LoggerBoolMap");
410 410
    }
411 411
  }
412 412

	
413 413
  // IdMap, RangeIdMap
414 414
  {
415 415
    typedef ListDigraph Graph;
416 416
    DIGRAPH_TYPEDEFS(Graph);
417 417

	
418 418
    checkConcept<ReadMap<Node, int>, IdMap<Graph, Node> >();
419 419
    checkConcept<ReadMap<Arc, int>, IdMap<Graph, Arc> >();
420 420
    checkConcept<ReadMap<Node, int>, RangeIdMap<Graph, Node> >();
421 421
    checkConcept<ReadMap<Arc, int>, RangeIdMap<Graph, Arc> >();
422 422

	
423 423
    Graph gr;
424 424
    IdMap<Graph, Node> nmap(gr);
425 425
    IdMap<Graph, Arc> amap(gr);
426 426
    RangeIdMap<Graph, Node> nrmap(gr);
427 427
    RangeIdMap<Graph, Arc> armap(gr);
428 428

	
429 429
    Node n0 = gr.addNode();
430 430
    Node n1 = gr.addNode();
431 431
    Node n2 = gr.addNode();
432 432

	
433 433
    Arc a0 = gr.addArc(n0, n1);
434 434
    Arc a1 = gr.addArc(n0, n2);
435 435
    Arc a2 = gr.addArc(n2, n1);
436 436
    Arc a3 = gr.addArc(n2, n0);
437 437

	
438 438
    check(nmap[n0] == gr.id(n0) && nmap(gr.id(n0)) == n0, "Wrong IdMap");
439 439
    check(nmap[n1] == gr.id(n1) && nmap(gr.id(n1)) == n1, "Wrong IdMap");
440 440
    check(nmap[n2] == gr.id(n2) && nmap(gr.id(n2)) == n2, "Wrong IdMap");
441 441

	
442 442
    check(amap[a0] == gr.id(a0) && amap(gr.id(a0)) == a0, "Wrong IdMap");
443 443
    check(amap[a1] == gr.id(a1) && amap(gr.id(a1)) == a1, "Wrong IdMap");
444 444
    check(amap[a2] == gr.id(a2) && amap(gr.id(a2)) == a2, "Wrong IdMap");
445 445
    check(amap[a3] == gr.id(a3) && amap(gr.id(a3)) == a3, "Wrong IdMap");
446 446

	
447 447
    check(nmap.inverse()[gr.id(n0)] == n0, "Wrong IdMap::InverseMap");
448 448
    check(amap.inverse()[gr.id(a0)] == a0, "Wrong IdMap::InverseMap");
449 449

	
450 450
    check(nrmap.size() == 3 && armap.size() == 4,
451 451
          "Wrong RangeIdMap::size()");
452 452

	
453 453
    check(nrmap[n0] == 0 && nrmap(0) == n0, "Wrong RangeIdMap");
454 454
    check(nrmap[n1] == 1 && nrmap(1) == n1, "Wrong RangeIdMap");
455 455
    check(nrmap[n2] == 2 && nrmap(2) == n2, "Wrong RangeIdMap");
456 456

	
457 457
    check(armap[a0] == 0 && armap(0) == a0, "Wrong RangeIdMap");
458 458
    check(armap[a1] == 1 && armap(1) == a1, "Wrong RangeIdMap");
459 459
    check(armap[a2] == 2 && armap(2) == a2, "Wrong RangeIdMap");
460 460
    check(armap[a3] == 3 && armap(3) == a3, "Wrong RangeIdMap");
461 461

	
462 462
    check(nrmap.inverse()[0] == n0, "Wrong RangeIdMap::InverseMap");
463 463
    check(armap.inverse()[0] == a0, "Wrong RangeIdMap::InverseMap");
464 464

	
465 465
    gr.erase(n1);
466 466

	
467 467
    if (nrmap[n0] == 1) nrmap.swap(n0, n2);
468 468
    nrmap.swap(n2, n0);
469 469
    if (armap[a1] == 1) armap.swap(a1, a3);
470 470
    armap.swap(a3, a1);
471 471

	
472 472
    check(nrmap.size() == 2 && armap.size() == 2,
473 473
          "Wrong RangeIdMap::size()");
474 474

	
475 475
    check(nrmap[n0] == 1 && nrmap(1) == n0, "Wrong RangeIdMap");
476 476
    check(nrmap[n2] == 0 && nrmap(0) == n2, "Wrong RangeIdMap");
477 477

	
478 478
    check(armap[a1] == 1 && armap(1) == a1, "Wrong RangeIdMap");
479 479
    check(armap[a3] == 0 && armap(0) == a3, "Wrong RangeIdMap");
480 480

	
481 481
    check(nrmap.inverse()[0] == n2, "Wrong RangeIdMap::InverseMap");
482 482
    check(armap.inverse()[0] == a3, "Wrong RangeIdMap::InverseMap");
483 483
  }
484 484

	
485 485
  // SourceMap, TargetMap, ForwardMap, BackwardMap, InDegMap, OutDegMap
486 486
  {
487 487
    typedef ListGraph Graph;
488 488
    GRAPH_TYPEDEFS(Graph);
489 489

	
490 490
    checkConcept<ReadMap<Arc, Node>, SourceMap<Graph> >();
491 491
    checkConcept<ReadMap<Arc, Node>, TargetMap<Graph> >();
492 492
    checkConcept<ReadMap<Edge, Arc>, ForwardMap<Graph> >();
493 493
    checkConcept<ReadMap<Edge, Arc>, BackwardMap<Graph> >();
494 494
    checkConcept<ReadMap<Node, int>, InDegMap<Graph> >();
495 495
    checkConcept<ReadMap<Node, int>, OutDegMap<Graph> >();
496 496

	
497 497
    Graph gr;
498 498
    Node n0 = gr.addNode();
499 499
    Node n1 = gr.addNode();
500 500
    Node n2 = gr.addNode();
501 501

	
502 502
    gr.addEdge(n0,n1);
503 503
    gr.addEdge(n1,n2);
504 504
    gr.addEdge(n0,n2);
505 505
    gr.addEdge(n2,n1);
506 506
    gr.addEdge(n1,n2);
507 507
    gr.addEdge(n0,n1);
508 508

	
509 509
    for (EdgeIt e(gr); e != INVALID; ++e) {
510 510
      check(forwardMap(gr)[e] == gr.direct(e, true), "Wrong ForwardMap");
511 511
      check(backwardMap(gr)[e] == gr.direct(e, false), "Wrong BackwardMap");
512 512
    }
513 513

	
514 514
    check(mapCompare(gr,
515 515
          sourceMap(orienter(gr, constMap<Edge, bool>(true))),
516 516
          targetMap(orienter(gr, constMap<Edge, bool>(false)))),
517 517
          "Wrong SourceMap or TargetMap");
518 518

	
519 519
    typedef Orienter<Graph, const ConstMap<Edge, bool> > Digraph;
520 520
    Digraph dgr(gr, constMap<Edge, bool>(true));
521 521
    OutDegMap<Digraph> odm(dgr);
522 522
    InDegMap<Digraph> idm(dgr);
523 523

	
524 524
    check(odm[n0] == 3 && odm[n1] == 2 && odm[n2] == 1, "Wrong OutDegMap");
525 525
    check(idm[n0] == 0 && idm[n1] == 3 && idm[n2] == 3, "Wrong InDegMap");
526 526

	
527 527
    gr.addEdge(n2, n0);
528 528

	
529 529
    check(odm[n0] == 3 && odm[n1] == 2 && odm[n2] == 2, "Wrong OutDegMap");
530 530
    check(idm[n0] == 1 && idm[n1] == 3 && idm[n2] == 3, "Wrong InDegMap");
531 531
  }
532 532

	
533 533
  // CrossRefMap
534 534
  {
535 535
    typedef ListDigraph Graph;
536 536
    DIGRAPH_TYPEDEFS(Graph);
537 537

	
538 538
    checkConcept<ReadWriteMap<Node, int>,
539 539
                 CrossRefMap<Graph, Node, int> >();
540 540
    checkConcept<ReadWriteMap<Node, bool>,
541 541
                 CrossRefMap<Graph, Node, bool> >();
542 542
    checkConcept<ReadWriteMap<Node, double>,
543 543
                 CrossRefMap<Graph, Node, double> >();
544 544

	
545 545
    Graph gr;
546 546
    typedef CrossRefMap<Graph, Node, char> CRMap;
547 547
    CRMap map(gr);
548 548

	
549 549
    Node n0 = gr.addNode();
550 550
    Node n1 = gr.addNode();
551 551
    Node n2 = gr.addNode();
552 552

	
553 553
    map.set(n0, 'A');
554 554
    map.set(n1, 'B');
555 555
    map.set(n2, 'C');
556 556

	
557 557
    check(map[n0] == 'A' && map('A') == n0 && map.inverse()['A'] == n0,
558 558
          "Wrong CrossRefMap");
559 559
    check(map[n1] == 'B' && map('B') == n1 && map.inverse()['B'] == n1,
560 560
          "Wrong CrossRefMap");
561 561
    check(map[n2] == 'C' && map('C') == n2 && map.inverse()['C'] == n2,
562 562
          "Wrong CrossRefMap");
563 563
    check(map.count('A') == 1 && map.count('B') == 1 && map.count('C') == 1,
564 564
          "Wrong CrossRefMap::count()");
565 565

	
566 566
    CRMap::ValueIt it = map.beginValue();
567 567
    check(*it++ == 'A' && *it++ == 'B' && *it++ == 'C' &&
568 568
          it == map.endValue(), "Wrong value iterator");
569 569

	
570 570
    map.set(n2, 'A');
571 571

	
572 572
    check(map[n0] == 'A' && map[n1] == 'B' && map[n2] == 'A',
573 573
          "Wrong CrossRefMap");
574 574
    check(map('A') == n0 && map.inverse()['A'] == n0, "Wrong CrossRefMap");
575 575
    check(map('B') == n1 && map.inverse()['B'] == n1, "Wrong CrossRefMap");
576 576
    check(map('C') == INVALID && map.inverse()['C'] == INVALID,
577 577
          "Wrong CrossRefMap");
578 578
    check(map.count('A') == 2 && map.count('B') == 1 && map.count('C') == 0,
579 579
          "Wrong CrossRefMap::count()");
580 580

	
581 581
    it = map.beginValue();
582 582
    check(*it++ == 'A' && *it++ == 'A' && *it++ == 'B' &&
583 583
          it == map.endValue(), "Wrong value iterator");
584 584

	
585 585
    map.set(n0, 'C');
586 586

	
587 587
    check(map[n0] == 'C' && map[n1] == 'B' && map[n2] == 'A',
588 588
          "Wrong CrossRefMap");
589 589
    check(map('A') == n2 && map.inverse()['A'] == n2, "Wrong CrossRefMap");
590 590
    check(map('B') == n1 && map.inverse()['B'] == n1, "Wrong CrossRefMap");
591 591
    check(map('C') == n0 && map.inverse()['C'] == n0, "Wrong CrossRefMap");
592 592
    check(map.count('A') == 1 && map.count('B') == 1 && map.count('C') == 1,
593 593
          "Wrong CrossRefMap::count()");
594 594

	
595 595
    it = map.beginValue();
596 596
    check(*it++ == 'A' && *it++ == 'B' && *it++ == 'C' &&
597 597
          it == map.endValue(), "Wrong value iterator");
598 598
  }
599 599

	
600 600
  // CrossRefMap
601 601
  {
602 602
    typedef SmartDigraph Graph;
603 603
    DIGRAPH_TYPEDEFS(Graph);
604 604

	
605 605
    checkConcept<ReadWriteMap<Node, int>,
606 606
                 CrossRefMap<Graph, Node, int> >();
607 607

	
608 608
    Graph gr;
609 609
    typedef CrossRefMap<Graph, Node, char> CRMap;
610 610
    typedef CRMap::ValueIterator ValueIt;
611 611
    CRMap map(gr);
612 612

	
613 613
    Node n0 = gr.addNode();
614 614
    Node n1 = gr.addNode();
615 615
    Node n2 = gr.addNode();
616 616

	
617 617
    map.set(n0, 'A');
618 618
    map.set(n1, 'B');
619 619
    map.set(n2, 'C');
620 620
    map.set(n2, 'A');
621 621
    map.set(n0, 'C');
622 622

	
623 623
    check(map[n0] == 'C' && map[n1] == 'B' && map[n2] == 'A',
624 624
          "Wrong CrossRefMap");
625 625
    check(map('A') == n2 && map.inverse()['A'] == n2, "Wrong CrossRefMap");
626 626
    check(map('B') == n1 && map.inverse()['B'] == n1, "Wrong CrossRefMap");
627 627
    check(map('C') == n0 && map.inverse()['C'] == n0, "Wrong CrossRefMap");
628 628

	
629 629
    ValueIt it = map.beginValue();
630 630
    check(*it++ == 'A' && *it++ == 'B' && *it++ == 'C' &&
631 631
          it == map.endValue(), "Wrong value iterator");
632 632
  }
633 633

	
634 634
  // Iterable bool map
635 635
  {
636 636
    typedef SmartGraph Graph;
637 637
    typedef SmartGraph::Node Item;
638 638

	
639 639
    typedef IterableBoolMap<SmartGraph, SmartGraph::Node> Ibm;
640 640
    checkConcept<ReferenceMap<Item, bool, bool&, const bool&>, Ibm>();
641 641

	
642 642
    const int num = 10;
643 643
    Graph g;
644 644
    Ibm map0(g, true);
645 645
    std::vector<Item> items;
646 646
    for (int i = 0; i < num; ++i) {
647 647
      items.push_back(g.addNode());
648 648
    }
649 649

	
650 650
    Ibm map1(g, true);
651 651
    int n = 0;
652 652
    for (Ibm::TrueIt it(map1); it != INVALID; ++it) {
653 653
      check(map1[static_cast<Item>(it)], "Wrong TrueIt");
654 654
      ++n;
655 655
    }
656 656
    check(n == num, "Wrong number");
657 657

	
658 658
    n = 0;
659 659
    for (Ibm::ItemIt it(map1, true); it != INVALID; ++it) {
660 660
        check(map1[static_cast<Item>(it)], "Wrong ItemIt for true");
661 661
        ++n;
662 662
    }
663 663
    check(n == num, "Wrong number");
664 664
    check(Ibm::FalseIt(map1) == INVALID, "Wrong FalseIt");
665 665
    check(Ibm::ItemIt(map1, false) == INVALID, "Wrong ItemIt for false");
666 666

	
667 667
    map1[items[5]] = true;
668 668

	
669 669
    n = 0;
670 670
    for (Ibm::ItemIt it(map1, true); it != INVALID; ++it) {
671 671
        check(map1[static_cast<Item>(it)], "Wrong ItemIt for true");
672 672
        ++n;
673 673
    }
674 674
    check(n == num, "Wrong number");
675 675

	
676 676
    map1[items[num / 2]] = false;
677 677
    check(map1[items[num / 2]] == false, "Wrong map value");
678 678

	
679 679
    n = 0;
680 680
    for (Ibm::TrueIt it(map1); it != INVALID; ++it) {
681 681
        check(map1[static_cast<Item>(it)], "Wrong TrueIt for true");
682 682
        ++n;
683 683
    }
684 684
    check(n == num - 1, "Wrong number");
685 685

	
686 686
    n = 0;
687 687
    for (Ibm::FalseIt it(map1); it != INVALID; ++it) {
688 688
        check(!map1[static_cast<Item>(it)], "Wrong FalseIt for true");
689 689
        ++n;
690 690
    }
691 691
    check(n == 1, "Wrong number");
692 692

	
693 693
    map1[items[0]] = false;
694 694
    check(map1[items[0]] == false, "Wrong map value");
695 695

	
696 696
    map1[items[num - 1]] = false;
697 697
    check(map1[items[num - 1]] == false, "Wrong map value");
698 698

	
699 699
    n = 0;
700 700
    for (Ibm::TrueIt it(map1); it != INVALID; ++it) {
701 701
        check(map1[static_cast<Item>(it)], "Wrong TrueIt for true");
702 702
        ++n;
703 703
    }
704 704
    check(n == num - 3, "Wrong number");
705 705
    check(map1.trueNum() == num - 3, "Wrong number");
706 706

	
707 707
    n = 0;
708 708
    for (Ibm::FalseIt it(map1); it != INVALID; ++it) {
709 709
        check(!map1[static_cast<Item>(it)], "Wrong FalseIt for true");
710 710
        ++n;
711 711
    }
712 712
    check(n == 3, "Wrong number");
713 713
    check(map1.falseNum() == 3, "Wrong number");
714 714
  }
715 715

	
716 716
  // Iterable int map
717 717
  {
718 718
    typedef SmartGraph Graph;
719 719
    typedef SmartGraph::Node Item;
720 720
    typedef IterableIntMap<SmartGraph, SmartGraph::Node> Iim;
721 721

	
722 722
    checkConcept<ReferenceMap<Item, int, int&, const int&>, Iim>();
723 723

	
724 724
    const int num = 10;
725 725
    Graph g;
726 726
    Iim map0(g, 0);
727 727
    std::vector<Item> items;
728 728
    for (int i = 0; i < num; ++i) {
729 729
      items.push_back(g.addNode());
730 730
    }
731 731

	
732 732
    Iim map1(g);
733 733
    check(map1.size() == 0, "Wrong size");
734 734

	
735 735
    for (int i = 0; i < num; ++i) {
736 736
      map1[items[i]] = i;
737 737
    }
738 738
    check(map1.size() == num, "Wrong size");
739 739

	
740 740
    for (int i = 0; i < num; ++i) {
741 741
      Iim::ItemIt it(map1, i);
742 742
      check(static_cast<Item>(it) == items[i], "Wrong value");
743 743
      ++it;
744 744
      check(static_cast<Item>(it) == INVALID, "Wrong value");
745 745
    }
746 746

	
747 747
    for (int i = 0; i < num; ++i) {
748 748
      map1[items[i]] = i % 2;
749 749
    }
750 750
    check(map1.size() == 2, "Wrong size");
751 751

	
752 752
    int n = 0;
753 753
    for (Iim::ItemIt it(map1, 0); it != INVALID; ++it) {
754 754
      check(map1[static_cast<Item>(it)] == 0, "Wrong value");
755 755
      ++n;
756 756
    }
757 757
    check(n == (num + 1) / 2, "Wrong number");
758 758

	
759 759
    for (Iim::ItemIt it(map1, 1); it != INVALID; ++it) {
760 760
      check(map1[static_cast<Item>(it)] == 1, "Wrong value");
761 761
      ++n;
762 762
    }
763 763
    check(n == num, "Wrong number");
764 764

	
765 765
  }
766 766

	
767 767
  // Iterable value map
768 768
  {
769 769
    typedef SmartGraph Graph;
770 770
    typedef SmartGraph::Node Item;
771 771
    typedef IterableValueMap<SmartGraph, SmartGraph::Node, double> Ivm;
772 772

	
773 773
    checkConcept<ReadWriteMap<Item, double>, Ivm>();
774 774

	
775 775
    const int num = 10;
776 776
    Graph g;
777 777
    Ivm map0(g, 0.0);
778 778
    std::vector<Item> items;
779 779
    for (int i = 0; i < num; ++i) {
780 780
      items.push_back(g.addNode());
781 781
    }
782 782

	
783 783
    Ivm map1(g, 0.0);
784 784
    check(distance(map1.beginValue(), map1.endValue()) == 1, "Wrong size");
785 785
    check(*map1.beginValue() == 0.0, "Wrong value");
786 786

	
787 787
    for (int i = 0; i < num; ++i) {
788 788
      map1.set(items[i], static_cast<double>(i));
789 789
    }
790 790
    check(distance(map1.beginValue(), map1.endValue()) == num, "Wrong size");
791 791

	
792 792
    for (int i = 0; i < num; ++i) {
793 793
      Ivm::ItemIt it(map1, static_cast<double>(i));
794 794
      check(static_cast<Item>(it) == items[i], "Wrong value");
795 795
      ++it;
796 796
      check(static_cast<Item>(it) == INVALID, "Wrong value");
797 797
    }
798 798

	
799 799
    for (Ivm::ValueIt vit = map1.beginValue();
800 800
         vit != map1.endValue(); ++vit) {
801 801
      check(map1[static_cast<Item>(Ivm::ItemIt(map1, *vit))] == *vit,
802 802
            "Wrong ValueIt");
803 803
    }
804 804

	
805 805
    for (int i = 0; i < num; ++i) {
806 806
      map1.set(items[i], static_cast<double>(i % 2));
807 807
    }
808 808
    check(distance(map1.beginValue(), map1.endValue()) == 2, "Wrong size");
809 809

	
810 810
    int n = 0;
811 811
    for (Ivm::ItemIt it(map1, 0.0); it != INVALID; ++it) {
812 812
      check(map1[static_cast<Item>(it)] == 0.0, "Wrong value");
813 813
      ++n;
814 814
    }
815 815
    check(n == (num + 1) / 2, "Wrong number");
816 816

	
817 817
    for (Ivm::ItemIt it(map1, 1.0); it != INVALID; ++it) {
818 818
      check(map1[static_cast<Item>(it)] == 1.0, "Wrong value");
819 819
      ++n;
820 820
    }
821 821
    check(n == num, "Wrong number");
822 822

	
823 823
  }
824 824

	
825 825
  // Graph map utilities:
826 826
  // mapMin(), mapMax(), mapMinValue(), mapMaxValue()
827 827
  // mapFind(), mapFindIf(), mapCount(), mapCountIf()
828 828
  // mapCopy(), mapCompare(), mapFill()
829 829
  {
830 830
    DIGRAPH_TYPEDEFS(SmartDigraph);
831 831

	
832 832
    SmartDigraph g;
833 833
    Node n1 = g.addNode();
834 834
    Node n2 = g.addNode();
835 835
    Node n3 = g.addNode();
836 836

	
837 837
    SmartDigraph::NodeMap<int> map1(g);
838 838
    SmartDigraph::ArcMap<char> map2(g);
839 839
    ConstMap<Node, A> cmap1 = A();
840 840
    ConstMap<Arc, C> cmap2 = C(0);
841 841

	
842 842
    map1[n1] = 10;
843 843
    map1[n2] = 5;
844 844
    map1[n3] = 12;
845 845

	
846 846
    // mapMin(), mapMax(), mapMinValue(), mapMaxValue()
847 847
    check(mapMin(g, map1) == n2, "Wrong mapMin()");
848 848
    check(mapMax(g, map1) == n3, "Wrong mapMax()");
849 849
    check(mapMin(g, map1, std::greater<int>()) == n3, "Wrong mapMin()");
850 850
    check(mapMax(g, map1, std::greater<int>()) == n2, "Wrong mapMax()");
851 851
    check(mapMinValue(g, map1) == 5, "Wrong mapMinValue()");
852 852
    check(mapMaxValue(g, map1) == 12, "Wrong mapMaxValue()");
853 853

	
854 854
    check(mapMin(g, map2) == INVALID, "Wrong mapMin()");
855 855
    check(mapMax(g, map2) == INVALID, "Wrong mapMax()");
856 856

	
857 857
    check(mapMin(g, cmap1) != INVALID, "Wrong mapMin()");
858 858
    check(mapMax(g, cmap2) == INVALID, "Wrong mapMax()");
859 859

	
860 860
    Arc a1 = g.addArc(n1, n2);
861 861
    Arc a2 = g.addArc(n1, n3);
862 862
    Arc a3 = g.addArc(n2, n3);
863 863
    Arc a4 = g.addArc(n3, n1);
864 864

	
865 865
    map2[a1] = 'b';
866 866
    map2[a2] = 'a';
867 867
    map2[a3] = 'b';
868 868
    map2[a4] = 'c';
869 869

	
870 870
    // mapMin(), mapMax(), mapMinValue(), mapMaxValue()
871 871
    check(mapMin(g, map2) == a2, "Wrong mapMin()");
872 872
    check(mapMax(g, map2) == a4, "Wrong mapMax()");
873 873
    check(mapMin(g, map2, std::greater<int>()) == a4, "Wrong mapMin()");
874 874
    check(mapMax(g, map2, std::greater<int>()) == a2, "Wrong mapMax()");
875 875
    check(mapMinValue(g, map2, std::greater<int>()) == 'c',
876 876
          "Wrong mapMinValue()");
877 877
    check(mapMaxValue(g, map2, std::greater<int>()) == 'a',
878 878
          "Wrong mapMaxValue()");
879 879

	
880 880
    check(mapMin(g, cmap1) != INVALID, "Wrong mapMin()");
881 881
    check(mapMax(g, cmap2) != INVALID, "Wrong mapMax()");
882 882
    check(mapMaxValue(g, cmap2) == C(0), "Wrong mapMaxValue()");
883 883

	
884 884
    check(mapMin(g, composeMap(functorToMap(&createC), map2)) == a2,
885 885
          "Wrong mapMin()");
886 886
    check(mapMax(g, composeMap(functorToMap(&createC), map2)) == a4,
887 887
          "Wrong mapMax()");
888 888
    check(mapMinValue(g, composeMap(functorToMap(&createC), map2)) == C('a'),
889 889
          "Wrong mapMinValue()");
890 890
    check(mapMaxValue(g, composeMap(functorToMap(&createC), map2)) == C('c'),
891 891
          "Wrong mapMaxValue()");
892 892

	
893 893
    // mapFind(), mapFindIf()
894 894
    check(mapFind(g, map1, 5) == n2, "Wrong mapFind()");
895 895
    check(mapFind(g, map1, 6) == INVALID, "Wrong mapFind()");
896 896
    check(mapFind(g, map2, 'a') == a2, "Wrong mapFind()");
897 897
    check(mapFind(g, map2, 'e') == INVALID, "Wrong mapFind()");
898 898
    check(mapFind(g, cmap2, C(0)) == ArcIt(g), "Wrong mapFind()");
899 899
    check(mapFind(g, cmap2, C(1)) == INVALID, "Wrong mapFind()");
900 900

	
901 901
    check(mapFindIf(g, map1, Less<int>(7)) == n2,
902 902
          "Wrong mapFindIf()");
903 903
    check(mapFindIf(g, map1, Less<int>(5)) == INVALID,
904 904
          "Wrong mapFindIf()");
905 905
    check(mapFindIf(g, map2, Less<char>('d')) == ArcIt(g),
906 906
          "Wrong mapFindIf()");
907 907
    check(mapFindIf(g, map2, Less<char>('a')) == INVALID,
908 908
          "Wrong mapFindIf()");
909 909

	
910 910
    // mapCount(), mapCountIf()
911 911
    check(mapCount(g, map1, 5) == 1, "Wrong mapCount()");
912 912
    check(mapCount(g, map1, 6) == 0, "Wrong mapCount()");
913 913
    check(mapCount(g, map2, 'a') == 1, "Wrong mapCount()");
914 914
    check(mapCount(g, map2, 'b') == 2, "Wrong mapCount()");
915 915
    check(mapCount(g, map2, 'e') == 0, "Wrong mapCount()");
916 916
    check(mapCount(g, cmap2, C(0)) == 4, "Wrong mapCount()");
917 917
    check(mapCount(g, cmap2, C(1)) == 0, "Wrong mapCount()");
918 918

	
919 919
    check(mapCountIf(g, map1, Less<int>(11)) == 2,
920 920
          "Wrong mapCountIf()");
921 921
    check(mapCountIf(g, map1, Less<int>(13)) == 3,
922 922
          "Wrong mapCountIf()");
923 923
    check(mapCountIf(g, map1, Less<int>(5)) == 0,
924 924
          "Wrong mapCountIf()");
925 925
    check(mapCountIf(g, map2, Less<char>('d')) == 4,
926 926
          "Wrong mapCountIf()");
927 927
    check(mapCountIf(g, map2, Less<char>('c')) == 3,
928 928
          "Wrong mapCountIf()");
929 929
    check(mapCountIf(g, map2, Less<char>('a')) == 0,
930 930
          "Wrong mapCountIf()");
931 931

	
932 932
    // MapIt, ConstMapIt
933 933
/*
934 934
These tests can be used after applying bugfix #330
935 935
    typedef SmartDigraph::NodeMap<int>::MapIt MapIt;
936 936
    typedef SmartDigraph::NodeMap<int>::ConstMapIt ConstMapIt;
937 937
    check(*std::min_element(MapIt(map1), MapIt(INVALID)) == 5,
938 938
          "Wrong NodeMap<>::MapIt");
939 939
    check(*std::max_element(ConstMapIt(map1), ConstMapIt(INVALID)) == 12,
940 940
          "Wrong NodeMap<>::MapIt");
941 941

	
942 942
    int sum = 0;
943 943
    std::for_each(MapIt(map1), MapIt(INVALID), Sum<int>(sum));
944 944
    check(sum == 27, "Wrong NodeMap<>::MapIt");
945 945
    std::for_each(ConstMapIt(map1), ConstMapIt(INVALID), Sum<int>(sum));
946 946
    check(sum == 54, "Wrong NodeMap<>::ConstMapIt");
947 947
*/
948 948

	
949 949
    // mapCopy(), mapCompare(), mapFill()
950 950
    check(mapCompare(g, map1, map1), "Wrong mapCompare()");
951 951
    check(mapCompare(g, cmap2, cmap2), "Wrong mapCompare()");
952 952
    check(mapCompare(g, map1, shiftMap(map1, 0)), "Wrong mapCompare()");
953 953
    check(mapCompare(g, map2, scaleMap(map2, 1)), "Wrong mapCompare()");
954 954
    check(!mapCompare(g, map1, shiftMap(map1, 1)), "Wrong mapCompare()");
955 955

	
956 956
    SmartDigraph::NodeMap<int> map3(g, 0);
957 957
    SmartDigraph::ArcMap<char> map4(g, 'a');
958 958

	
959 959
    check(!mapCompare(g, map1, map3), "Wrong mapCompare()");
960 960
    check(!mapCompare(g, map2, map4), "Wrong mapCompare()");
961 961

	
962 962
    mapCopy(g, map1, map3);
963 963
    mapCopy(g, map2, map4);
964 964

	
965 965
    check(mapCompare(g, map1, map3), "Wrong mapCompare() or mapCopy()");
966 966
    check(mapCompare(g, map2, map4), "Wrong mapCompare() or mapCopy()");
967 967

	
968 968
    Undirector<SmartDigraph> ug(g);
969 969
    Undirector<SmartDigraph>::EdgeMap<char> umap1(ug, 'x');
970 970
    Undirector<SmartDigraph>::ArcMap<double> umap2(ug, 3.14);
971 971

	
972 972
    check(!mapCompare(g, map2, umap1), "Wrong mapCompare() or mapCopy()");
973 973
    check(!mapCompare(g, umap1, map2), "Wrong mapCompare() or mapCopy()");
974 974
    check(!mapCompare(ug, map2, umap1), "Wrong mapCompare() or mapCopy()");
975 975
    check(!mapCompare(ug, umap1, map2), "Wrong mapCompare() or mapCopy()");
976 976

	
977 977
    mapCopy(g, map2, umap1);
978 978

	
979 979
    check(mapCompare(g, map2, umap1), "Wrong mapCompare() or mapCopy()");
980 980
    check(mapCompare(g, umap1, map2), "Wrong mapCompare() or mapCopy()");
981 981
    check(mapCompare(ug, map2, umap1), "Wrong mapCompare() or mapCopy()");
982 982
    check(mapCompare(ug, umap1, map2), "Wrong mapCompare() or mapCopy()");
983 983

	
984 984
    mapCopy(g, map2, umap1);
985 985
    mapCopy(g, umap1, map2);
986 986
    mapCopy(ug, map2, umap1);
987 987
    mapCopy(ug, umap1, map2);
988 988

	
989 989
    check(!mapCompare(ug, umap1, umap2), "Wrong mapCompare() or mapCopy()");
990 990
    mapCopy(ug, umap1, umap2);
991 991
    check(mapCompare(ug, umap1, umap2), "Wrong mapCompare() or mapCopy()");
992 992

	
993 993
    check(!mapCompare(g, map1, constMap<Node>(2)), "Wrong mapCompare()");
994 994
    mapFill(g, map1, 2);
995 995
    check(mapCompare(g, constMap<Node>(2), map1), "Wrong mapFill()");
996 996

	
997 997
    check(!mapCompare(g, map2, constMap<Arc>('z')), "Wrong mapCompare()");
998 998
    mapCopy(g, constMap<Arc>('z'), map2);
999 999
    check(mapCompare(g, constMap<Arc>('z'), map2), "Wrong mapCopy()");
1000 1000
  }
1001 1001

	
1002 1002
  return 0;
1003 1003
}
Show white space 4096 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
 * Copyright (C) 2003-2010
5
 * Copyright (C) 2003-2011
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 <iostream>
20 20

	
21 21
#include "test_tools.h"
22 22
#include <lemon/smart_graph.h>
23 23
#include <lemon/preflow.h>
24 24
#include <lemon/concepts/digraph.h>
25 25
#include <lemon/concepts/maps.h>
26 26
#include <lemon/lgf_reader.h>
27 27
#include <lemon/elevator.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
  "5\n"
40 40
  "6\n"
41 41
  "7\n"
42 42
  "8\n"
43 43
  "9\n"
44 44
  "@arcs\n"
45 45
  "    label capacity\n"
46 46
  "0 1 0     20\n"
47 47
  "0 2 1     0\n"
48 48
  "1 1 2     3\n"
49 49
  "1 2 3     8\n"
50 50
  "1 3 4     8\n"
51 51
  "2 5 5     5\n"
52 52
  "3 2 6     5\n"
53 53
  "3 5 7     5\n"
54 54
  "3 6 8     5\n"
55 55
  "4 3 9     3\n"
56 56
  "5 7 10    3\n"
57 57
  "5 6 11    10\n"
58 58
  "5 8 12    10\n"
59 59
  "6 8 13    8\n"
60 60
  "8 9 14    20\n"
61 61
  "8 1 15    5\n"
62 62
  "9 5 16    5\n"
63 63
  "@attributes\n"
64 64
  "source 1\n"
65 65
  "target 8\n";
66 66

	
67 67
void checkPreflowCompile()
68 68
{
69 69
  typedef int VType;
70 70
  typedef concepts::Digraph Digraph;
71 71

	
72 72
  typedef Digraph::Node Node;
73 73
  typedef Digraph::Arc Arc;
74 74
  typedef concepts::ReadMap<Arc,VType> CapMap;
75 75
  typedef concepts::ReadWriteMap<Arc,VType> FlowMap;
76 76
  typedef concepts::WriteMap<Node,bool> CutMap;
77 77

	
78 78
  typedef Elevator<Digraph, Digraph::Node> Elev;
79 79
  typedef LinkedElevator<Digraph, Digraph::Node> LinkedElev;
80 80

	
81 81
  Digraph g;
82 82
  Node n;
83 83
  Arc e;
84 84
  CapMap cap;
85 85
  FlowMap flow;
86 86
  CutMap cut;
87 87
  VType v;
88 88
  bool b;
89 89

	
90 90
  typedef Preflow<Digraph, CapMap>
91 91
            ::SetFlowMap<FlowMap>
92 92
            ::SetElevator<Elev>
93 93
            ::SetStandardElevator<LinkedElev>
94 94
            ::Create PreflowType;
95 95
  PreflowType preflow_test(g, cap, n, n);
96 96
  const PreflowType& const_preflow_test = preflow_test;
97 97

	
98 98
  const PreflowType::Elevator& elev = const_preflow_test.elevator();
99 99
  preflow_test.elevator(const_cast<PreflowType::Elevator&>(elev));
100 100
  PreflowType::Tolerance tol = const_preflow_test.tolerance();
101 101
  preflow_test.tolerance(tol);
102 102

	
103 103
  preflow_test
104 104
    .capacityMap(cap)
105 105
    .flowMap(flow)
106 106
    .source(n)
107 107
    .target(n);
108 108

	
109 109
  preflow_test.init();
110 110
  preflow_test.init(cap);
111 111
  preflow_test.startFirstPhase();
112 112
  preflow_test.startSecondPhase();
113 113
  preflow_test.run();
114 114
  preflow_test.runMinCut();
115 115

	
116 116
  v = const_preflow_test.flowValue();
117 117
  v = const_preflow_test.flow(e);
118 118
  const FlowMap& fm = const_preflow_test.flowMap();
119 119
  b = const_preflow_test.minCut(n);
120 120
  const_preflow_test.minCutMap(cut);
121 121

	
122 122
  ignore_unused_variable_warning(fm);
123 123
}
124 124

	
125 125
int cutValue (const SmartDigraph& g,
126 126
              const SmartDigraph::NodeMap<bool>& cut,
127 127
              const SmartDigraph::ArcMap<int>& cap) {
128 128

	
129 129
  int c=0;
130 130
  for(SmartDigraph::ArcIt e(g); e!=INVALID; ++e) {
131 131
    if (cut[g.source(e)] && !cut[g.target(e)]) c+=cap[e];
132 132
  }
133 133
  return c;
134 134
}
135 135

	
136 136
bool checkFlow(const SmartDigraph& g,
137 137
               const SmartDigraph::ArcMap<int>& flow,
138 138
               const SmartDigraph::ArcMap<int>& cap,
139 139
               SmartDigraph::Node s, SmartDigraph::Node t) {
140 140

	
141 141
  for (SmartDigraph::ArcIt e(g); e != INVALID; ++e) {
142 142
    if (flow[e] < 0 || flow[e] > cap[e]) return false;
143 143
  }
144 144

	
145 145
  for (SmartDigraph::NodeIt n(g); n != INVALID; ++n) {
146 146
    if (n == s || n == t) continue;
147 147
    int sum = 0;
148 148
    for (SmartDigraph::OutArcIt e(g, n); e != INVALID; ++e) {
149 149
      sum += flow[e];
150 150
    }
151 151
    for (SmartDigraph::InArcIt e(g, n); e != INVALID; ++e) {
152 152
      sum -= flow[e];
153 153
    }
154 154
    if (sum != 0) return false;
155 155
  }
156 156
  return true;
157 157
}
158 158

	
159 159
void initFlowTest()
160 160
{
161 161
  DIGRAPH_TYPEDEFS(SmartDigraph);
162 162
  
163 163
  SmartDigraph g;
164 164
  SmartDigraph::ArcMap<int> cap(g),iflow(g);
165 165
  Node s=g.addNode(); Node t=g.addNode();
166 166
  Node n1=g.addNode(); Node n2=g.addNode();
167 167
  Arc a;
168 168
  a=g.addArc(s,n1); cap[a]=20; iflow[a]=20;
169 169
  a=g.addArc(n1,n2); cap[a]=10; iflow[a]=0;
170 170
  a=g.addArc(n2,t); cap[a]=20; iflow[a]=0;
171 171

	
172 172
  Preflow<SmartDigraph> pre(g,cap,s,t);
173 173
  pre.init(iflow);
174 174
  pre.startFirstPhase();
175 175
  check(pre.flowValue() == 10, "The incorrect max flow value.");
176 176
  check(pre.minCut(s), "Wrong min cut (Node s).");
177 177
  check(pre.minCut(n1), "Wrong min cut (Node n1).");
178 178
  check(!pre.minCut(n2), "Wrong min cut (Node n2).");
179 179
  check(!pre.minCut(t), "Wrong min cut (Node t).");
180 180
}
181 181

	
182 182

	
183 183
int main() {
184 184

	
185 185
  typedef SmartDigraph Digraph;
186 186

	
187 187
  typedef Digraph::Node Node;
188 188
  typedef Digraph::NodeIt NodeIt;
189 189
  typedef Digraph::ArcIt ArcIt;
190 190
  typedef Digraph::ArcMap<int> CapMap;
191 191
  typedef Digraph::ArcMap<int> FlowMap;
192 192
  typedef Digraph::NodeMap<bool> CutMap;
193 193

	
194 194
  typedef Preflow<Digraph, CapMap> PType;
195 195

	
196 196
  Digraph g;
197 197
  Node s, t;
198 198
  CapMap cap(g);
199 199
  std::istringstream input(test_lgf);
200 200
  DigraphReader<Digraph>(g,input).
201 201
    arcMap("capacity", cap).
202 202
    node("source",s).
203 203
    node("target",t).
204 204
    run();
205 205

	
206 206
  PType preflow_test(g, cap, s, t);
207 207
  preflow_test.run();
208 208

	
209 209
  check(checkFlow(g, preflow_test.flowMap(), cap, s, t),
210 210
        "The flow is not feasible.");
211 211

	
212 212
  CutMap min_cut(g);
213 213
  preflow_test.minCutMap(min_cut);
214 214
  int min_cut_value=cutValue(g,min_cut,cap);
215 215

	
216 216
  check(preflow_test.flowValue() == min_cut_value,
217 217
        "The max flow value is not equal to the three min cut values.");
218 218

	
219 219
  FlowMap flow(g);
220 220
  for(ArcIt e(g); e!=INVALID; ++e) flow[e] = preflow_test.flowMap()[e];
221 221

	
222 222
  int flow_value=preflow_test.flowValue();
223 223

	
224 224
  for(ArcIt e(g); e!=INVALID; ++e) cap[e]=2*cap[e];
225 225
  preflow_test.init(flow);
226 226
  preflow_test.startFirstPhase();
227 227

	
228 228
  CutMap min_cut1(g);
229 229
  preflow_test.minCutMap(min_cut1);
230 230
  min_cut_value=cutValue(g,min_cut1,cap);
231 231

	
232 232
  check(preflow_test.flowValue() == min_cut_value &&
233 233
        min_cut_value == 2*flow_value,
234 234
        "The max flow value or the min cut value is wrong.");
235 235

	
236 236
  preflow_test.startSecondPhase();
237 237

	
238 238
  check(checkFlow(g, preflow_test.flowMap(), cap, s, t),
239 239
        "The flow is not feasible.");
240 240

	
241 241
  CutMap min_cut2(g);
242 242
  preflow_test.minCutMap(min_cut2);
243 243
  min_cut_value=cutValue(g,min_cut2,cap);
244 244

	
245 245
  check(preflow_test.flowValue() == min_cut_value &&
246 246
        min_cut_value == 2*flow_value,
247 247
        "The max flow value or the three min cut values were not doubled");
248 248

	
249 249

	
250 250
  preflow_test.flowMap(flow);
251 251

	
252 252
  NodeIt tmp1(g,s);
253 253
  ++tmp1;
254 254
  if ( tmp1 != INVALID ) s=tmp1;
255 255

	
256 256
  NodeIt tmp2(g,t);
257 257
  ++tmp2;
258 258
  if ( tmp2 != INVALID ) t=tmp2;
259 259

	
260 260
  preflow_test.source(s);
261 261
  preflow_test.target(t);
262 262

	
263 263
  preflow_test.run();
264 264

	
265 265
  CutMap min_cut3(g);
266 266
  preflow_test.minCutMap(min_cut3);
267 267
  min_cut_value=cutValue(g,min_cut3,cap);
268 268

	
269 269

	
270 270
  check(preflow_test.flowValue() == min_cut_value,
271 271
        "The max flow value or the three min cut values are incorrect.");
272 272

	
273 273
  initFlowTest();
274 274
  
275 275
  return 0;
276 276
}
0 comments (0 inline)