graph_adjacency.hh 32.1 KB
Newer Older
1
2
// graph-tool -- a general graph modification and manipulation thingy
//
Tiago Peixoto's avatar
Tiago Peixoto committed
3
// Copyright (C) 2006-2016 Tiago de Paula Peixoto <tiago@skewed.de>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

18
19
20
21
22
23
24
25
#ifndef GRAPH_ADJACENCY_HH
#define GRAPH_ADJACENCY_HH

#include <vector>
#include <deque>
#include <utility>
#include <numeric>
#include <iostream>
Tiago Peixoto's avatar
Tiago Peixoto committed
26
#include <tuple>
27
#include <functional>
28
29
30
31
32
33
34
35
#include <boost/iterator.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/range/irange.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/properties.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/iterator_facade.hpp>

36
37
#include "transform_iterator.hh"

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
namespace boost
{

// ========================================================================
// Forward declarations
// ========================================================================

template <class Vertex>
class adj_list;

// forward declaration of manipulation functions
template <class Vertex>
std::pair<typename adj_list<Vertex>::vertex_iterator,
          typename adj_list<Vertex>::vertex_iterator>
vertices(const adj_list<Vertex>& g);

template <class Vertex>
std::pair<typename adj_list<Vertex>::edge_iterator,
          typename adj_list<Vertex>::edge_iterator>
edges(const adj_list<Vertex>& g);

template <class Vertex>
60
std::pair<typename adj_list<Vertex>::edge_descriptor, bool>
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
edge(Vertex s, Vertex t, const adj_list<Vertex>& g);

template <class Vertex>
size_t out_degree(Vertex v, const adj_list<Vertex>& g);

template <class Vertex>
size_t in_degree(Vertex v, const adj_list<Vertex>& g);

template <class Vertex>
std::pair<typename adj_list<Vertex>::out_edge_iterator,
          typename adj_list<Vertex>::out_edge_iterator>
out_edges(Vertex v, const adj_list<Vertex>& g);

template <class Vertex>
std::pair<typename adj_list<Vertex>::in_edge_iterator,
          typename adj_list<Vertex>::in_edge_iterator>
in_edges(Vertex v, const adj_list<Vertex>& g);

template <class Vertex>
std::pair<typename adj_list<Vertex>::adjacency_iterator,
          typename adj_list<Vertex>::adjacency_iterator>
adjacent_vertices(Vertex v, const adj_list<Vertex>& g);

84
85
86
87
88
89
90
91
92
93
template <class Vertex>
std::pair<typename adj_list<Vertex>::adjacency_iterator,
          typename adj_list<Vertex>::adjacency_iterator>
out_neighbours(Vertex v, const adj_list<Vertex>& g);

template <class Vertex>
std::pair<typename adj_list<Vertex>::adjacency_iterator,
          typename adj_list<Vertex>::adjacency_iterator>
in_neighbours(Vertex v, const adj_list<Vertex>& g);

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
template <class Vertex>
size_t num_vertices(const adj_list<Vertex>& g);

template <class Vertex>
size_t num_edges(const adj_list<Vertex>& g);

template <class Vertex>
Vertex add_vertex(adj_list<Vertex>& g);

template <class Vertex>
void clear_vertex(Vertex v, adj_list<Vertex>& g);

template <class Vertex>
void remove_vertex(Vertex v, adj_list<Vertex>& g);

109
110
111
template <class Vertex>
void remove_vertex_fast(Vertex v, adj_list<Vertex>& g);

112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
template <class Vertex>
std::pair<typename adj_list<Vertex>::edge_descriptor, bool>
add_edge(Vertex s, Vertex t, adj_list<Vertex>& g);

template <class Vertex>
void remove_edge(Vertex s, Vertex t, adj_list<Vertex>& g);

template <class Vertex>
void remove_edge(const typename adj_list<Vertex>::edge_descriptor& e,
                 adj_list<Vertex>& g);

// ========================================================================
// adj_list<Vertex>
// ========================================================================
//
// adj_list is a very simple adjacency list implementation for bidirectional
// graphs based on std::vector, meant to be reasonably efficient both
// memory-wise and computationally. It maintains a list of in and out-edges for
// each vertex, and each edge has a built-in index (which is replicated in both
// lists). For each edge, a total of 4 integers is necessary: the source and
// target vertices, in the in_edges and out_edges lists, respectively, and the
// (same) edge index in both lists. The integer type is given by the Vertex
// template parameter. It achieves about half as much memory as
// boost::adjacency_list with an edge index property map and the same integer
// type.

// The complexity guarantees and iterator invalidation rules are the same as
// boost::adjacency_list with vector storage selectors for both vertex and edge
// lists.

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
namespace detail
{
template <class Vertex>
struct adj_edge_descriptor
{
    adj_edge_descriptor()
        : s(std::numeric_limits<Vertex>::max()),
          t(std::numeric_limits<Vertex>::max()),
          idx(std::numeric_limits<Vertex>::max()), inv(false) {};
    adj_edge_descriptor(Vertex s, Vertex t, Vertex idx, bool inv)
        : s(s), t(t), idx(idx), inv(inv) {}

