lemon/nearest_neighbor_tsp.h
author Peter Kovacs <kpeter@inf.elte.hu>
Thu, 01 Nov 2018 11:27:05 +0100
changeset 1197 f179aa1045a4
parent 1092 dceba191c00d
permissions -rw-r--r--
Suppress unused typdef warnings (#615)
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_NEAREST_NEIGHBOUR_TSP_H
f4c3@1031
    20
#define LEMON_NEAREST_NEIGHBOUR_TSP_H
f4c3@1031
    21
kpeter@1033
    22
/// \ingroup tsp
kpeter@1033
    23
/// \file
kpeter@1033
    24
/// \brief Nearest neighbor algorithm for symmetric TSP
kpeter@1033
    25
f4c3@1031
    26
#include <deque>
kpeter@1034
    27
#include <vector>
kpeter@1033
    28
#include <limits>
f4c3@1031
    29
#include <lemon/full_graph.h>
f4c3@1031
    30
#include <lemon/maps.h>
f4c3@1031
    31
f4c3@1031
    32
namespace lemon {
f4c3@1031
    33
kpeter@1034
    34
  /// \ingroup tsp
kpeter@1034
    35
  ///
kpeter@1033
    36
  /// \brief Nearest neighbor algorithm for symmetric TSP.
kpeter@1033
    37
  ///
kpeter@1033
    38
  /// NearestNeighborTsp implements the nearest neighbor heuristic for solving
kpeter@1033
    39
  /// symmetric \ref tsp "TSP".
kpeter@1033
    40
  ///
kpeter@1033
    41
  /// This is probably the simplest TSP heuristic.
kpeter@1033
    42
  /// It starts with a minimum cost edge and at each step, it connects the
kpeter@1033
    43
  /// nearest unvisited node to the current path.
kpeter@1033
    44
  /// Finally, it connects the two end points of the path to form a tour.
kpeter@1033
    45
  ///
kpeter@1033
    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.
f4c3@1031
    52
  template <typename CM>
kpeter@1033
    53
  class NearestNeighborTsp
kpeter@1033
    54
  {
kpeter@1033
    55
    public:
kpeter@1033
    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
f4c3@1031
    62
    private:
kpeter@1033
    63
f4c3@1031
    64
      GRAPH_TYPEDEFS(FullGraph);
f4c3@1031
    65
kpeter@1033
    66
      const FullGraph &_gr;
kpeter@1033
    67
      const CostMap &_cost;
kpeter@1033
    68
      Cost _sum;
kpeter@1034
    69
      std::vector<Node> _path;
kpeter@1033
    70
f4c3@1031
    71
    public:
f4c3@1031
    72
kpeter@1033
    73
      /// \brief Constructor
kpeter@1033
    74
      ///
kpeter@1033
    75
      /// Constructor.
kpeter@1033
    76
      /// \param gr The \ref FullGraph "full graph" the algorithm runs on.
kpeter@1033
    77
      /// \param cost The cost map.
kpeter@1033
    78
      NearestNeighborTsp(const FullGraph &gr, const CostMap &cost)
kpeter@1033
    79
        : _gr(gr), _cost(cost) {}
kpeter@1033
    80
kpeter@1033
    81
      /// \name Execution Control
kpeter@1033
    82
      /// @{
kpeter@1033
    83
kpeter@1033
    84
      /// \brief Runs the algorithm.
kpeter@1033
    85
      ///
kpeter@1033
    86
      /// This function runs the algorithm.
kpeter@1033
    87
      ///
kpeter@1033
    88
      /// \return The total cost of the found tour.
f4c3@1031
    89
      Cost run() {
f4c3@1031
    90
        _path.clear();
kpeter@1034
    91
        if (_gr.nodeNum() == 0) {
kpeter@1034
    92
          return _sum = 0;
kpeter@1034
    93
        }
kpeter@1033
    94
        else if (_gr.nodeNum() == 1) {
kpeter@1033
    95
          _path.push_back(_gr(0));
kpeter@1033
    96
          return _sum = 0;
kpeter@1033
    97
        }
kpeter@1033
    98
kpeter@1034
    99
        std::deque<Node> path_dq;
f4c3@1031
   100
        Edge min_edge1 = INVALID,
f4c3@1031
   101
             min_edge2 = INVALID;
kpeter@1033
   102
f4c3@1031
   103
        min_edge1 = mapMin(_gr, _cost);
kpeter@1033
   104
        Node n1 = _gr.u(min_edge1),
f4c3@1031
   105
             n2 = _gr.v(min_edge1);
kpeter@1034
   106
        path_dq.push_back(n1);
kpeter@1034
   107
        path_dq.push_back(n2);
f4c3@1031
   108
kpeter@1033
   109
        FullGraph::NodeMap<bool> used(_gr, false);
f4c3@1031
   110
        used[n1] = true;
f4c3@1031
   111
        used[n2] = true;
f4c3@1031
   112
f4c3@1031
   113
        min_edge1 = INVALID;
kpeter@1034
   114
        while (int(path_dq.size()) != _gr.nodeNum()) {
f4c3@1031
   115
          if (min_edge1 == INVALID) {
kpeter@1033
   116
            for (IncEdgeIt e(_gr, n1); e != INVALID; ++e) {
kpeter@1033
   117
              if (!used[_gr.runningNode(e)] &&
alpar@1101
   118
                  (min_edge1 == INVALID || _cost[e] < _cost[min_edge1])) {
kpeter@1033
   119
                min_edge1 = e;
f4c3@1031
   120
              }
f4c3@1031
   121
            }
f4c3@1031
   122
          }
f4c3@1031
   123
f4c3@1031
   124
          if (min_edge2 == INVALID) {
kpeter@1033
   125
            for (IncEdgeIt e(_gr, n2); e != INVALID; ++e) {
kpeter@1033
   126
              if (!used[_gr.runningNode(e)] &&
alpar@1101
   127
                  (min_edge2 == INVALID||_cost[e] < _cost[min_edge2])) {
kpeter@1033
   128
                min_edge2 = e;
f4c3@1031
   129
              }
f4c3@1031
   130
            }
f4c3@1031
   131
          }
f4c3@1031
   132
kpeter@1033
   133
          if (_cost[min_edge1] < _cost[min_edge2]) {
kpeter@1033
   134
            n1 = _gr.oppositeNode(n1, min_edge1);
kpeter@1034
   135
            path_dq.push_front(n1);
f4c3@1031
   136
f4c3@1031
   137
            used[n1] = true;
f4c3@1031
   138
            min_edge1 = INVALID;
f4c3@1031
   139
kpeter@1033
   140
            if (_gr.u(min_edge2) == n1 || _gr.v(min_edge2) == n1)
f4c3@1031
   141
              min_edge2 = INVALID;
f4c3@1031
   142
          } else {
kpeter@1033
   143
            n2 = _gr.oppositeNode(n2, min_edge2);
kpeter@1034
   144
            path_dq.push_back(n2);
f4c3@1031
   145
f4c3@1031
   146
            used[n2] = true;
f4c3@1031
   147
            min_edge2 = INVALID;
f4c3@1031
   148
kpeter@1033
   149
            if (_gr.u(min_edge1) == n2 || _gr.v(min_edge1) == n2)
f4c3@1031
   150
              min_edge1 = INVALID;
f4c3@1031
   151
          }
f4c3@1031
   152
        }
f4c3@1031
   153
kpeter@1034
   154
        n1 = path_dq.back();
kpeter@1034
   155
        n2 = path_dq.front();
kpeter@1034
   156
        _path.push_back(n2);
kpeter@1034
   157
        _sum = _cost[_gr.edge(n1, n2)];
kpeter@1034
   158
        for (int i = 1; i < int(path_dq.size()); ++i) {
kpeter@1034
   159
          n1 = n2;
kpeter@1034
   160
          n2 = path_dq[i];
kpeter@1034
   161
          _path.push_back(n2);
kpeter@1034
   162
          _sum += _cost[_gr.edge(n1, n2)];
kpeter@1033
   163
        }
f4c3@1031
   164
f4c3@1031
   165
        return _sum;
f4c3@1031
   166
      }
f4c3@1031
   167
kpeter@1033
   168
      /// @}
kpeter@1033
   169
kpeter@1033
   170
      /// \name Query Functions
kpeter@1033
   171
      /// @{
kpeter@1033
   172
kpeter@1033
   173
      /// \brief The total cost of the found tour.
kpeter@1033
   174
      ///
kpeter@1033
   175
      /// This function returns the total cost of the found tour.
kpeter@1033
   176
      ///
kpeter@1033
   177
      /// \pre run() must be called before using this function.
kpeter@1033
   178
      Cost tourCost() const {
kpeter@1033
   179
        return _sum;
f4c3@1031
   180
      }
f4c3@1031
   181
kpeter@1033
   182
      /// \brief Returns a const reference to the node sequence of the
kpeter@1033
   183
      /// found tour.
kpeter@1033
   184
      ///
kpeter@1034
   185
      /// This function returns a const reference to a vector
kpeter@1033
   186
      /// that stores the node sequence of the found tour.
kpeter@1033
   187
      ///
kpeter@1033
   188
      /// \pre run() must be called before using this function.
kpeter@1034
   189
      const std::vector<Node>& tourNodes() const {
f4c3@1031
   190
        return _path;
f4c3@1031
   191
      }
kpeter@1033
   192
kpeter@1033
   193
      /// \brief Gives back the node sequence of the found tour.
kpeter@1033
   194
      ///
kpeter@1033
   195
      /// This function copies the node sequence of the found tour into
kpeter@1037
   196
      /// an STL container through the given output iterator. The
kpeter@1037
   197
      /// <tt>value_type</tt> of the container must be <tt>FullGraph::Node</tt>.
kpeter@1037
   198
      /// For example,
kpeter@1037
   199
      /// \code
kpeter@1037
   200
      /// std::vector<FullGraph::Node> nodes(countNodes(graph));
kpeter@1037
   201
      /// tsp.tourNodes(nodes.begin());
kpeter@1037
   202
      /// \endcode
kpeter@1037
   203
      /// or
kpeter@1037
   204
      /// \code
kpeter@1037
   205
      /// std::list<FullGraph::Node> nodes;
kpeter@1037
   206
      /// tsp.tourNodes(std::back_inserter(nodes));
kpeter@1037
   207
      /// \endcode
kpeter@1033
   208
      ///
kpeter@1033
   209
      /// \pre run() must be called before using this function.
kpeter@1037
   210
      template <typename Iterator>
kpeter@1037
   211
      void tourNodes(Iterator out) const {
kpeter@1037
   212
        std::copy(_path.begin(), _path.end(), out);
kpeter@1033
   213
      }
kpeter@1033
   214
kpeter@1033
   215
      /// \brief Gives back the found tour as a path.
kpeter@1033
   216
      ///
kpeter@1033
   217
      /// This function copies the found tour as a list of arcs/edges into
alpar@1074
   218
      /// the given \ref lemon::concepts::Path "path structure".
kpeter@1033
   219
      ///
kpeter@1033
   220
      /// \pre run() must be called before using this function.
kpeter@1033
   221
      template <typename Path>
kpeter@1033
   222
      void tour(Path &path) const {
kpeter@1033
   223
        path.clear();
kpeter@1033
   224
        for (int i = 0; i < int(_path.size()) - 1; ++i) {
kpeter@1033
   225
          path.addBack(_gr.arc(_path[i], _path[i+1]));
f4c3@1031
   226
        }
kpeter@1033
   227
        if (int(_path.size()) >= 2) {
kpeter@1033
   228
          path.addBack(_gr.arc(_path.back(), _path.front()));
kpeter@1033
   229
        }
f4c3@1031
   230
      }
f4c3@1031
   231
kpeter@1033
   232
      /// @}
kpeter@1033
   233
f4c3@1031
   234
  };
f4c3@1031
   235
f4c3@1031
   236
}; // namespace lemon
f4c3@1031
   237
f4c3@1031
   238
#endif