lemon/nearest_neighbor_tsp.h
author Peter Kovacs <kpeter@inf.elte.hu>
Sun, 09 Jan 2011 00:56:52 +0100
changeset 1034 ef200e268af2
parent 1033 9a51db038228
child 1036 dff32ce3db71
permissions -rw-r--r--
Unifications and improvements in TSP algorithms (#386)
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
 *
kpeter@1033
     5
 * Copyright (C) 2003-2010
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@1034
    47
  /// It quickly finds a short tour for most TSP instances, but in special
kpeter@1034
    48
  /// cases, it could yield a really bad (or even the worst) solution.
kpeter@1033
    49
  ///
kpeter@1033
    50
  /// \tparam CM Type of the cost map.
f4c3@1031
    51
  template <typename CM>
kpeter@1033
    52
  class NearestNeighborTsp
kpeter@1033
    53
  {
kpeter@1033
    54
    public:
kpeter@1033
    55
kpeter@1033
    56
      /// Type of the cost map
kpeter@1033
    57
      typedef CM CostMap;
kpeter@1033
    58
      /// Type of the edge costs
kpeter@1033
    59
      typedef typename CM::Value Cost;
kpeter@1033
    60
f4c3@1031
    61
    private:
kpeter@1033
    62
f4c3@1031
    63
      GRAPH_TYPEDEFS(FullGraph);
f4c3@1031
    64
kpeter@1033
    65
      const FullGraph &_gr;
kpeter@1033
    66
      const CostMap &_cost;
kpeter@1033
    67
      Cost _sum;
kpeter@1034
    68
      std::vector<Node> _path;
kpeter@1033
    69
f4c3@1031
    70
    public:
f4c3@1031
    71
kpeter@1033
    72
      /// \brief Constructor
kpeter@1033
    73
      ///
kpeter@1033
    74
      /// Constructor.
kpeter@1033
    75
      /// \param gr The \ref FullGraph "full graph" the algorithm runs on.
kpeter@1033
    76
      /// \param cost The cost map.
kpeter@1033
    77
      NearestNeighborTsp(const FullGraph &gr, const CostMap &cost)
kpeter@1033
    78
        : _gr(gr), _cost(cost) {}
kpeter@1033
    79
kpeter@1033
    80
      /// \name Execution Control
kpeter@1033
    81
      /// @{
kpeter@1033
    82
kpeter@1033
    83
      /// \brief Runs the algorithm.
kpeter@1033
    84
      ///
kpeter@1033
    85
      /// This function runs the algorithm.
kpeter@1033
    86
      ///
kpeter@1033
    87
      /// \return The total cost of the found tour.
f4c3@1031
    88
      Cost run() {
f4c3@1031
    89
        _path.clear();
kpeter@1034
    90
        if (_gr.nodeNum() == 0) {
kpeter@1034
    91
          return _sum = 0;
kpeter@1034
    92
        }
kpeter@1033
    93
        else if (_gr.nodeNum() == 1) {
kpeter@1033
    94
          _path.push_back(_gr(0));
kpeter@1033
    95
          return _sum = 0;
kpeter@1033
    96
        }
kpeter@1033
    97
kpeter@1034
    98
        std::deque<Node> path_dq;
f4c3@1031
    99
        Edge min_edge1 = INVALID,
f4c3@1031
   100
             min_edge2 = INVALID;
kpeter@1033
   101
f4c3@1031
   102
        min_edge1 = mapMin(_gr, _cost);
kpeter@1033
   103
        Node n1 = _gr.u(min_edge1),
f4c3@1031
   104
             n2 = _gr.v(min_edge1);
kpeter@1034
   105
        path_dq.push_back(n1);
kpeter@1034
   106
        path_dq.push_back(n2);
f4c3@1031
   107
kpeter@1033
   108
        FullGraph::NodeMap<bool> used(_gr, false);
f4c3@1031
   109
        used[n1] = true;
f4c3@1031
   110
        used[n2] = true;
f4c3@1031
   111
f4c3@1031
   112
        min_edge1 = INVALID;
kpeter@1034
   113
        while (int(path_dq.size()) != _gr.nodeNum()) {
f4c3@1031
   114
          if (min_edge1 == INVALID) {
kpeter@1033
   115
            for (IncEdgeIt e(_gr, n1); e != INVALID; ++e) {
kpeter@1033
   116
              if (!used[_gr.runningNode(e)] &&
kpeter@1033
   117
                  (_cost[e] < _cost[min_edge1] || min_edge1 == INVALID)) {
kpeter@1033
   118
                min_edge1 = e;
f4c3@1031
   119
              }
f4c3@1031
   120
            }
f4c3@1031
   121
          }
f4c3@1031
   122
f4c3@1031
   123
          if (min_edge2 == INVALID) {
kpeter@1033
   124
            for (IncEdgeIt e(_gr, n2); e != INVALID; ++e) {
kpeter@1033
   125
              if (!used[_gr.runningNode(e)] &&
kpeter@1033
   126
                  (_cost[e] < _cost[min_edge2] || min_edge2 == INVALID)) {
kpeter@1033
   127
                min_edge2 = e;
f4c3@1031
   128
              }
f4c3@1031
   129
            }
f4c3@1031
   130
          }
f4c3@1031
   131
kpeter@1033
   132
          if (_cost[min_edge1] < _cost[min_edge2]) {
kpeter@1033
   133
            n1 = _gr.oppositeNode(n1, min_edge1);
kpeter@1034
   134
            path_dq.push_front(n1);
f4c3@1031
   135
f4c3@1031
   136
            used[n1] = true;
f4c3@1031
   137
            min_edge1 = INVALID;
f4c3@1031
   138
kpeter@1033
   139
            if (_gr.u(min_edge2) == n1 || _gr.v(min_edge2) == n1)
f4c3@1031
   140
              min_edge2 = INVALID;
f4c3@1031
   141
          } else {
kpeter@1033
   142
            n2 = _gr.oppositeNode(n2, min_edge2);
kpeter@1034
   143
            path_dq.push_back(n2);
f4c3@1031
   144
f4c3@1031
   145
            used[n2] = true;
f4c3@1031
   146
            min_edge2 = INVALID;
f4c3@1031
   147
kpeter@1033
   148
            if (_gr.u(min_edge1) == n2 || _gr.v(min_edge1) == n2)
f4c3@1031
   149
              min_edge1 = INVALID;
f4c3@1031
   150
          }
f4c3@1031
   151
        }
f4c3@1031
   152
kpeter@1034
   153
        n1 = path_dq.back();
kpeter@1034
   154
        n2 = path_dq.front();
kpeter@1034
   155
        _path.push_back(n2);
kpeter@1034
   156
        _sum = _cost[_gr.edge(n1, n2)];
kpeter@1034
   157
        for (int i = 1; i < int(path_dq.size()); ++i) {
kpeter@1034
   158
          n1 = n2;
kpeter@1034
   159
          n2 = path_dq[i];
kpeter@1034
   160
          _path.push_back(n2);
kpeter@1034
   161
          _sum += _cost[_gr.edge(n1, n2)];
kpeter@1033
   162
        }
f4c3@1031
   163
f4c3@1031
   164
        return _sum;
f4c3@1031
   165
      }
f4c3@1031
   166
kpeter@1033
   167
      /// @}
kpeter@1033
   168
kpeter@1033
   169
      /// \name Query Functions
kpeter@1033
   170
      /// @{
kpeter@1033
   171
kpeter@1033
   172
      /// \brief The total cost of the found tour.
kpeter@1033
   173
      ///
kpeter@1033
   174
      /// This function returns the total cost of the found tour.
kpeter@1033
   175
      ///
kpeter@1033
   176
      /// \pre run() must be called before using this function.
kpeter@1033
   177
      Cost tourCost() const {
kpeter@1033
   178
        return _sum;
f4c3@1031
   179
      }
f4c3@1031
   180
kpeter@1033
   181
      /// \brief Returns a const reference to the node sequence of the
kpeter@1033
   182
      /// found tour.
kpeter@1033
   183
      ///
kpeter@1034
   184
      /// This function returns a const reference to a vector
kpeter@1033
   185
      /// that stores the node sequence of the found tour.
kpeter@1033
   186
      ///
kpeter@1033
   187
      /// \pre run() must be called before using this function.
kpeter@1034
   188
      const std::vector<Node>& tourNodes() const {
f4c3@1031
   189
        return _path;
f4c3@1031
   190
      }
kpeter@1033
   191
kpeter@1033
   192
      /// \brief Gives back the node sequence of the found tour.
kpeter@1033
   193
      ///
kpeter@1033
   194
      /// This function copies the node sequence of the found tour into
kpeter@1033
   195
      /// the given standard container.
kpeter@1033
   196
      ///
kpeter@1033
   197
      /// \pre run() must be called before using this function.
kpeter@1033
   198
      template <typename Container>
kpeter@1033
   199
      void tourNodes(Container &container) const {
kpeter@1033
   200
        container.assign(_path.begin(), _path.end());
kpeter@1033
   201
      }
kpeter@1033
   202
kpeter@1033
   203
      /// \brief Gives back the found tour as a path.
kpeter@1033
   204
      ///
kpeter@1033
   205
      /// This function copies the found tour as a list of arcs/edges into
kpeter@1033
   206
      /// the given \ref concept::Path "path structure".
kpeter@1033
   207
      ///
kpeter@1033
   208
      /// \pre run() must be called before using this function.
kpeter@1033
   209
      template <typename Path>
kpeter@1033
   210
      void tour(Path &path) const {
kpeter@1033
   211
        path.clear();
kpeter@1033
   212
        for (int i = 0; i < int(_path.size()) - 1; ++i) {
kpeter@1033
   213
          path.addBack(_gr.arc(_path[i], _path[i+1]));
f4c3@1031
   214
        }
kpeter@1033
   215
        if (int(_path.size()) >= 2) {
kpeter@1033
   216
          path.addBack(_gr.arc(_path.back(), _path.front()));
kpeter@1033
   217
        }
f4c3@1031
   218
      }
f4c3@1031
   219
kpeter@1033
   220
      /// @}
kpeter@1033
   221
f4c3@1031
   222
  };
f4c3@1031
   223
f4c3@1031
   224
}; // namespace lemon
f4c3@1031
   225
f4c3@1031
   226
#endif