lemon/compact_graph.h
author Peter Kovacs <kpeter@inf.elte.hu>
Sat, 17 Feb 2018 23:44:32 +0100
changeset 1421 4fd76139b69e
permissions -rw-r--r--
Add operator[] to Path structures (#250)
gabriel@1419
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
gabriel@1419
     2
 *
gabriel@1419
     3
 * This file is a part of LEMON, a generic C++ optimization library.
gabriel@1419
     4
 *
gabriel@1419
     5
 * Copyright (C) 2017
gabriel@1419
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
gabriel@1419
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
gabriel@1419
     8
 *
gabriel@1419
     9
 * Permission to use, modify and distribute this software is granted
gabriel@1419
    10
 * provided that this copyright notice appears in all copies. For
gabriel@1419
    11
 * precise terms see the accompanying LICENSE file.
gabriel@1419
    12
 *
gabriel@1419
    13
 * This software is provided "AS IS" with no warranty of any kind,
gabriel@1419
    14
 * express or implied, and with no claim as to its suitability for any
gabriel@1419
    15
 * purpose.
gabriel@1419
    16
 *
gabriel@1419
    17
 */
gabriel@1419
    18
gabriel@1419
    19
#ifndef LEMON_COMPACT_GRAPH_H
gabriel@1419
    20
#define LEMON_COMPACT_GRAPH_H
gabriel@1419
    21
gabriel@1419
    22
///\ingroup graphs
gabriel@1419
    23
///\file
gabriel@1419
    24
///\brief CompactDigraph class.
gabriel@1419
    25
gabriel@1419
    26
#include <lemon/core.h>
gabriel@1419
    27
#include <lemon/bits/graph_extender.h>
gabriel@1419
    28
gabriel@1419
    29
#include <algorithm>
gabriel@1419
    30
gabriel@1419
    31
namespace lemon {
gabriel@1419
    32
gabriel@1419
    33
  class CompactDigraphBase {
gabriel@1419
    34
gabriel@1419
    35
  public:
gabriel@1419
    36
gabriel@1419
    37
    CompactDigraphBase()
gabriel@1419
    38
      : built(false), node_num(0), arc_num(0),
gabriel@1419
    39
        node_first_out(NULL),
gabriel@1419
    40
        arc_target(NULL) {}
gabriel@1419
    41
gabriel@1419
    42
    ~CompactDigraphBase() {
gabriel@1419
    43
      if (built) {
gabriel@1419
    44
        delete[] node_first_out;
gabriel@1419
    45
        delete[] arc_target;
gabriel@1419
    46
      }
gabriel@1419
    47
    }
gabriel@1419
    48
gabriel@1419
    49
    class Node {
gabriel@1419
    50
      friend class CompactDigraphBase;
gabriel@1419
    51
    protected:
gabriel@1419
    52
      int id;
gabriel@1419
    53
      Node(int _id) : id(_id) {}
gabriel@1419
    54
    public:
gabriel@1419
    55
      Node() {}
gabriel@1419
    56
      Node (Invalid) : id(-1) {}
gabriel@1419
    57
      bool operator==(const Node& node) const { return id == node.id; }
gabriel@1419
    58
      bool operator!=(const Node& node) const { return id != node.id; }
gabriel@1419
    59
      bool operator<(const Node& node) const { return id < node.id; }
gabriel@1419
    60
    };
gabriel@1419
    61
gabriel@1419
    62
    class Arc {
gabriel@1419
    63
      friend class CompactDigraphBase;
gabriel@1419
    64
    protected:
gabriel@1419
    65
      int id;
gabriel@1419
    66
      int source;
gabriel@1419
    67
      Arc(int _id, int _source) : id(_id), source(_source) {}
gabriel@1419
    68
    public:
gabriel@1419
    69
      Arc() { }
gabriel@1419
    70
      Arc (Invalid) : id(-1), source(-1) {}
gabriel@1419
    71
      bool operator==(const Arc& arc) const { return id == arc.id; }
gabriel@1419
    72
      bool operator!=(const Arc& arc) const { return id != arc.id; }
gabriel@1419
    73
      bool operator<(const Arc& arc) const { return id < arc.id; }
gabriel@1419
    74
    };
gabriel@1419
    75
gabriel@1419
    76
    Node source(const Arc& e) const { return Node(e.source); }
gabriel@1419
    77
    Node target(const Arc& e) const { return Node(arc_target[e.id]); }
gabriel@1419
    78
gabriel@1419
    79
    void first(Node& n) const { n.id = node_num - 1; }
gabriel@1419
    80
    static void next(Node& n) { --n.id; }
gabriel@1419
    81
gabriel@1419
    82
  private:
gabriel@1419
    83
gabriel@1419
    84
    void nextSource(Arc& e) const {
gabriel@1419
    85
      if (e.id == -1) return;
gabriel@1419
    86
      int last = node_first_out[e.source] - 1;
gabriel@1419
    87
      while (e.id == last) {
gabriel@1419
    88
        --e.source;
gabriel@1419
    89
        last = node_first_out[e.source] - 1;
gabriel@1419
    90
      }
gabriel@1419
    91
    }
gabriel@1419
    92
gabriel@1419
    93
  public:
gabriel@1419
    94
gabriel@1419
    95
    void first(Arc& e) const {
gabriel@1419
    96
      e.id = arc_num - 1;
gabriel@1419
    97
      e.source = node_num - 1;
gabriel@1419
    98
      nextSource(e);
gabriel@1419
    99
    }
gabriel@1419
   100
    void next(Arc& e) const {
gabriel@1419
   101
      --e.id;
gabriel@1419
   102
      nextSource(e);
gabriel@1419
   103
    }
gabriel@1419
   104
gabriel@1419
   105
    void firstOut(Arc& e, const Node& n) const {
gabriel@1419
   106
      e.source = n.id;
gabriel@1419
   107
      e.id = node_first_out[n.id];
gabriel@1419
   108
      if (e.id == node_first_out[n.id + 1]) e = INVALID;
gabriel@1419
   109
    }
gabriel@1419
   110
    void nextOut(Arc& e) const {
gabriel@1419
   111
      ++e.id;
gabriel@1419
   112
      if (e.id == node_first_out[e.source + 1]) e = INVALID;
gabriel@1419
   113
    }
gabriel@1419
   114
gabriel@1419
   115
    void firstIn(Arc& e, const Node& n) const {
gabriel@1419
   116
      first(e);
gabriel@1419
   117
      while(e != INVALID && target(e) != n) {
gabriel@1419
   118
        next(e);
gabriel@1419
   119
      }
gabriel@1419
   120
    }
gabriel@1419
   121
    void nextIn(Arc& e) const {
gabriel@1419
   122
      Node arcTarget = target(e);
gabriel@1419
   123
      do {
gabriel@1419
   124
        next(e);
gabriel@1419
   125
      } while(e != INVALID && target(e) != arcTarget);
gabriel@1419
   126
    }
gabriel@1419
   127
gabriel@1419
   128
    static int id(const Node& n) { return n.id; }
gabriel@1419
   129
    static Node nodeFromId(int id) { return Node(id); }
gabriel@1419
   130
    int maxNodeId() const { return node_num - 1; }
gabriel@1419
   131
gabriel@1419
   132
    static int id(const Arc& e) { return e.id; }
gabriel@1419
   133
    Arc arcFromId(int id) const {
gabriel@1419
   134
      int *l = std::upper_bound(node_first_out, node_first_out + node_num, id) - 1;
gabriel@1419
   135
      int src = l - node_first_out;
gabriel@1419
   136
      return Arc(id, src);
gabriel@1419
   137
    }
gabriel@1419
   138
    int maxArcId() const { return arc_num - 1; }
gabriel@1419
   139
gabriel@1419
   140
    typedef True NodeNumTag;
gabriel@1419
   141
    typedef True ArcNumTag;
gabriel@1419
   142
gabriel@1419
   143
    int nodeNum() const { return node_num; }
gabriel@1419
   144
    int arcNum() const { return arc_num; }
gabriel@1419
   145
gabriel@1419
   146
  private:
gabriel@1419
   147
gabriel@1419
   148
    template <typename Digraph, typename NodeRefMap>
gabriel@1419
   149
    class ArcLess {
gabriel@1419
   150
    public:
gabriel@1419
   151
      typedef typename Digraph::Arc Arc;
gabriel@1419
   152
gabriel@1419
   153
      ArcLess(const Digraph &_graph, const NodeRefMap& _nodeRef)
gabriel@1419
   154
        : digraph(_graph), nodeRef(_nodeRef) {}
gabriel@1419
   155
gabriel@1419
   156
      bool operator()(const Arc& left, const Arc& right) const {
gabriel@1419
   157
        return nodeRef[digraph.target(left)] < nodeRef[digraph.target(right)];
gabriel@1419
   158
      }
gabriel@1419
   159
    private:
gabriel@1419
   160
      const Digraph& digraph;
gabriel@1419
   161
      const NodeRefMap& nodeRef;
gabriel@1419
   162
    };
gabriel@1419
   163
gabriel@1419
   164
  public:
gabriel@1419
   165
gabriel@1419
   166
    typedef True BuildTag;
gabriel@1419
   167
gabriel@1419
   168
    void clear() {
gabriel@1419
   169
      if (built) {
gabriel@1419
   170
        delete[] node_first_out;
gabriel@1419
   171
        delete[] arc_target;
gabriel@1419
   172
      }
gabriel@1419
   173
      built = false;
gabriel@1419
   174
      node_num = 0;
gabriel@1419
   175
      arc_num = 0;
gabriel@1419
   176
    }
gabriel@1419
   177
gabriel@1419
   178
    template <typename Digraph, typename NodeRefMap, typename ArcRefMap>
gabriel@1419
   179
    void build(const Digraph& digraph, NodeRefMap& nodeRef, ArcRefMap& arcRef) {
gabriel@1419
   180
      typedef typename Digraph::Node GNode;
gabriel@1419
   181
      typedef typename Digraph::Arc GArc;
gabriel@1419
   182
gabriel@1419
   183
      built = true;
gabriel@1419
   184
gabriel@1419
   185
      node_num = countNodes(digraph);
gabriel@1419
   186
      arc_num = countArcs(digraph);
gabriel@1419
   187
gabriel@1419
   188
      node_first_out = new int[node_num + 1];
gabriel@1419
   189
gabriel@1419
   190
      arc_target = new int[arc_num];
gabriel@1419
   191
gabriel@1419
   192
      int node_index = 0;
gabriel@1419
   193
      for (typename Digraph::NodeIt n(digraph); n != INVALID; ++n) {
gabriel@1419
   194
        nodeRef[n] = Node(node_index);
gabriel@1419
   195
        ++node_index;
gabriel@1419
   196
      }
gabriel@1419
   197
gabriel@1419
   198
      ArcLess<Digraph, NodeRefMap> arcLess(digraph, nodeRef);
gabriel@1419
   199
gabriel@1419
   200
      int arc_index = 0;
gabriel@1419
   201
      for (typename Digraph::NodeIt n(digraph); n != INVALID; ++n) {
gabriel@1419
   202
        int source = nodeRef[n].id;
gabriel@1419
   203
        std::vector<GArc> arcs;
gabriel@1419
   204
        for (typename Digraph::OutArcIt e(digraph, n); e != INVALID; ++e) {
gabriel@1419
   205
          arcs.push_back(e);
gabriel@1419
   206
        }
gabriel@1419
   207
        if (!arcs.empty()) {
gabriel@1419
   208
          node_first_out[source] = arc_index;
gabriel@1419
   209
          std::sort(arcs.begin(), arcs.end(), arcLess);
gabriel@1419
   210
          for (typename std::vector<GArc>::iterator it = arcs.begin();
gabriel@1419
   211
               it != arcs.end(); ++it) {
gabriel@1419
   212
            int target = nodeRef[digraph.target(*it)].id;
gabriel@1419
   213
            arcRef[*it] = Arc(arc_index, source);
gabriel@1419
   214
            arc_target[arc_index] = target;
gabriel@1419
   215
            ++arc_index;
gabriel@1419
   216
          }
gabriel@1419
   217
        } else {
gabriel@1419
   218
          node_first_out[source] = arc_index;
gabriel@1419
   219
        }
gabriel@1419
   220
      }
gabriel@1419
   221
      node_first_out[node_num] = arc_num;
gabriel@1419
   222
    }
gabriel@1419
   223
gabriel@1419
   224
    template <typename ArcListIterator>
gabriel@1419
   225
    void build(int n, ArcListIterator first, ArcListIterator last) {
gabriel@1419
   226
      built = true;
gabriel@1419
   227
gabriel@1419
   228
      node_num = n;
gabriel@1419
   229
      arc_num = static_cast<int>(std::distance(first, last));
gabriel@1419
   230
gabriel@1419
   231
      node_first_out = new int[node_num + 1];
gabriel@1419
   232
gabriel@1419
   233
      arc_target = new int[arc_num];
gabriel@1419
   234
gabriel@1419
   235
      int arc_index = 0;
gabriel@1419
   236
      for (int i = 0; i != node_num; ++i) {
gabriel@1419
   237
        node_first_out[i] = arc_index;
gabriel@1419
   238
        for ( ; first != last && (*first).first == i; ++first) {
gabriel@1419
   239
          int j = (*first).second;
gabriel@1419
   240
          LEMON_ASSERT(j >= 0 && j < node_num,
gabriel@1419
   241
            "Wrong arc list for CompactDigraph::build()");
gabriel@1419
   242
          arc_target[arc_index] = j;
gabriel@1419
   243
          ++arc_index;
gabriel@1419
   244
        }
gabriel@1419
   245
      }
gabriel@1419
   246
      LEMON_ASSERT(first == last,
gabriel@1419
   247
        "Wrong arc list for CompactDigraph::build()");
gabriel@1419
   248
      node_first_out[node_num] = arc_num;
gabriel@1419
   249
    }
gabriel@1419
   250
gabriel@1419
   251
  protected:
gabriel@1419
   252
    bool built;
gabriel@1419
   253
    int node_num;
gabriel@1419
   254
    int arc_num;
gabriel@1419
   255
    int *node_first_out;
gabriel@1419
   256
    int *arc_target;
gabriel@1419
   257
  };
gabriel@1419
   258
gabriel@1419
   259
  typedef DigraphExtender<CompactDigraphBase> ExtendedCompactDigraphBase;
gabriel@1419
   260
gabriel@1419
   261
gabriel@1419
   262
  /// \ingroup graphs
gabriel@1419
   263
  ///
gabriel@1419
   264
  /// \brief A static directed graph class.
gabriel@1419
   265
  ///
gabriel@1419
   266
  /// \ref CompactDigraph is a highly efficient digraph implementation
gabriel@1419
   267
  /// similar to \ref StaticDigraph. It is more memory efficient but does
gabriel@1419
   268
  /// not provide efficient iteration over incoming arcs.
gabriel@1419
   269
  ///
gabriel@1419
   270
  /// It stores only one \c int values for each node and one \c int value
gabriel@1419
   271
  /// for each arc. Its \ref InArcIt implementation is inefficient and
gabriel@1419
   272
  /// provided only for compatibility with the \ref concepts::Digraph "Digraph concept".
gabriel@1419
   273
  ///
gabriel@1419
   274
  /// This type fully conforms to the \ref concepts::Digraph "Digraph concept".
gabriel@1419
   275
  /// Most of its member functions and nested classes are documented
gabriel@1419
   276
  /// only in the concept class.
gabriel@1419
   277
  ///
gabriel@1419
   278
  /// \sa concepts::Digraph
gabriel@1419
   279
  class CompactDigraph : public ExtendedCompactDigraphBase {
gabriel@1419
   280
gabriel@1419
   281
  private:
gabriel@1419
   282
    /// Graphs are \e not copy constructible. Use DigraphCopy instead.
gabriel@1419
   283
    CompactDigraph(const CompactDigraph &) : ExtendedCompactDigraphBase() {};
gabriel@1419
   284
    /// \brief Assignment of a graph to another one is \e not allowed.
gabriel@1419
   285
    /// Use DigraphCopy instead.
gabriel@1419
   286
    void operator=(const CompactDigraph&) {}
gabriel@1419
   287
gabriel@1419
   288
  public:
gabriel@1419
   289
gabriel@1419
   290
    typedef ExtendedCompactDigraphBase Parent;
gabriel@1419
   291
gabriel@1419
   292
  public:
gabriel@1419
   293
gabriel@1419
   294
    /// \brief Constructor
gabriel@1419
   295
    ///
gabriel@1419
   296
    /// Default constructor.
gabriel@1419
   297
    CompactDigraph() : Parent() {}
gabriel@1419
   298
gabriel@1419
   299
    /// \brief The node with the given index.
gabriel@1419
   300
    ///
gabriel@1419
   301
    /// This function returns the node with the given index.
gabriel@1419
   302
    /// \sa index()
gabriel@1419
   303
    static Node node(int ix) { return Parent::nodeFromId(ix); }
gabriel@1419
   304
gabriel@1419
   305
    /// \brief The arc with the given index.
gabriel@1419
   306
    ///
gabriel@1419
   307
    /// This function returns the arc with the given index.
gabriel@1419
   308
    /// \sa index()
gabriel@1419
   309
    Arc arc(int ix) { return arcFromId(ix); }
gabriel@1419
   310
gabriel@1419
   311
    /// \brief The index of the given node.
gabriel@1419
   312
    ///
gabriel@1419
   313
    /// This function returns the index of the the given node.
gabriel@1419
   314
    /// \sa node()
gabriel@1419
   315
    static int index(Node node) { return Parent::id(node); }
gabriel@1419
   316
gabriel@1419
   317
    /// \brief The index of the given arc.
gabriel@1419
   318
    ///
gabriel@1419
   319
    /// This function returns the index of the the given arc.
gabriel@1419
   320
    /// \sa arc()
gabriel@1419
   321
    static int index(Arc arc) { return Parent::id(arc); }
gabriel@1419
   322
gabriel@1419
   323
    /// \brief Number of nodes.
gabriel@1419
   324
    ///
gabriel@1419
   325
    /// This function returns the number of nodes.
gabriel@1419
   326
    int nodeNum() const { return node_num; }
gabriel@1419
   327
gabriel@1419
   328
    /// \brief Number of arcs.
gabriel@1419
   329
    ///
gabriel@1419
   330
    /// This function returns the number of arcs.
gabriel@1419
   331
    int arcNum() const { return arc_num; }
gabriel@1419
   332
gabriel@1419
   333
    /// \brief Build the digraph copying another digraph.
gabriel@1419
   334
    ///
gabriel@1419
   335
    /// This function builds the digraph copying another digraph of any
gabriel@1419
   336
    /// kind. It can be called more than once, but in such case, the whole
gabriel@1419
   337
    /// structure and all maps will be cleared and rebuilt.
gabriel@1419
   338
    ///
gabriel@1419
   339
    /// This method also makes possible to copy a digraph to a CompactDigraph
gabriel@1419
   340
    /// structure using \ref DigraphCopy.
gabriel@1419
   341
    ///
gabriel@1419
   342
    /// \param digraph An existing digraph to be copied.
gabriel@1419
   343
    /// \param nodeRef The node references will be copied into this map.
gabriel@1419
   344
    /// Its key type must be \c Digraph::Node and its value type must be
gabriel@1419
   345
    /// \c CompactDigraph::Node.
gabriel@1419
   346
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap"
gabriel@1419
   347
    /// concept.
gabriel@1419
   348
    /// \param arcRef The arc references will be copied into this map.
gabriel@1419
   349
    /// Its key type must be \c Digraph::Arc and its value type must be
gabriel@1419
   350
    /// \c CompactDigraph::Arc.
gabriel@1419
   351
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
gabriel@1419
   352
    ///
gabriel@1419
   353
    /// \note If you do not need the arc references, then you could use
gabriel@1419
   354
    /// \ref NullMap for the last parameter. However the node references
gabriel@1419
   355
    /// are required by the function itself, thus they must be readable
gabriel@1419
   356
    /// from the map.
gabriel@1419
   357
    template <typename Digraph, typename NodeRefMap, typename ArcRefMap>
gabriel@1419
   358
    void build(const Digraph& digraph, NodeRefMap& nodeRef, ArcRefMap& arcRef) {
gabriel@1419
   359
      if (built) Parent::clear();
gabriel@1419
   360
      Parent::build(digraph, nodeRef, arcRef);
gabriel@1419
   361
    }
gabriel@1419
   362
gabriel@1419
   363
    /// \brief Build the digraph from an arc list.
gabriel@1419
   364
    ///
gabriel@1419
   365
    /// This function builds the digraph from the given arc list.
gabriel@1419
   366
    /// It can be called more than once, but in such case, the whole
gabriel@1419
   367
    /// structure and all maps will be cleared and rebuilt.
gabriel@1419
   368
    ///
gabriel@1419
   369
    /// The list of the arcs must be given in the range <tt>[begin, end)</tt>
gabriel@1419
   370
    /// specified by STL compatible itartors whose \c value_type must be
gabriel@1419
   371
    /// <tt>std::pair<int,int></tt>.
gabriel@1419
   372
    /// Each arc must be specified by a pair of integer indices
gabriel@1419
   373
    /// from the range <tt>[0..n-1]</tt>. <i>The pairs must be in a
gabriel@1419
   374
    /// non-decreasing order with respect to their first values.</i>
gabriel@1419
   375
    /// If the k-th pair in the list is <tt>(i,j)</tt>, then
gabriel@1419
   376
    /// <tt>arc(k-1)</tt> will connect <tt>node(i)</tt> to <tt>node(j)</tt>.
gabriel@1419
   377
    ///
gabriel@1419
   378
    /// \param n The number of nodes.
gabriel@1419
   379
    /// \param begin An iterator pointing to the beginning of the arc list.
gabriel@1419
   380
    /// \param end An iterator pointing to the end of the arc list.
gabriel@1419
   381
    ///
gabriel@1419
   382
    /// For example, a simple digraph can be constructed like this.
gabriel@1419
   383
    /// \code
gabriel@1419
   384
    ///   std::vector<std::pair<int,int> > arcs;
gabriel@1419
   385
    ///   arcs.push_back(std::make_pair(0,1));
gabriel@1419
   386
    ///   arcs.push_back(std::make_pair(0,2));
gabriel@1419
   387
    ///   arcs.push_back(std::make_pair(1,3));
gabriel@1419
   388
    ///   arcs.push_back(std::make_pair(1,2));
gabriel@1419
   389
    ///   arcs.push_back(std::make_pair(3,0));
gabriel@1419
   390
    ///   CompactDigraph gr;
gabriel@1419
   391
    ///   gr.build(4, arcs.begin(), arcs.end());
gabriel@1419
   392
    /// \endcode
gabriel@1419
   393
    template <typename ArcListIterator>
gabriel@1419
   394
    void build(int n, ArcListIterator begin, ArcListIterator end) {
gabriel@1419
   395
      if (built) Parent::clear();
gabriel@1419
   396
      CompactDigraphBase::build(n, begin, end);
gabriel@1419
   397
      notifier(Node()).build();
gabriel@1419
   398
      notifier(Arc()).build();
gabriel@1419
   399
    }
gabriel@1419
   400
gabriel@1419
   401
    /// \brief Clear the digraph.
gabriel@1419
   402
    ///
gabriel@1419
   403
    /// This function erases all nodes and arcs from the digraph.
gabriel@1419
   404
    void clear() {
gabriel@1419
   405
      Parent::clear();
gabriel@1419
   406
    }
gabriel@1419
   407
gabriel@1419
   408
  public:
gabriel@1419
   409
gabriel@1419
   410
    Node baseNode(const OutArcIt &arc) const {
gabriel@1419
   411
      return Parent::source(static_cast<const Arc&>(arc));
gabriel@1419
   412
    }
gabriel@1419
   413
gabriel@1419
   414
    Node runningNode(const OutArcIt &arc) const {
gabriel@1419
   415
      return Parent::target(static_cast<const Arc&>(arc));
gabriel@1419
   416
    }
gabriel@1419
   417
gabriel@1419
   418
    Node baseNode(const InArcIt &arc) const {
gabriel@1419
   419
      return Parent::target(static_cast<const Arc&>(arc));
gabriel@1419
   420
    }
gabriel@1419
   421
gabriel@1419
   422
    Node runningNode(const InArcIt &arc) const {
gabriel@1419
   423
      return Parent::source(static_cast<const Arc&>(arc));
gabriel@1419
   424
    }
gabriel@1419
   425
gabriel@1419
   426
  };
gabriel@1419
   427
gabriel@1419
   428
}
gabriel@1419
   429
gabriel@1419
   430
#endif