    bool operator==(const adj_edge_descriptor& other) const
    {
        return idx == other.idx;
    }
    bool operator!=(const adj_edge_descriptor& other) const
    {
        return idx != other.idx;
    }
    bool operator<(const adj_edge_descriptor& other) const
    {
        return idx < other.idx;
    }

    Vertex s, t, idx;
    bool inv;
};
} // namespace detail

172
173
174
175
176
177
template <class Vertex = size_t>
class adj_list
{
public:
    struct graph_tag {};
    typedef Vertex vertex_t;
178

179
    typedef detail::adj_edge_descriptor<Vertex> edge_descriptor;
180

181
    typedef std::vector<std::pair<vertex_t, vertex_t> > edge_list_t;
182
    typedef std::vector<edge_list_t> vertex_list_t;
183
184
    typedef typename integer_range<Vertex>::iterator vertex_iterator;

185
    adj_list(): _n_edges(0), _edge_index_range(0), _keep_epos(false) {}
186

187
188
189
190
    struct get_vertex
    {
        get_vertex() {}
        typedef Vertex result_type;
191
        __attribute__((always_inline))
192
193
194
195
        Vertex operator()(const std::pair<vertex_t, vertex_t>& v) const
        { return v.first; }
    };

196
197
    typedef transform_random_access_iterator<get_vertex,
                                             typename edge_list_t::const_iterator>
198
199
        adjacency_iterator;

200
    typedef adjacency_iterator in_adjacency_iterator;
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

    template <class Deference>
    struct base_edge_iterator:
        public boost::iterator_facade<base_edge_iterator<Deference>,
                                      edge_descriptor,
                                      std::random_access_iterator_tag,
                                      edge_descriptor>
    {
        base_edge_iterator() {}
        base_edge_iterator(vertex_t v, typename edge_list_t::const_iterator&& iter)
            : _v(v), _iter(std::forward<typename edge_list_t::const_iterator>(iter))
        {}

    private:
        friend class boost::iterator_core_access;
        void increment() { ++_iter; }
        void decrement() { --_iter; }
Tiago Peixoto's avatar
Tiago Peixoto committed
218
219
        template <class Distance>
        void advance(Distance n) { _iter += n; }
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
        auto distance_to(base_edge_iterator const& other) const
        {
            return other._iter - _iter;
        }

        bool equal(base_edge_iterator const& other) const
        {
            return _iter == other._iter;
        }

        edge_descriptor dereference() const
        {
            return Deference::def(_v, *_iter);
        }

        vertex_t _v;
        typename edge_list_t::const_iterator _iter;
    };

239
240
    struct make_out_edge
    {
241
242
243
        static edge_descriptor def(vertex_t src,
                                   const std::pair<vertex_t, vertex_t>& v)
        { return edge_descriptor(src, v.first, v.second, false); }
244
245
246
247
    };

    struct make_in_edge
    {
248
249
250
        static edge_descriptor def(vertex_t tgt,
                                   const std::pair<vertex_t, vertex_t>& v)
        { return edge_descriptor(v.first, tgt, v.second, false); }
251
252
    };

253
254
    typedef base_edge_iterator<make_out_edge> out_edge_iterator;
    typedef base_edge_iterator<make_in_edge> in_edge_iterator;
255
256
257
258
259
260
261
262
263

