lemon/greedy_tsp.h
author Alpar Juttner <alpar@cs.elte.hu>
Wed, 01 Apr 2015 18:13:30 +0200
changeset 1121 1d80ec7d17eb
parent 1074 97d978243703
permissions -rw-r--r--
Remove GCC_VERSION define (#536)

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