lemon/nearest_neighbor_tsp.h
author Peter Kovacs <kpeter@inf.elte.hu>
Sat, 08 Jan 2011 22:51:16 +0100
changeset 1033 9a51db038228
parent 1031 ae0b056593a7
child 1034 ef200e268af2
permissions -rw-r--r--
Document and greatly improve TSP algorithms (#386)

- Add LEMON headers.
- Add Doxygen doc for all classes and their members.
- Clarify and unify the public API of the algorithms.
- Various small improvements in the implementations to make
them clearer and faster.
- Avoid using adaptors in ChristofidesTsp.
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@1033
    27
#include <limits>
f4c3@1031
    28
#include <lemon/full_graph.h>
f4c3@1031
    29
#include <lemon/maps.h>
f4c3@1031
    30
f4c3@1031
    31
namespace lemon {
f4c3@1031
    32
kpeter@1033
    33
  /// \brief Nearest neighbor algorithm for symmetric TSP.
kpeter@1033
    34
  ///
kpeter@1033
    35
  /// NearestNeighborTsp implements the nearest neighbor heuristic for solving
kpeter@1033
    36
  /// symmetric \ref tsp "TSP".
kpeter@1033
    37
  ///
kpeter@1033
    38
  /// This is probably the simplest TSP heuristic.
kpeter@1033
    39
  /// It starts with a minimum cost edge and at each step, it connects the
kpeter@1033
    40
  /// nearest unvisited node to the current path.
kpeter@1033
    41
  /// Finally, it connects the two end points of the path to form a tour.
kpeter@1033
    42
  ///
kpeter@1033
    43
  /// This method runs in O(n<sup>2</sup>) time.
kpeter@1033
    44
  /// It quickly finds an effectively short tour for most TSP
kpeter@1033
    45
  /// instances, but in special cases, it could yield a really bad
kpeter@1033
    46
  /// (or even the worst) solution.
kpeter@1033
    47
  ///
kpeter@1033
    48
  /// \tparam CM Type of the cost map.
f4c3@1031
    49
  template <typename CM>
kpeter@1033
    50
  class NearestNeighborTsp
kpeter@1033
    51
  {
kpeter@1033
    52
    public:
kpeter@1033
    53
kpeter@1033
    54
      /// Type of the cost map
kpeter@1033
    55
      typedef CM CostMap;
kpeter@1033
    56
      /// Type of the edge costs
kpeter@1033
    57
      typedef typename CM::Value Cost;
kpeter@1033
    58
f4c3@1031
    59
    private:
kpeter@1033
    60
f4c3@1031
    61
      GRAPH_TYPEDEFS(FullGraph);
f4c3@1031
    62
kpeter@1033
    63
      const FullGraph &_gr;
kpeter@1033
    64
      const CostMap &_cost;
kpeter@1033
    65
      Cost _sum;
kpeter@1033
    66
      std::deque<Node> _path;
kpeter@1033
    67
f4c3@1031
    68
    public:
f4c3@1031
    69
kpeter@1033
    70
      /// \brief Constructor
kpeter@1033
    71
      ///
kpeter@1033
    72
      /// Constructor.
kpeter@1033
    73
      /// \param gr The \ref FullGraph "full graph" the algorithm runs on.
kpeter@1033
    74
      /// \param cost The cost map.
kpeter@1033
    75
      NearestNeighborTsp(const FullGraph &gr, const CostMap &cost)
kpeter@1033
    76
        : _gr(gr), _cost(cost) {}
kpeter@1033
    77
kpeter@1033
    78
      /// \name Execution Control
kpeter@1033
    79
      /// @{
kpeter@1033
    80
kpeter@1033
    81
      /// \brief Runs the algorithm.
kpeter@1033
    82
      ///
kpeter@1033
    83
      /// This function runs the algorithm.
kpeter@1033
    84
      ///
kpeter@1033
    85
      /// \return The total cost of the found tour.
f4c3@1031
    86
      Cost run() {
f4c3@1031
    87
        _path.clear();
f4c3@1031
    88
kpeter@1033
    89
        if (_gr.nodeNum() == 0) return _sum = 0;
kpeter@1033
    90
        else if (_gr.nodeNum() == 1) {
kpeter@1033
    91
          _path.push_back(_gr(0));
kpeter@1033
    92
          return _sum = 0;
kpeter@1033
    93
        }
kpeter@1033
    94
f4c3@1031
    95
        Edge min_edge1 = INVALID,
f4c3@1031
    96
             min_edge2 = INVALID;
kpeter@1033
    97
f4c3@1031
    98
        min_edge1 = mapMin(_gr, _cost);
kpeter@1033
    99
        Node n1 = _gr.u(min_edge1),
f4c3@1031
   100
             n2 = _gr.v(min_edge1);
f4c3@1031
   101
        _path.push_back(n1);
f4c3@1031
   102
        _path.push_back(n2);
f4c3@1031
   103
kpeter@1033
   104
        FullGraph::NodeMap<bool> used(_gr, false);
f4c3@1031
   105
        used[n1] = true;
f4c3@1031
   106
        used[n2] = true;
f4c3@1031
   107
f4c3@1031
   108
        min_edge1 = INVALID;
f4c3@1031
   109
        while (int(_path.size()) != _gr.nodeNum()) {
f4c3@1031
   110
          if (min_edge1 == INVALID) {
kpeter@1033
   111
            for (IncEdgeIt e(_gr, n1); e != INVALID; ++e) {
kpeter@1033
   112
              if (!used[_gr.runningNode(e)] &&
kpeter@1033
   113
                  (_cost[e] < _cost[min_edge1] || min_edge1 == INVALID)) {
kpeter@1033
   114
                min_edge1 = e;
f4c3@1031
   115
              }
f4c3@1031
   116
            }
f4c3@1031
   117
          }
f4c3@1031
   118
f4c3@1031
   119
          if (min_edge2 == INVALID) {
kpeter@1033
   120
            for (IncEdgeIt e(_gr, n2); e != INVALID; ++e) {
kpeter@1033
   121
              if (!used[_gr.runningNode(e)] &&
kpeter@1033
   122
                  (_cost[e] < _cost[min_edge2] || min_edge2 == INVALID)) {
kpeter@1033
   123
                min_edge2 = e;
f4c3@1031
   124
              }
f4c3@1031
   125
            }
f4c3@1031
   126
          }
f4c3@1031
   127
kpeter@1033
   128
          if (_cost[min_edge1] < _cost[min_edge2]) {
kpeter@1033
   129
            n1 = _gr.oppositeNode(n1, min_edge1);
f4c3@1031
   130
            _path.push_front(n1);
f4c3@1031
   131
f4c3@1031
   132
            used[n1] = true;
f4c3@1031
   133
            min_edge1 = INVALID;
f4c3@1031
   134
kpeter@1033
   135
            if (_gr.u(min_edge2) == n1 || _gr.v(min_edge2) == n1)
f4c3@1031
   136
              min_edge2 = INVALID;
f4c3@1031
   137
          } else {
kpeter@1033
   138
            n2 = _gr.oppositeNode(n2, min_edge2);
f4c3@1031
   139
            _path.push_back(n2);
f4c3@1031
   140
f4c3@1031
   141
            used[n2] = true;
f4c3@1031
   142
            min_edge2 = INVALID;
f4c3@1031
   143
kpeter@1033
   144
            if (_gr.u(min_edge1) == n2 || _gr.v(min_edge1) == n2)
f4c3@1031
   145
              min_edge1 = INVALID;
f4c3@1031
   146
          }
f4c3@1031
   147
        }
f4c3@1031
   148
kpeter@1033
   149
        _sum = _cost[_gr.edge(_path.back(), _path.front())];
kpeter@1033
   150
        for (int i = 0; i < int(_path.size())-1; ++i) {
kpeter@1033
   151
          _sum += _cost[_gr.edge(_path[i], _path[i+1])];
kpeter@1033
   152
        }
f4c3@1031
   153
f4c3@1031
   154
        return _sum;
f4c3@1031
   155
      }
f4c3@1031
   156
kpeter@1033
   157
      /// @}
kpeter@1033
   158
kpeter@1033
   159
      /// \name Query Functions
kpeter@1033
   160
      /// @{
kpeter@1033
   161
kpeter@1033
   162
      /// \brief The total cost of the found tour.
kpeter@1033
   163
      ///
kpeter@1033
   164
      /// This function returns the total cost of the found tour.
kpeter@1033
   165
      ///
kpeter@1033
   166
      /// \pre run() must be called before using this function.
kpeter@1033
   167
      Cost tourCost() const {
kpeter@1033
   168
        return _sum;
f4c3@1031
   169
      }
f4c3@1031
   170
kpeter@1033
   171
      /// \brief Returns a const reference to the node sequence of the
kpeter@1033
   172
      /// found tour.
kpeter@1033
   173
      ///
kpeter@1033
   174
      /// This function returns a const reference to the internal structure
kpeter@1033
   175
      /// that stores the node sequence of the found tour.
kpeter@1033
   176
      ///
kpeter@1033
   177
      /// \pre run() must be called before using this function.
kpeter@1033
   178
      const std::deque<Node>& tourNodes() const {
f4c3@1031
   179
        return _path;
f4c3@1031
   180
      }
kpeter@1033
   181
kpeter@1033
   182
      /// \brief Gives back the node sequence of the found tour.
kpeter@1033
   183
      ///
kpeter@1033
   184
      /// This function copies the node sequence of the found tour into
kpeter@1033
   185
      /// the given standard container.
kpeter@1033
   186
      ///
kpeter@1033
   187
      /// \pre run() must be called before using this function.
kpeter@1033
   188
      template <typename Container>
kpeter@1033
   189
      void tourNodes(Container &container) const {
kpeter@1033
   190
        container.assign(_path.begin(), _path.end());
kpeter@1033
   191
      }
kpeter@1033
   192
kpeter@1033
   193
      /// \brief Gives back the found tour as a path.
kpeter@1033
   194
      ///
kpeter@1033
   195
      /// This function copies the found tour as a list of arcs/edges into
kpeter@1033
   196
      /// the given \ref concept::Path "path structure".
kpeter@1033
   197
      ///
kpeter@1033
   198
      /// \pre run() must be called before using this function.
kpeter@1033
   199
      template <typename Path>
kpeter@1033
   200
      void tour(Path &path) const {
kpeter@1033
   201
        path.clear();
kpeter@1033
   202
        for (int i = 0; i < int(_path.size()) - 1; ++i) {
kpeter@1033
   203
          path.addBack(_gr.arc(_path[i], _path[i+1]));
f4c3@1031
   204
        }
kpeter@1033
   205
        if (int(_path.size()) >= 2) {
kpeter@1033
   206
          path.addBack(_gr.arc(_path.back(), _path.front()));
kpeter@1033
   207
        }
f4c3@1031
   208
      }
f4c3@1031
   209
kpeter@1033
   210
      /// @}
kpeter@1033
   211
f4c3@1031
   212
  };
f4c3@1031
   213
f4c3@1031
   214
}; // namespace lemon
f4c3@1031
   215
f4c3@1031
   216
#endif