    class edge_iterator:
        public boost::iterator_facade<edge_iterator,
                                      edge_descriptor,
                                      boost::forward_traversal_tag,
                                      edge_descriptor>
    {
    public:
        edge_iterator() {}
264
265
266
        explicit edge_iterator(const typename vertex_list_t::const_iterator& vi_begin,
                               const typename vertex_list_t::const_iterator& vi_end,
                               const typename vertex_list_t::const_iterator& vi,
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
                               const typename edge_list_t::const_iterator& ei)
            : _vi_begin(vi_begin), _vi_end(vi_end), _vi(vi), _ei(ei)
        {
            // move position to first edge
            skip();
        }

    private:
        friend class boost::iterator_core_access;

        void skip()
        {
            //skip empty vertices
            while (_vi != _vi_end && _ei == _vi->end())
            {
                ++_vi;
                if (_vi != _vi_end)
                    _ei = _vi->begin();
            }
        }

        void increment()
        {
            ++_ei;
            skip();
        }

        bool equal(edge_iterator const& other) const
        {
            if (_vi_begin == _vi_end)
                return _vi == other._vi;
            return _vi == other._vi && _ei == other._ei;
        }

        edge_descriptor dereference() const
        {
303
            return edge_descriptor(vertex_t(_vi - _vi_begin),
304
                                   _ei->first, _ei->second, false);
305
306
        }

307
308
309
        typename vertex_list_t::const_iterator _vi_begin;
        typename vertex_list_t::const_iterator _vi_end;
        typename vertex_list_t::const_iterator _vi;
310
311
312
313
314
315
        typename edge_list_t::const_iterator _ei;
    };

    void reindex_edges()
    {
        _free_indexes.clear();
316
        _edge_index_range = 0;
317
318
319
        _in_edges.clear();
        _in_edges.resize(_out_edges.size());
        for (size_t i = 0; i < _out_edges.size(); ++i)
320
321
        {
            auto& oes = _out_edges[i];
322
            for (size_t j = 0; j < oes.size(); ++j)
323
            {
324
                auto& oe = oes[j];
325
                Vertex v = oe.first;
326
327
328
                oe.second = _edge_index_range;
                _in_edges[v].emplace_back(i, _edge_index_range);
                _edge_index_range++;
329
            }
330
        }
331
332
333
334
335
336
337
338
339

        if (_keep_epos)
            rebuild_epos();
    }

    void set_keep_epos(bool keep)
    {
        if (keep)
        {
Tiago Peixoto's avatar
Tiago Peixoto committed
340
            if (!_keep_epos)
341
342
343
344
345
346
347
348
349
350
351
352
                rebuild_epos();
        }
        else
        {
            _epos.clear();
        }
        _keep_epos = keep;
    }

    bool get_keep_epos()
    {
        return _keep_epos;
353
354
    }

355
    size_t get_edge_index_range() const { return _edge_index_range; }
356

357
358
    static Vertex null_vertex() { return std::numeric_limits<Vertex>::max(); }

359
360
361
362
363
364
365
366
367
368
369
370
371
    void shrink_to_fit()
    {
        _in_edges.shrink_to_fit();
        _out_edges.shrink_to_fit();
        std::for_each(_in_edges.begin(), _in_edges.end(),
                      [](auto &es){es.shrink_to_fit();});
        std::for_each(_out_edges.begin(), _out_edges.end(),
                      [](auto &es){es.shrink_to_fit();});
        auto erange = boost::edges(*this);
        auto iter = std::max_element(erange.first, erange.second,
                                     [](const auto &a, const auto& b) -> bool
                                     {return a.idx < b.idx;});
        if (iter == erange.second)
372
            _edge_index_range = 0;
373
        else
374
            _edge_index_range = iter->idx + 1;
375
376
377
        auto iter_idx = std::remove_if(_free_indexes.begin(),
                                       _free_indexes.end(),
                                       [&](auto idx) -> bool
378
                                       {return idx > _edge_index_range;});
379
380
381
        _free_indexes.erase(iter_idx, _free_indexes.end());
        _free_indexes.shrink_to_fit();
        if (_keep_epos)
382
            _epos.resize(_edge_index_range);
383
384
385
        _epos.shrink_to_fit();
    }

386
387
388
389
private:
    vertex_list_t _out_edges;
    vertex_list_t _in_edges;
    size_t _n_edges;
390
    size_t _edge_index_range;
391
392
393
394
    std::deque<size_t> _free_indexes; // indexes of deleted edges to be used up
                                      // for new edges to avoid very large
                                      // indexes, and unnecessary property map
                                      // memory use
395
    bool _keep_epos;
396
    std::vector<std::pair<int32_t, int32_t>> _epos;
397
398
399

