lemon/greedy_tsp.h
author Peter Kovacs <kpeter@inf.elte.hu>
Sat, 07 Oct 2017 15:48:00 +0200
changeset 1410 d9f79b81ef6c
parent 1250 97d978243703
permissions -rw-r--r--
Change the default graph type of Vf2 and Vf2pp (#597)
kpeter@1201
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
kpeter@1201
     2
 *
kpeter@1201
     3
 * This file is a part of LEMON, a generic C++ optimization library.
kpeter@1201
     4
 *
alpar@1270
     5
 * Copyright (C) 2003-2013
kpeter@1201
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@1201
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@1201
     8
 *
kpeter@1201
     9
 * Permission to use, modify and distribute this software is granted
kpeter@1201
    10
 * provided that this copyright notice appears in all copies. For
kpeter@1201
    11
 * precise terms see the accompanying LICENSE file.
kpeter@1201
    12
 *
kpeter@1201
    13
 * This software is provided "AS IS" with no warranty of any kind,
kpeter@1201
    14
 * express or implied, and with no claim as to its suitability for any
kpeter@1201
    15
 * purpose.
kpeter@1201
    16
 *
kpeter@1201
    17
 */
kpeter@1201
    18
f4c3@1199
    19
#ifndef LEMON_GREEDY_TSP_H
f4c3@1199
    20
#define LEMON_GREEDY_TSP_H
f4c3@1199
    21
kpeter@1201
    22
/// \ingroup tsp
kpeter@1201
    23
/// \file
kpeter@1201
    24
/// \brief Greedy algorithm for symmetric TSP
kpeter@1201
    25
kpeter@1201
    26
#include <vector>
kpeter@1201
    27
#include <algorithm>
f4c3@1199
    28
#include <lemon/full_graph.h>
f4c3@1199
    29
#include <lemon/unionfind.h>
f4c3@1199
    30
f4c3@1199
    31
namespace lemon {
f4c3@1199
    32
kpeter@1202
    33
  /// \ingroup tsp
kpeter@1202
    34
  ///
kpeter@1201
    35
  /// \brief Greedy algorithm for symmetric TSP.
kpeter@1201
    36
  ///
kpeter@1201
    37
  /// GreedyTsp implements the greedy heuristic for solving
kpeter@1201
    38
  /// symmetric \ref tsp "TSP".
kpeter@1201
    39
  ///
kpeter@1201
    40
  /// This algorithm is quite similar to the \ref NearestNeighborTsp
kpeter@1201
    41
  /// "nearest neighbor" heuristic, but it maintains a set of disjoint paths.
kpeter@1201
    42
  /// At each step, the shortest possible edge is added to these paths
kpeter@1201
    43
  /// as long as it does not create a cycle of less than n edges and it does
kpeter@1201
    44
  /// not increase the degree of any node above two.
kpeter@1201
    45
  ///
kpeter@1204
    46
  /// This method runs in O(n<sup>2</sup>) time.
kpeter@1204
    47
  /// It quickly finds a relatively short tour for most TSP instances,
kpeter@1204
    48
  /// but it could also yield a really bad (or even the worst) solution
kpeter@1204
    49
  /// in special cases.
kpeter@1201
    50
  ///
kpeter@1201
    51
  /// \tparam CM Type of the cost map.
kpeter@1201
    52
  template <typename CM>
kpeter@1201
    53
  class GreedyTsp
kpeter@1201
    54
  {
kpeter@1201
    55
    public:
f4c3@1199
    56
kpeter@1201
    57
      /// Type of the cost map
kpeter@1201
    58
      typedef CM CostMap;
kpeter@1201
    59
      /// Type of the edge costs
kpeter@1201
    60
      typedef typename CM::Value Cost;
kpeter@1201
    61
kpeter@1201
    62
    private:
kpeter@1201
    63
kpeter@1201
    64
      GRAPH_TYPEDEFS(FullGraph);
kpeter@1201
    65
kpeter@1201
    66
      const FullGraph &_gr;
kpeter@1201
    67
      const CostMap &_cost;
kpeter@1201
    68
      Cost _sum;
kpeter@1201
    69
      std::vector<Node> _path;
alpar@1270
    70
kpeter@1201
    71
    private:
alpar@1270
    72
kpeter@1201
    73
      // Functor class to compare edges by their costs
kpeter@1201
    74
      class EdgeComp {
kpeter@1201
    75
      private:
kpeter@1201
    76
        const CostMap &_cost;
kpeter@1201
    77
f4c3@1199
    78
      public:
kpeter@1201
    79
        EdgeComp(const CostMap &cost) : _cost(cost) {}
kpeter@1201
    80
kpeter@1201
    81
        bool operator()(const Edge &a, const Edge &b) const {
kpeter@1201
    82
          return _cost[a] < _cost[b];
f4c3@1199
    83
        }
kpeter@1201
    84
      };
f4c3@1199
    85
kpeter@1201
    86
    public:
f4c3@1199
    87
kpeter@1201
    88
      /// \brief Constructor
kpeter@1201
    89
      ///
kpeter@1201
    90
      /// Constructor.
kpeter@1201
    91
      /// \param gr The \ref FullGraph "full graph" the algorithm runs on.
kpeter@1201
    92
      /// \param cost The cost map.
kpeter@1201
    93
      GreedyTsp(const FullGraph &gr, const CostMap &cost)
kpeter@1201
    94
        : _gr(gr), _cost(cost) {}
f4c3@1199
    95
kpeter@1201
    96
      /// \name Execution Control
kpeter@1201
    97
      /// @{
f4c3@1199
    98
kpeter@1201
    99
      /// \brief Runs the algorithm.
kpeter@1201
   100
      ///
kpeter@1201
   101
      /// This function runs the algorithm.
kpeter@1201
   102
      ///
kpeter@1201
   103
      /// \return The total cost of the found tour.
f4c3@1199
   104
      Cost run() {
kpeter@1201
   105
        _path.clear();
kpeter@1201
   106
kpeter@1201
   107
        if (_gr.nodeNum() == 0) return _sum = 0;
kpeter@1201
   108
        else if (_gr.nodeNum() == 1) {
kpeter@1201
   109
          _path.push_back(_gr(0));
kpeter@1201
   110
          return _sum = 0;
kpeter@1201
   111
        }
kpeter@1201
   112
kpeter@1201
   113
        std::vector<int> plist;
kpeter@1201
   114
        plist.resize(_gr.nodeNum()*2, -1);
kpeter@1201
   115
kpeter@1201
   116
        std::vector<Edge> sorted_edges;
f4c3@1199
   117
        sorted_edges.reserve(_gr.edgeNum());
kpeter@1201
   118
        for (EdgeIt e(_gr); e != INVALID; ++e)
kpeter@1201
   119
          sorted_edges.push_back(e);
kpeter@1201
   120
        std::sort(sorted_edges.begin(), sorted_edges.end(), EdgeComp(_cost));
f4c3@1199
   121
kpeter@1201
   122
        FullGraph::NodeMap<int> item_int_map(_gr);
kpeter@1201
   123
        UnionFind<FullGraph::NodeMap<int> > union_find(item_int_map);
kpeter@1201
   124
        for (NodeIt n(_gr); n != INVALID; ++n)
kpeter@1201
   125
          union_find.insert(n);
f4c3@1199
   126
f4c3@1199
   127
        FullGraph::NodeMap<int> degree(_gr, 0);
f4c3@1199
   128
f4c3@1199
   129
        int nodesNum = 0, i = 0;
kpeter@1201
   130
        while (nodesNum != _gr.nodeNum()-1) {
kpeter@1201
   131
          Edge e = sorted_edges[i++];
kpeter@1201
   132
          Node u = _gr.u(e),
kpeter@1201
   133
               v = _gr.v(e);
f4c3@1199
   134
kpeter@1201
   135
          if (degree[u] <= 1 && degree[v] <= 1) {
kpeter@1201
   136
            if (union_find.join(u, v)) {
kpeter@1201
   137
              const int uid = _gr.id(u),
kpeter@1201
   138
                        vid = _gr.id(v);
kpeter@1201
   139
kpeter@1201
   140
              plist[uid*2 + degree[u]] = vid;
kpeter@1201
   141
              plist[vid*2 + degree[v]] = uid;
kpeter@1201
   142
f4c3@1199
   143
              ++degree[u];
f4c3@1199
   144
              ++degree[v];
f4c3@1199
   145
              ++nodesNum;
f4c3@1199
   146
            }
f4c3@1199
   147
          }
f4c3@1199
   148
        }
f4c3@1199
   149
f4c3@1199
   150
        for (int i=0, n=-1; i<_gr.nodeNum()*2; ++i) {
kpeter@1201
   151
          if (plist[i] == -1) {
f4c3@1199
   152
            if (n==-1) {
f4c3@1199
   153
              n = i;
f4c3@1199
   154
            } else {
kpeter@1201
   155
              plist[n] = i/2;
kpeter@1201
   156
              plist[i] = n/2;
f4c3@1199
   157
              break;
f4c3@1199
   158
            }
f4c3@1199
   159
          }
f4c3@1199
   160
        }
f4c3@1199
   161
kpeter@1201
   162
        for (int i=0, next=0, last=-1; i!=_gr.nodeNum(); ++i) {
kpeter@1201
   163
          _path.push_back(_gr.nodeFromId(next));
kpeter@1201
   164
          if (plist[2*next] != last) {
kpeter@1201
   165
            last = next;
kpeter@1201
   166
            next = plist[2*next];
f4c3@1199
   167
          } else {
kpeter@1201
   168
            last = next;
kpeter@1201
   169
            next = plist[2*next+1];
f4c3@1199
   170
          }
f4c3@1199
   171
        }
f4c3@1199
   172
kpeter@1201
   173
        _sum = _cost[_gr.edge(_path.back(), _path.front())];
kpeter@1201
   174
        for (int i = 0; i < int(_path.size())-1; ++i) {
kpeter@1201
   175
          _sum += _cost[_gr.edge(_path[i], _path[i+1])];
kpeter@1201
   176
        }
f4c3@1199
   177
f4c3@1199
   178
        return _sum;
f4c3@1199
   179
      }
f4c3@1199
   180
kpeter@1201
   181
      /// @}
f4c3@1199
   182
kpeter@1201
   183
      /// \name Query Functions
kpeter@1201
   184
      /// @{
f4c3@1199
   185
kpeter@1201
   186
      /// \brief The total cost of the found tour.
kpeter@1201
   187
      ///
kpeter@1201
   188
      /// This function returns the total cost of the found tour.
kpeter@1201
   189
      ///
kpeter@1201
   190
      /// \pre run() must be called before using this function.
kpeter@1201
   191
      Cost tourCost() const {
f4c3@1199
   192
        return _sum;
f4c3@1199
   193
      }
f4c3@1199
   194
kpeter@1201
   195
      /// \brief Returns a const reference to the node sequence of the
kpeter@1201
   196
      /// found tour.
kpeter@1201
   197
      ///
kpeter@1202
   198
      /// This function returns a const reference to a vector
kpeter@1201
   199
      /// that stores the node sequence of the found tour.
kpeter@1201
   200
      ///
kpeter@1201
   201
      /// \pre run() must be called before using this function.
kpeter@1201
   202
      const std::vector<Node>& tourNodes() const {
kpeter@1201
   203
        return _path;
kpeter@1201
   204
      }
kpeter@1201
   205
kpeter@1201
   206
      /// \brief Gives back the node sequence of the found tour.
kpeter@1201
   207
      ///
kpeter@1201
   208
      /// This function copies the node sequence of the found tour into
kpeter@1205
   209
      /// an STL container through the given output iterator. The
kpeter@1205
   210
      /// <tt>value_type</tt> of the container must be <tt>FullGraph::Node</tt>.
kpeter@1205
   211
      /// For example,
kpeter@1205
   212
      /// \code
kpeter@1205
   213
      /// std::vector<FullGraph::Node> nodes(countNodes(graph));
kpeter@1205
   214
      /// tsp.tourNodes(nodes.begin());
kpeter@1205
   215
      /// \endcode
kpeter@1205
   216
      /// or
kpeter@1205
   217
      /// \code
kpeter@1205
   218
      /// std::list<FullGraph::Node> nodes;
kpeter@1205
   219
      /// tsp.tourNodes(std::back_inserter(nodes));
kpeter@1205
   220
      /// \endcode
kpeter@1201
   221
      ///
kpeter@1201
   222
      /// \pre run() must be called before using this function.
kpeter@1205
   223
      template <typename Iterator>
kpeter@1205
   224
      void tourNodes(Iterator out) const {
kpeter@1205
   225
        std::copy(_path.begin(), _path.end(), out);
kpeter@1201
   226
      }
kpeter@1201
   227
kpeter@1201
   228
      /// \brief Gives back the found tour as a path.
kpeter@1201
   229
      ///
kpeter@1201
   230
      /// This function copies the found tour as a list of arcs/edges into
alpar@1250
   231
      /// the given \ref lemon::concepts::Path "path structure".
kpeter@1201
   232
      ///
kpeter@1201
   233
      /// \pre run() must be called before using this function.
kpeter@1201
   234
      template <typename Path>
kpeter@1201
   235
      void tour(Path &path) const {
kpeter@1201
   236
        path.clear();
kpeter@1201
   237
        for (int i = 0; i < int(_path.size()) - 1; ++i) {
kpeter@1201
   238
          path.addBack(_gr.arc(_path[i], _path[i+1]));
kpeter@1201
   239
        }
kpeter@1201
   240
        if (int(_path.size()) >= 2) {
kpeter@1201
   241
          path.addBack(_gr.arc(_path.back(), _path.front()));
kpeter@1201
   242
        }
kpeter@1201
   243
      }
kpeter@1201
   244
kpeter@1201
   245
      /// @}
kpeter@1201
   246
f4c3@1199
   247
  };
f4c3@1199
   248
f4c3@1199
   249
}; // namespace lemon
f4c3@1199
   250
f4c3@1199
   251
#endif