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