    void rebuild_epos()
    {
400
        _epos.resize(_edge_index_range);
401
402
        for (size_t i = 0; i < _out_edges.size(); ++i)
        {
403
404
            auto& oes = _out_edges[i];
            for (size_t j = 0; j < oes.size(); ++j)
405
            {
406
                size_t idx = oes[j].second;
407
408
409
                _epos[idx].first = j;
            }

410
411
            auto& ies = _in_edges[i];
            for (size_t j = 0; j < ies.size(); ++j)
412
413
414
415
416
417
            {
                size_t idx = _in_edges[i][j].second;
                _epos[idx].second = j;
            }
        }
    }
418
419
420
421
422
423
424
425

    // manipulation functions
    friend std::pair<vertex_iterator, vertex_iterator>
    vertices<>(const adj_list<Vertex>& g);

    friend std::pair<edge_iterator, edge_iterator>
    edges<>(const adj_list<Vertex>& g);

426
    friend std::pair<edge_descriptor, bool>
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    edge<>(Vertex s, Vertex t, const adj_list<Vertex>& g);

    friend size_t out_degree<>(Vertex v, const adj_list<Vertex>& g);

    friend size_t in_degree<>(Vertex v, const adj_list<Vertex>& g);

    friend std::pair<out_edge_iterator, out_edge_iterator>
    out_edges<>(Vertex v, const adj_list<Vertex>& g);

    friend std::pair<in_edge_iterator, in_edge_iterator>
    in_edges<>(Vertex v, const adj_list<Vertex>& g);

    friend std::pair<adjacency_iterator, adjacency_iterator>
    adjacent_vertices<>(Vertex v, const adj_list<Vertex>& g);

442
443
444
445
446
447
    friend std::pair<adjacency_iterator, adjacency_iterator>
    out_neighbours<>(Vertex v, const adj_list<Vertex>& g);

    friend std::pair<adjacency_iterator, adjacency_iterator>
    in_neighbours<>(Vertex v, const adj_list<Vertex>& g);

448
449
450
451
452
453
454
455
456
457
    friend size_t num_vertices<>(const adj_list<Vertex>& g);

    friend size_t num_edges<>(const adj_list<Vertex>& g);

    friend Vertex add_vertex<>(adj_list<Vertex>& g);

    friend void clear_vertex<>(Vertex v, adj_list<Vertex>& g);

    friend void remove_vertex<>(Vertex v, adj_list<Vertex>& g);

458
459
    friend void remove_vertex_fast<>(Vertex v, adj_list<Vertex>& g);

460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
    friend std::pair<edge_descriptor, bool>
    add_edge<>(Vertex s, Vertex t, adj_list<Vertex>& g);

    friend void remove_edge<>(Vertex s, Vertex t, adj_list<Vertex>& g);

    friend void remove_edge<>(const edge_descriptor& e, adj_list<Vertex>& g);
};

//========================================================================
// Graph traits and BGL scaffolding
//========================================================================

struct adj_list_traversal_tag
    : public vertex_list_graph_tag,
      public edge_list_graph_tag,
      public adjacency_graph_tag,
476
477
      public bidirectional_graph_tag,
      public adjacency_matrix_tag {};
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499

template <class Vertex>
struct graph_traits<adj_list<Vertex> >
{
    typedef Vertex vertex_descriptor;
    typedef typename adj_list<Vertex>::edge_descriptor edge_descriptor;
    typedef typename adj_list<Vertex>::edge_iterator edge_iterator;
    typedef typename adj_list<Vertex>::adjacency_iterator adjacency_iterator;

    typedef typename adj_list<Vertex>::out_edge_iterator out_edge_iterator;
    typedef typename adj_list<Vertex>::in_edge_iterator in_edge_iterator;

    typedef typename adj_list<Vertex>::vertex_iterator vertex_iterator;

    typedef bidirectional_tag directed_category;
    typedef allow_parallel_edge_tag edge_parallel_category;
    typedef adj_list_traversal_tag traversal_category;

