lemon/opt2_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_OPT2_TSP_H
f4c3@1031
    20
#define LEMON_OPT2_TSP_H
f4c3@1031
    21
kpeter@1033
    22
/// \ingroup tsp
kpeter@1033
    23
/// \file
kpeter@1033
    24
/// \brief 2-opt algorithm for symmetric TSP
kpeter@1033
    25
f4c3@1031
    26
#include <vector>
f4c3@1031
    27
#include <lemon/full_graph.h>
f4c3@1031
    28
f4c3@1031
    29
namespace lemon {
kpeter@1033
    30
kpeter@1033
    31
  /// \brief 2-opt algorithm for symmetric TSP.
kpeter@1033
    32
  ///
kpeter@1033
    33
  /// Opt2Tsp implements the 2-opt heuristic for solving
kpeter@1033
    34
  /// symmetric \ref tsp "TSP".
kpeter@1033
    35
  ///
kpeter@1033
    36
  /// This algorithm starts with an initial tour and iteratively improves it.
kpeter@1033
    37
  /// At each step, it removes two edges and the reconnects the created two
kpeter@1033
    38
  /// paths in the other way if the resulting tour is shorter.
kpeter@1033
    39
  /// The algorithm finishes when no such 2-opt move can be applied, and so
kpeter@1033
    40
  /// the tour is 2-optimal.
kpeter@1033
    41
  ///
kpeter@1033
    42
  /// If no starting tour is given to the \ref run() function, then the
kpeter@1033
    43
  /// algorithm uses the node sequence determined by the node IDs.
kpeter@1033
    44
  /// Oherwise, it starts with the given tour.
kpeter@1033
    45
  ///
kpeter@1033
    46
  /// This is a relatively slow but powerful method. 
kpeter@1033
    47
  /// A typical usage of it is the improvement of a solution that is resulted
kpeter@1033
    48
  /// by a fast tour construction heuristic (e.g. the InsertionTsp algorithm).
kpeter@1033
    49
  ///
kpeter@1033
    50
  /// \tparam CM Type of the cost map.
f4c3@1031
    51
  template <typename CM>
kpeter@1033
    52
  class Opt2Tsp
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@1033
    68
      std::vector<int> _plist;
kpeter@1033
    69
      std::vector<Node> _path;
kpeter@1033
    70
f4c3@1031
    71
    public:
kpeter@1033
    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
      Opt2Tsp(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 from scratch.
kpeter@1033
    85
      ///
kpeter@1033
    86
      /// This function runs the algorithm starting from the tour that is
kpeter@1033
    87
      /// determined by the node ID sequence.
kpeter@1033
    88
      ///
kpeter@1033
    89
      /// \return The total cost of the found tour.
kpeter@1033
    90
      Cost run() {
kpeter@1033
    91
        _path.clear();
kpeter@1033
    92
kpeter@1033
    93
        if (_gr.nodeNum() == 0) return _sum = 0;
kpeter@1033
    94
        else if (_gr.nodeNum() == 1) {
kpeter@1033
    95
          _path.push_back(_gr(0));
kpeter@1033
    96
          return _sum = 0;
f4c3@1031
    97
        }
kpeter@1033
    98
        else if (_gr.nodeNum() == 2) {
kpeter@1033
    99
          _path.push_back(_gr(0));
kpeter@1033
   100
          _path.push_back(_gr(1));
kpeter@1033
   101
          return _sum = 2 * _cost[_gr.edge(_gr(0), _gr(1))];
kpeter@1033
   102
        }
f4c3@1031
   103
kpeter@1033
   104
        _plist.resize(2*_gr.nodeNum());
kpeter@1033
   105
        for (int i = 1; i < _gr.nodeNum()-1; ++i) {
kpeter@1033
   106
          _plist[2*i] = i-1;
kpeter@1033
   107
          _plist[2*i+1] = i+1;
f4c3@1031
   108
        }
kpeter@1033
   109
        _plist[0] = _gr.nodeNum()-1;
kpeter@1033
   110
        _plist[1] = 1;
kpeter@1033
   111
        _plist[2*_gr.nodeNum()-2] = _gr.nodeNum()-2;
kpeter@1033
   112
        _plist[2*_gr.nodeNum()-1] = 0;
kpeter@1033
   113
kpeter@1033
   114
        return start();
f4c3@1031
   115
      }
f4c3@1031
   116
kpeter@1033
   117
      /// \brief Runs the algorithm from the given tour.
kpeter@1033
   118
      ///
kpeter@1033
   119
      /// This function runs the algorithm starting from the given tour.
kpeter@1033
   120
      ///
kpeter@1033
   121
      /// \param tour The tour as a path structure. It must be a
kpeter@1033
   122
      /// \ref checkPath() "valid path" containing excactly n arcs.
kpeter@1033
   123
      ///
kpeter@1033
   124
      /// \return The total cost of the found tour.
kpeter@1033
   125
      template <typename Path>
kpeter@1033
   126
      Cost run(const Path& tour) {
kpeter@1033
   127
        _path.clear();
kpeter@1033
   128
kpeter@1033
   129
        if (_gr.nodeNum() == 0) return _sum = 0;
kpeter@1033
   130
        else if (_gr.nodeNum() == 1) {
kpeter@1033
   131
          _path.push_back(_gr(0));
kpeter@1033
   132
          return _sum = 0;
kpeter@1033
   133
        }
kpeter@1033
   134
        else if (_gr.nodeNum() == 2) {
kpeter@1033
   135
          _path.push_back(_gr(0));
kpeter@1033
   136
          _path.push_back(_gr(1));
kpeter@1033
   137
          return _sum = 2 * _cost[_gr.edge(_gr(0), _gr(1))];
kpeter@1033
   138
        }
kpeter@1033
   139
kpeter@1033
   140
        _plist.resize(2*_gr.nodeNum());
kpeter@1033
   141
        typename Path::ArcIt it(tour);
kpeter@1033
   142
        int first = _gr.id(_gr.source(it)),
kpeter@1033
   143
            prev = first,
kpeter@1033
   144
            curr = _gr.id(_gr.target(it)),
kpeter@1033
   145
            next = -1;
kpeter@1033
   146
        _plist[2*first+1] = curr;
kpeter@1033
   147
        for (++it; it != INVALID; ++it) {
kpeter@1033
   148
          next = _gr.id(_gr.target(it));
kpeter@1033
   149
          _plist[2*curr] = prev;
kpeter@1033
   150
          _plist[2*curr+1] = next;
kpeter@1033
   151
          prev = curr;
kpeter@1033
   152
          curr = next;
kpeter@1033
   153
        }
kpeter@1033
   154
        _plist[2*first] = prev;
kpeter@1033
   155
kpeter@1033
   156
        return start();
kpeter@1033
   157
      }
kpeter@1033
   158
kpeter@1033
   159
      /// \brief Runs the algorithm from the given tour.
kpeter@1033
   160
      ///
kpeter@1033
   161
      /// This function runs the algorithm starting from the given tour.
kpeter@1033
   162
      ///
kpeter@1033
   163
      /// \param tour The tour as a node sequence. It must be a standard
kpeter@1033
   164
      /// sequence container storing all <tt>Node</tt>s in the desired order.
kpeter@1033
   165
      ///
kpeter@1033
   166
      /// \return The total cost of the found tour.
kpeter@1033
   167
      template <template <typename> class Container>
kpeter@1033
   168
      Cost run(const Container<Node>& tour) {
kpeter@1033
   169
        _path.clear();
kpeter@1033
   170
kpeter@1033
   171
        if (_gr.nodeNum() == 0) return _sum = 0;
kpeter@1033
   172
        else if (_gr.nodeNum() == 1) {
kpeter@1033
   173
          _path.push_back(_gr(0));
kpeter@1033
   174
          return _sum = 0;
kpeter@1033
   175
        }
kpeter@1033
   176
        else if (_gr.nodeNum() == 2) {
kpeter@1033
   177
          _path.push_back(_gr(0));
kpeter@1033
   178
          _path.push_back(_gr(1));
kpeter@1033
   179
          return _sum = 2 * _cost[_gr.edge(_gr(0), _gr(1))];
kpeter@1033
   180
        }
kpeter@1033
   181
kpeter@1033
   182
        _plist.resize(2*_gr.nodeNum());
kpeter@1033
   183
        typename Container<Node>::const_iterator it = tour.begin();
kpeter@1033
   184
        int first = _gr.id(*it),
kpeter@1033
   185
            prev = first,
kpeter@1033
   186
            curr = _gr.id(*(++it)),
kpeter@1033
   187
            next = -1;
kpeter@1033
   188
        _plist[2*first+1] = curr;
kpeter@1033
   189
        for (++it; it != tour.end(); ++it) {
kpeter@1033
   190
          next = _gr.id(*it);
kpeter@1033
   191
          _plist[2*curr] = prev;
kpeter@1033
   192
          _plist[2*curr+1] = next;
kpeter@1033
   193
          prev = curr;
kpeter@1033
   194
          curr = next;
kpeter@1033
   195
        }
kpeter@1033
   196
        _plist[2*first] = curr;
kpeter@1033
   197
        _plist[2*curr] = prev;
kpeter@1033
   198
        _plist[2*curr+1] = first;
kpeter@1033
   199
kpeter@1033
   200
        return start();
kpeter@1033
   201
      }
kpeter@1033
   202
kpeter@1033
   203
      /// @}
kpeter@1033
   204
kpeter@1033
   205
      /// \name Query Functions
kpeter@1033
   206
      /// @{
kpeter@1033
   207
kpeter@1033
   208
      /// \brief The total cost of the found tour.
kpeter@1033
   209
      ///
kpeter@1033
   210
      /// This function returns the total cost of the found tour.
kpeter@1033
   211
      ///
kpeter@1033
   212
      /// \pre run() must be called before using this function.
kpeter@1033
   213
      Cost tourCost() const {
kpeter@1033
   214
        return _sum;
kpeter@1033
   215
      }
kpeter@1033
   216
kpeter@1033
   217
      /// \brief Returns a const reference to the node sequence of the
kpeter@1033
   218
      /// found tour.
kpeter@1033
   219
      ///
kpeter@1033
   220
      /// This function returns a const reference to the internal structure
kpeter@1033
   221
      /// that stores the node sequence of the found tour.
kpeter@1033
   222
      ///
kpeter@1033
   223
      /// \pre run() must be called before using this function.
kpeter@1033
   224
      const std::vector<Node>& tourNodes() const {
kpeter@1033
   225
        return _path;
kpeter@1033
   226
      }
kpeter@1033
   227
kpeter@1033
   228
      /// \brief Gives back the node sequence of the found tour.
kpeter@1033
   229
      ///
kpeter@1033
   230
      /// This function copies the node sequence of the found tour into
kpeter@1033
   231
      /// the given standard container.
kpeter@1033
   232
      ///
kpeter@1033
   233
      /// \pre run() must be called before using this function.
kpeter@1033
   234
      template <typename Container>
kpeter@1033
   235
      void tourNodes(Container &container) const {
kpeter@1033
   236
        container.assign(_path.begin(), _path.end());
kpeter@1033
   237
      }
kpeter@1033
   238
kpeter@1033
   239
      /// \brief Gives back the found tour as a path.
kpeter@1033
   240
      ///
kpeter@1033
   241
      /// This function copies the found tour as a list of arcs/edges into
kpeter@1033
   242
      /// the given \ref concept::Path "path structure".
kpeter@1033
   243
      ///
kpeter@1033
   244
      /// \pre run() must be called before using this function.
kpeter@1033
   245
      template <typename Path>
kpeter@1033
   246
      void tour(Path &path) const {
kpeter@1033
   247
        path.clear();
kpeter@1033
   248
        for (int i = 0; i < int(_path.size()) - 1; ++i) {
kpeter@1033
   249
          path.addBack(_gr.arc(_path[i], _path[i+1]));
kpeter@1033
   250
        }
kpeter@1033
   251
        if (int(_path.size()) >= 2) {
kpeter@1033
   252
          path.addBack(_gr.arc(_path.back(), _path.front()));
kpeter@1033
   253
        }
kpeter@1033
   254
      }
kpeter@1033
   255
kpeter@1033
   256
      /// @}
kpeter@1033
   257
f4c3@1031
   258
    private:
kpeter@1033
   259
kpeter@1033
   260
      // Iterator class for the linked list storage of the tour
kpeter@1033
   261
      class PathListIt {
f4c3@1031
   262
        public:
kpeter@1033
   263
          PathListIt(const std::vector<int> &pl, int i=0)
kpeter@1033
   264
            : plist(&pl), act(i), last(pl[2*act]) {}
kpeter@1033
   265
          PathListIt(const std::vector<int> &pl, int i, int l)
kpeter@1033
   266
            : plist(&pl), act(i), last(l) {}
f4c3@1031
   267
kpeter@1033
   268
          int nextIndex() const {
kpeter@1033
   269
            return (*plist)[2*act] == last ? 2*act+1 : 2*act;
f4c3@1031
   270
          }
kpeter@1033
   271
kpeter@1033
   272
          int prevIndex() const {
kpeter@1033
   273
            return (*plist)[2*act] == last ? 2*act : 2*act+1;
f4c3@1031
   274
          }
kpeter@1033
   275
f4c3@1031
   276
          int next() const {
kpeter@1033
   277
            int x = (*plist)[2*act];
kpeter@1033
   278
            return x == last ? (*plist)[2*act+1] : x;
f4c3@1031
   279
          }
f4c3@1031
   280
f4c3@1031
   281
          int prev() const {
kpeter@1033
   282
            return last;
f4c3@1031
   283
          }
kpeter@1033
   284
kpeter@1033
   285
          PathListIt& operator++() {
f4c3@1031
   286
            int tmp = act;
f4c3@1031
   287
            act = next();
f4c3@1031
   288
            last = tmp;
f4c3@1031
   289
            return *this;
f4c3@1031
   290
          }
kpeter@1033
   291
f4c3@1031
   292
          operator int() const {
f4c3@1031
   293
            return act;
f4c3@1031
   294
          }
kpeter@1033
   295
f4c3@1031
   296
        private:
kpeter@1033
   297
          const std::vector<int> *plist;
f4c3@1031
   298
          int act;
f4c3@1031
   299
          int last;
f4c3@1031
   300
      };
f4c3@1031
   301
kpeter@1033
   302
      // Checks and applies 2-opt move (if it improves the tour)
kpeter@1033
   303
      bool checkOpt2(const PathListIt& i, const PathListIt& j) {
kpeter@1033
   304
        Node u  = _gr.nodeFromId(i),
kpeter@1033
   305
             un = _gr.nodeFromId(i.next()),
kpeter@1033
   306
             v  = _gr.nodeFromId(j),
kpeter@1033
   307
             vn = _gr.nodeFromId(j.next());
f4c3@1031
   308
kpeter@1033
   309
        if (_cost[_gr.edge(u, un)] + _cost[_gr.edge(v, vn)] >
kpeter@1033
   310
            _cost[_gr.edge(u, v)] + _cost[_gr.edge(un, vn)])
kpeter@1033
   311
        {
kpeter@1033
   312
          _plist[PathListIt(_plist, i.next(), i).prevIndex()] = j.next();
kpeter@1033
   313
          _plist[PathListIt(_plist, j.next(), j).prevIndex()] = i.next();
f4c3@1031
   314
kpeter@1033
   315
          _plist[i.nextIndex()] = j;
kpeter@1033
   316
          _plist[j.nextIndex()] = i;
f4c3@1031
   317
kpeter@1033
   318
          return true;
f4c3@1031
   319
        }
kpeter@1033
   320
f4c3@1031
   321
        return false;
kpeter@1033
   322
     }
f4c3@1031
   323
kpeter@1033
   324
      // Executes the algorithm from the initial tour
kpeter@1033
   325
      Cost start() {
f4c3@1031
   326
kpeter@1033
   327
      restart_search:
kpeter@1033
   328
        for (PathListIt i(_plist); true; ++i) {
kpeter@1033
   329
          PathListIt j = i;
kpeter@1033
   330
          if (++j == 0 || ++j == 0) break;
kpeter@1033
   331
          for (; j != 0 && j != i.prev(); ++j) {
kpeter@1033
   332
            if (checkOpt2(i, j))
kpeter@1033
   333
              goto restart_search;
f4c3@1031
   334
          }
f4c3@1031
   335
        }
f4c3@1031
   336
kpeter@1033
   337
        PathListIt i(_plist);
kpeter@1033
   338
        _path.push_back(_gr.nodeFromId(i));
kpeter@1033
   339
        for (++i; i != 0; ++i)
kpeter@1033
   340
          _path.push_back(_gr.nodeFromId(i));
f4c3@1031
   341
kpeter@1033
   342
        _sum = _cost[_gr.edge(_path.back(), _path.front())];
kpeter@1033
   343
        for (int i = 0; i < int(_path.size())-1; ++i) {
kpeter@1033
   344
          _sum += _cost[_gr.edge(_path[i], _path[i+1])];
kpeter@1033
   345
        }
f4c3@1031
   346
f4c3@1031
   347
        return _sum;
f4c3@1031
   348
      }
f4c3@1031
   349
f4c3@1031
   350
  };
f4c3@1031
   351
f4c3@1031
   352
}; // namespace lemon
f4c3@1031
   353
f4c3@1031
   354
#endif