    typedef Vertex vertices_size_type;
    typedef Vertex edges_size_type;
    typedef size_t degree_size_type;

500
    static Vertex null_vertex() { return adj_list<Vertex>::null_vertex(); }
501

502
503
504
505
506
507
508
private:
    BOOST_STATIC_ASSERT((is_convertible<typename std::iterator_traits<out_edge_iterator>::iterator_category,
                                        std::random_access_iterator_tag>::value));
    BOOST_STATIC_ASSERT((is_convertible<typename std::iterator_traits<in_edge_iterator>::iterator_category,
                                        std::random_access_iterator_tag>::value));
    BOOST_STATIC_ASSERT((is_convertible<typename std::iterator_traits<adjacency_iterator>::iterator_category,
                                        std::random_access_iterator_tag>::value));
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
};

template <class Vertex>
struct graph_traits<const adj_list<Vertex> >
    : public graph_traits<adj_list<Vertex> >
{
};


template <class Vertex>
struct edge_property_type<adj_list<Vertex> >
{
    typedef void type;
};

template <class Vertex>
struct vertex_property_type<adj_list<Vertex> >
{
    typedef void type;
};

template <class Vertex>
struct graph_property_type<adj_list<Vertex> >
{
    typedef void type;
};

//========================================================================
// Graph access and manipulation functions
//========================================================================

template <class Vertex>
541
inline __attribute__((always_inline))
542
543
std::pair<typename adj_list<Vertex>::vertex_iterator,
          typename adj_list<Vertex>::vertex_iterator>
544
545
546
547
548
549
550
551
vertices(const adj_list<Vertex>& g)
{
    typedef typename adj_list<Vertex>::vertex_iterator vi_t;
    return std::make_pair(vi_t(0), vi_t(g._out_edges.size()));
}


template <class Vertex>
552
inline
553
554
std::pair<typename adj_list<Vertex>::edge_iterator,
          typename adj_list<Vertex>::edge_iterator>
555
556
557
558
edges(const adj_list<Vertex>& g)
{
    typedef typename adj_list<Vertex>::edge_list_t::const_iterator ei_t;
    typedef typename adj_list<Vertex>::vertex_list_t::const_iterator vi_t;
559
560
561
562
563
564
565
566
567
568
569
570
    ei_t ei_begin, ei_end;
    vi_t last_vi;
    if (g._out_edges.empty())
    {
        last_vi = g._out_edges.end();
    }
    else
    {
        ei_begin = g._out_edges[0].begin();
        last_vi = g._out_edges.end() - 1;
        ei_end = last_vi->end();
    }
571
572
573
574
575
576
577
578
579
580
581
582
    typename adj_list<Vertex>::edge_iterator ebegin(g._out_edges.begin(),
                                                    g._out_edges.end(),
                                                    g._out_edges.begin(),
                                                    ei_begin);
    typename adj_list<Vertex>::edge_iterator eend(g._out_edges.begin(),
                                                  g._out_edges.end(),
                                                  last_vi,
                                                  ei_end);
    return std::make_pair(ebegin, eend);
}

template <class Vertex>
583
inline __attribute__((always_inline))
584
Vertex vertex(size_t i, const adj_list<Vertex>&)
585
586
587
588
589
{
    return i;
}

template <class Vertex>
590
inline
591
std::pair<typename adj_list<Vertex>::edge_descriptor, bool>
592
593
edge(Vertex s, Vertex t, const adj_list<Vertex>& g)
{
594
    typedef typename adj_list<Vertex>::edge_descriptor edge_descriptor;
Tiago Peixoto's avatar
Tiago Peixoto committed
595
    const auto& oes = g._out_edges[s];
596
597
598
599
600
    auto iter = std::find_if(oes.begin(), oes.end(),
                             [&](const auto& e) -> bool {return e.first == t;});
    if (iter != oes.end())
        return std::make_pair(edge_descriptor(s, t, iter->second, false),
                              true);
601
    Vertex v = graph_traits<adj_list<Vertex> >::null_vertex();
602
    return std::make_pair(edge_descriptor(v, v, v, false), false);
603
604
605
}

template <class Vertex>
606
inline __attribute__((always_inline))
607
size_t out_degree(Vertex v, const adj_list<Vertex>& g)
608
609
610
611
612
{
    return g._out_edges[v].size();
}

template <class Vertex>
613
inline __attribute__((always_inline))
614
size_t in_degree(Vertex v, const adj_list<Vertex>& g)
615
616
617
618
619
{
    return g._in_edges[v].size();
}

template <class Vertex>
620
inline __attribute__((always_inline))
621
size_t degree(Vertex v, const adj_list<Vertex>& g)
622
623
624
625
626
{
    return in_degree(v, g) + out_degree(v, g);
}

template <class Vertex>
627
inline __attribute__((always_inline))
628
629
std::pair<typename adj_list<Vertex>::out_edge_iterator,
          typename adj_list<Vertex>::out_edge_iterator>
630
631
632
out_edges(Vertex v, const adj_list<Vertex>& g)
{
    typedef typename adj_list<Vertex>::out_edge_iterator ei_t;
633
    auto& edges = g._out_edges[v];
634
635
    return std::make_pair(ei_t(v, edges.begin()),
                          ei_t(v, edges.end()));
636
637
638
}

template <class Vertex>
639
inline  __attribute__((always_inline))
640
641
std::pair<typename adj_list<Vertex>::in_edge_iterator,
          typename adj_list<Vertex>::in_edge_iterator>
642
643
644
in_edges(Vertex v, const adj_list<Vertex>& g)
{
    typedef typename adj_list<Vertex>::in_edge_iterator ei_t;
645
    auto& edges = g._in_edges[v];
646
647
    return std::make_pair(ei_t(v, edges.begin()),
                          ei_t(v, edges.end()));
648
649
650
}

template <class Vertex>
651
inline __attribute__((always_inline))
652
653
std::pair<typename adj_list<Vertex>::adjacency_iterator,
          typename adj_list<Vertex>::adjacency_iterator>
654
out_neighbours(Vertex v, const adj_list<Vertex>& g)
655
656
{
    typedef typename adj_list<Vertex>::adjacency_iterator ai_t;
657
658
659
    auto& edges = g._out_edges[v];
    return std::make_pair(ai_t(edges.begin()),
                          ai_t(edges.end()));
660
661
}

662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
template <class Vertex>
inline __attribute__((always_inline))
std::pair<typename adj_list<Vertex>::adjacency_iterator,
          typename adj_list<Vertex>::adjacency_iterator>
in_neighbours(Vertex v, const adj_list<Vertex>& g)
{
    typedef typename adj_list<Vertex>::adjacency_iterator ai_t;
    auto& edges = g._in_edges[v];
    return std::make_pair(ai_t(edges.begin()),
                          ai_t(edges.end()));
}

template <class Vertex>
inline __attribute__((always_inline))
std::pair<typename adj_list<Vertex>::adjacency_iterator,
          typename adj_list<Vertex>::adjacency_iterator>
adjacent_vertices(Vertex v, const adj_list<Vertex>& g)
{
    return out_neighbours(v, g);
}


684
template <class Vertex>
685
inline __attribute__((always_inline))
686
size_t num_vertices(const adj_list<Vertex>& g)
687
688
689
690
691
{
    return g._out_edges.size();
}

template <class Vertex>
692
inline __attribute__((always_inline))
693
size_t num_edges(const adj_list<Vertex>& g)
694
695
696
697
698
{
    return g._n_edges;
}

template <class Vertex>
699
inline __attribute__((always_inline))
700
Vertex add_vertex(adj_list<Vertex>& g)
701
{
702
703
704
    g._out_edges.emplace_back();
    g._in_edges.emplace_back();
    return g._out_edges.size() - 1;
705
706
707
708
709
}

template <class Vertex>
inline void clear_vertex(Vertex v, adj_list<Vertex>& g)
{
710
    if (!g._keep_epos)
711
    {
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
        auto remove_es = [&] (auto& out_edges, auto& in_edges)
            {
                auto& oes = out_edges[v];
                for (const auto& oe : oes)
                {
                    Vertex t = oe.first;
                    auto& ies = in_edges[t];
                    auto iter =
                        std::remove_if(ies.begin(), ies.end(),
                                       [&](const auto& ei) -> bool
                                       {
                                           if (ei.first == v)
                                           {
                                               g._free_indexes.push_back(ei.second);
                                               return true;
                                           }
                                           return false;
                                       });
                    ies.erase(iter, ies.end());
                }
                g._n_edges -= oes.size();
                oes.clear();
            };
        remove_es(g._out_edges, g._in_edges);
        remove_es(g._in_edges, g._out_edges);
737
738
739
    }
    else
    {
740
741
        auto remove_es = [&] (auto& out_edges, auto& in_edges,
                              const auto& get_pos)
742
        {
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
            auto& oes = out_edges[v];
            for (const auto& ei : oes)
            {
                Vertex t = ei.first;
                size_t idx = ei.second;
                auto& ies = in_edges[t];
                auto& back = ies.back();
                auto& pos = get_pos(idx);
                auto& bpos = get_pos(back.second);
                bpos = pos;
                ies[pos] = back;
                ies.pop_back();
                g._free_indexes.push_back(idx);
            }
            g._n_edges -= oes.size();
            oes.clear();
        };
        remove_es(g._out_edges, g._in_edges,
                  [&](size_t idx) -> auto& {return g._epos[idx].second;});
762
763
        remove_es(g._in_edges, g._out_edges,
                  [&](size_t idx) -> auto& {return g._epos[idx].first;});
764
765
766
    }
}

767
// O(V + E)
768
769
770
771
772
773
template <class Vertex>
inline void remove_vertex(Vertex v, adj_list<Vertex>& g)
{
    clear_vertex(v, g);
    g._out_edges.erase(g._out_edges.begin() + v);
    g._in_edges.erase(g._in_edges.begin() + v);
774

775
776
    auto shift_es = [&](auto& edges, int i)
    {
777
        for (auto& e : edges[i])
778
779
780
781
782
783
        {
            if (e.first > v)
                e.first--;
        }
    };

784
    int i, N = g._out_edges.size();
Tiago Peixoto's avatar
Tiago Peixoto committed
785
    #pragma omp parallel for default(shared) private(i) \
786
        schedule(runtime) if (N > 100)
787
788
    for (i = 0; i < N; ++i)
    {
789
790
        shift_es(g._out_edges, i);
        shift_es(g._in_edges, i);
791
    }
792
793
}

794
795
796
797
798
799
800
801
// O(k + k_last)
template <class Vertex>
inline void remove_vertex_fast(Vertex v, adj_list<Vertex>& g)
{
    Vertex back = g._out_edges.size() - 1;

    if (v < back)
    {
802
        clear_vertex(v, g);
803
804
        g._out_edges[v].swap(g._out_edges[back]);
        g._in_edges[v].swap(g._in_edges[back]);
805
806
        g._out_edges.pop_back();
        g._in_edges.pop_back();
807

808
        auto rename_v = [&] (auto& out_edges, auto& in_edges,
809
                             const auto& get_pos)
810
            {
811
                for (auto& eu : out_edges[v])
Tiago Peixoto's avatar
Tiago Peixoto committed
812
                {
813
814
815
816
817
818
819
820
821
                    Vertex u = eu.first;
                    if (u == back)
                    {
                        eu.first = v;
                    }
                    else
                    {
                        if (!g._keep_epos)
                        {
822
                            for (auto& e : in_edges[u])
823
824
825
826
827
828
829
830
831
                            {
                                if (e.first == back)
                                    e.first = v;
                            }
                        }
                        else
                        {
                            size_t idx = eu.second;
                            auto pos = get_pos(idx);
832
                            in_edges[u][pos].first = v;
833
834
                        }
                    }
Tiago Peixoto's avatar
Tiago Peixoto committed
835
                }
836
            };
837

838
        rename_v(g._out_edges, g._in_edges,
839
                 [&](size_t idx) -> auto {return g._epos[idx].second;});
840
841
        rename_v(g._in_edges, g._out_edges,
                 [&](size_t idx) -> auto {return g._epos[idx].first;});
842
843
    }
}
844
845

template <class Vertex>
846
847
inline
typename std::pair<typename adj_list<Vertex>::edge_descriptor, bool>
848
849
850
851
852
add_edge(Vertex s, Vertex t, adj_list<Vertex>& g)
{
    Vertex idx;
    if (g._free_indexes.empty())
    {
853
        idx = g._edge_index_range++;
854
855
856
857
858
859
860
    }
    else
    {
        idx = g._free_indexes.front();
        g._free_indexes.pop_front();
    }

861
862
863
864
    auto& oes = g._out_edges[s];
    auto& ies = g._in_edges[t];
    oes.emplace_back(t, idx);
    ies.emplace_back(s, idx);
865
866
    g._n_edges++;

867
868
869
870
    if (g._keep_epos)
    {
        if (idx >= g._epos.size())
            g._epos.resize(idx + 1);
871
872
873
        auto& ei = g._epos[idx];
        ei.first = oes.size() - 1;
        ei.second = ies.size() - 1;
874
875
    }

876
877
    typedef typename adj_list<Vertex>::edge_descriptor edge_descriptor;
    return std::make_pair(edge_descriptor(s, t, idx, false), true);
878
879
880
881
882
883
}

template <class Vertex>
inline void remove_edge(Vertex s, Vertex t,
                        adj_list<Vertex>& g)
{
884
    if (!g._keep_epos)
885
    {
Tiago Peixoto's avatar
Tiago Peixoto committed
886
        auto& oes = g._out_edges[s];
887
888
889
890
        auto iter_o = std::find_if(oes.begin(), oes.end(),
                                   [&] (const auto& ei) -> bool
                                   {return t == ei.first;});
        if (iter_o != oes.end())
891
        {
892
893
894
            g._free_indexes.push_back(iter_o->second);
            oes.erase(iter_o);
            g._n_edges--;
895
896
        }

Tiago Peixoto's avatar
Tiago Peixoto committed
897
        auto& ies = g._in_edges[t];
898
899
900
901
        auto iter_i = std::find_if(ies.begin(), ies.end(),
                                   [&] (const auto& ei) -> bool
                                   {return s == ei.first;});
        if (iter_i != ies.end())
902
        {
903
            ies.erase(iter_i);
904
905
        }
    }
906
    else
907
    {
908
        remove_edge(edge(s, t, g).first, g);
909
910
911
912
913
914
915
    }
}

template <class Vertex>
inline void remove_edge(const typename adj_list<Vertex>::edge_descriptor& e,
                        adj_list<Vertex>& g)
{
916
917
918
    auto& s = e.s;
    auto& t = e.t;
    auto& idx = e.idx;
Tiago Peixoto's avatar
Tiago Peixoto committed
919
920
    auto& oes = g._out_edges[s];
    auto& ies = g._in_edges[t];
921

922
    bool found = false;
923
    if (!g._keep_epos) // O(k_s + k_t)
924
    {
925
926
927
928
929
930
931
932
933
934
935
        auto remove_e = [&] (auto& elist, auto v)
            {
                auto iter = std::find_if(elist.begin(), elist.end(),
                                         [&] (const auto& ei) -> bool
                                         {return v == ei.first && idx == ei.second;});
                if (iter != elist.end())
                {
                    elist.erase(iter);
                    found = true;
                }
            };
936

937
938
        remove_e(oes, t);
        remove_e(ies, s);
939
    }
940
941
    else // O(1)
    {
942
943
        if (idx < g._epos.size())
        {
944
945
946
947
948
949
950
951
952
953
954
            auto remove_e = [&] (auto& elist, const auto& get_pos)
            {
                const auto& back = elist.back();
                auto pindex = get_pos(idx);
                get_pos(back.second) = pindex;
                elist[pindex] = back;
                elist.pop_back();
            };

            remove_e(oes, [&](size_t idx) -> auto& {return g._epos[idx].first;});
            remove_e(ies, [&](size_t idx) -> auto& {return g._epos[idx].second;});
955

956
957
            found = true;
        }
958
959
960
961
962
963
    }

    if (found)
    {
        g._free_indexes.push_back(idx);
        g._n_edges--;
964
    }
965
966
}

967

968
template <class Vertex>
969
inline
970
971
Vertex source(const typename adj_list<Vertex>::edge_descriptor& e,
              const adj_list<Vertex>&)
972
{
973
    return e.s;
974
975
976
}

template <class Vertex>
977
inline
978
979
Vertex target(const typename adj_list<Vertex>::edge_descriptor& e,
              const adj_list<Vertex>&)
980
{
981
    return e.t;
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
}

//========================================================================
// Vertex and edge index property maps
//========================================================================

template <class Vertex>
struct property_map<adj_list<Vertex>, vertex_index_t>
{
    typedef identity_property_map type;
    typedef type const_type;
};

template <class Vertex>
struct property_map<const adj_list<Vertex>, vertex_index_t>
{
    typedef identity_property_map type;
    typedef type const_type;
};
For faster browsing, not all history is shown. View entire blame