lemon/greedy_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_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@1033
    33
  /// \brief Greedy algorithm for symmetric TSP.
kpeter@1033
    34
  ///
kpeter@1033
    35
  /// GreedyTsp implements the greedy heuristic for solving
kpeter@1033
    36
  /// symmetric \ref tsp "TSP".
kpeter@1033
    37
  ///
kpeter@1033
    38
  /// This algorithm is quite similar to the \ref NearestNeighborTsp
kpeter@1033
    39
  /// "nearest neighbor" heuristic, but it maintains a set of disjoint paths.
kpeter@1033
    40
  /// At each step, the shortest possible edge is added to these paths
kpeter@1033
    41
  /// as long as it does not create a cycle of less than n edges and it does
kpeter@1033
    42
  /// not increase the degree of any node above two.
kpeter@1033
    43
  ///
kpeter@1033
    44
  /// This method runs in O(n<sup>2</sup>log(n)) time.
kpeter@1033
    45
  /// It quickly finds an effectively short tour for most TSP
kpeter@1033
    46
  /// instances, but in special cases, it could yield a really bad
kpeter@1033
    47
  /// (or even the worst) solution.
kpeter@1033
    48
  ///
kpeter@1033
    49
  /// \tparam CM Type of the cost map.
kpeter@1033
    50
  template <typename CM>
kpeter@1033
    51
  class GreedyTsp
kpeter@1033
    52
  {
kpeter@1033
    53
    public:
f4c3@1031
    54
kpeter@1033
    55
      /// Type of the cost map
kpeter@1033
    56
      typedef CM CostMap;
kpeter@1033
    57
      /// Type of the edge costs
kpeter@1033
    58
      typedef typename CM::Value Cost;
kpeter@1033
    59
kpeter@1033
    60
    private:
kpeter@1033
    61
kpeter@1033
    62
      GRAPH_TYPEDEFS(FullGraph);
kpeter@1033
    63
kpeter@1033
    64
      const FullGraph &_gr;
kpeter@1033
    65
      const CostMap &_cost;
kpeter@1033
    66
      Cost _sum;
kpeter@1033
    67
      std::vector<Node> _path;
f4c3@1031
    68
      
kpeter@1033
    69
    private:
kpeter@1033
    70
    
kpeter@1033
    71
      // Functor class to compare edges by their costs
kpeter@1033
    72
      class EdgeComp {
kpeter@1033
    73
      private:
kpeter@1033
    74
        const CostMap &_cost;
kpeter@1033
    75
f4c3@1031
    76
      public:
kpeter@1033
    77
        EdgeComp(const CostMap &cost) : _cost(cost) {}
kpeter@1033
    78
kpeter@1033
    79
        bool operator()(const Edge &a, const Edge &b) const {
kpeter@1033
    80
          return _cost[a] < _cost[b];
f4c3@1031
    81
        }
kpeter@1033
    82
      };
f4c3@1031
    83
kpeter@1033
    84
    public:
f4c3@1031
    85
kpeter@1033
    86
      /// \brief Constructor
kpeter@1033
    87
      ///
kpeter@1033
    88
      /// Constructor.
kpeter@1033
    89
      /// \param gr The \ref FullGraph "full graph" the algorithm runs on.
kpeter@1033
    90
      /// \param cost The cost map.
kpeter@1033
    91
      GreedyTsp(const FullGraph &gr, const CostMap &cost)
kpeter@1033
    92
        : _gr(gr), _cost(cost) {}
f4c3@1031
    93
kpeter@1033
    94
      /// \name Execution Control
kpeter@1033
    95
      /// @{
f4c3@1031
    96
kpeter@1033
    97
      /// \brief Runs the algorithm.
kpeter@1033
    98
      ///
kpeter@1033
    99
      /// This function runs the algorithm.
kpeter@1033
   100
      ///
kpeter@1033
   101
      /// \return The total cost of the found tour.
f4c3@1031
   102
      Cost run() {
kpeter@1033
   103
        _path.clear();
kpeter@1033
   104
kpeter@1033
   105
        if (_gr.nodeNum() == 0) return _sum = 0;
kpeter@1033
   106
        else if (_gr.nodeNum() == 1) {
kpeter@1033
   107
          _path.push_back(_gr(0));
kpeter@1033
   108
          return _sum = 0;
kpeter@1033
   109
        }
kpeter@1033
   110
kpeter@1033
   111
        std::vector<int> plist;
kpeter@1033
   112
        plist.resize(_gr.nodeNum()*2, -1);
kpeter@1033
   113
kpeter@1033
   114
        std::vector<Edge> sorted_edges;
f4c3@1031
   115
        sorted_edges.reserve(_gr.edgeNum());
kpeter@1033
   116
        for (EdgeIt e(_gr); e != INVALID; ++e)
kpeter@1033
   117
          sorted_edges.push_back(e);
kpeter@1033
   118
        std::sort(sorted_edges.begin(), sorted_edges.end(), EdgeComp(_cost));
f4c3@1031
   119
kpeter@1033
   120
        FullGraph::NodeMap<int> item_int_map(_gr);
kpeter@1033
   121
        UnionFind<FullGraph::NodeMap<int> > union_find(item_int_map);
kpeter@1033
   122
        for (NodeIt n(_gr); n != INVALID; ++n)
kpeter@1033
   123
          union_find.insert(n);
f4c3@1031
   124
f4c3@1031
   125
        FullGraph::NodeMap<int> degree(_gr, 0);
f4c3@1031
   126
f4c3@1031
   127
        int nodesNum = 0, i = 0;
kpeter@1033
   128
        while (nodesNum != _gr.nodeNum()-1) {
kpeter@1033
   129
          Edge e = sorted_edges[i++];
kpeter@1033
   130
          Node u = _gr.u(e),
kpeter@1033
   131
               v = _gr.v(e);
f4c3@1031
   132
kpeter@1033
   133
          if (degree[u] <= 1 && degree[v] <= 1) {
kpeter@1033
   134
            if (union_find.join(u, v)) {
kpeter@1033
   135
              const int uid = _gr.id(u),
kpeter@1033
   136
                        vid = _gr.id(v);
kpeter@1033
   137
kpeter@1033
   138
              plist[uid*2 + degree[u]] = vid;
kpeter@1033
   139
              plist[vid*2 + degree[v]] = uid;
kpeter@1033
   140
f4c3@1031
   141
              ++degree[u];
f4c3@1031
   142
              ++degree[v];
f4c3@1031
   143
              ++nodesNum;
f4c3@1031
   144
            }
f4c3@1031
   145
          }
f4c3@1031
   146
        }
f4c3@1031
   147
f4c3@1031
   148
        for (int i=0, n=-1; i<_gr.nodeNum()*2; ++i) {
kpeter@1033
   149
          if (plist[i] == -1) {
f4c3@1031
   150
            if (n==-1) {
f4c3@1031
   151
              n = i;
f4c3@1031
   152
            } else {
kpeter@1033
   153
              plist[n] = i/2;
kpeter@1033
   154
              plist[i] = n/2;
f4c3@1031
   155
              break;
f4c3@1031
   156
            }
f4c3@1031
   157
          }
f4c3@1031
   158
        }
f4c3@1031
   159
kpeter@1033
   160
        for (int i=0, next=0, last=-1; i!=_gr.nodeNum(); ++i) {
kpeter@1033
   161
          _path.push_back(_gr.nodeFromId(next));
kpeter@1033
   162
          if (plist[2*next] != last) {
kpeter@1033
   163
            last = next;
kpeter@1033
   164
            next = plist[2*next];
f4c3@1031
   165
          } else {
kpeter@1033
   166
            last = next;
kpeter@1033
   167
            next = plist[2*next+1];
f4c3@1031
   168
          }
f4c3@1031
   169
        }
f4c3@1031
   170
kpeter@1033
   171
        _sum = _cost[_gr.edge(_path.back(), _path.front())];
kpeter@1033
   172
        for (int i = 0; i < int(_path.size())-1; ++i) {
kpeter@1033
   173
          _sum += _cost[_gr.edge(_path[i], _path[i+1])];
kpeter@1033
   174
        }
f4c3@1031
   175
f4c3@1031
   176
        return _sum;
f4c3@1031
   177
      }
f4c3@1031
   178
kpeter@1033
   179
      /// @}
f4c3@1031
   180
kpeter@1033
   181
      /// \name Query Functions
kpeter@1033
   182
      /// @{
f4c3@1031
   183
kpeter@1033
   184
      /// \brief The total cost of the found tour.
kpeter@1033
   185
      ///
kpeter@1033
   186
      /// This function returns the total cost of the found tour.
kpeter@1033
   187
      ///
kpeter@1033
   188
      /// \pre run() must be called before using this function.
kpeter@1033
   189
      Cost tourCost() const {
f4c3@1031
   190
        return _sum;
f4c3@1031
   191
      }
f4c3@1031
   192
kpeter@1033
   193
      /// \brief Returns a const reference to the node sequence of the
kpeter@1033
   194
      /// found tour.
kpeter@1033
   195
      ///
kpeter@1033
   196
      /// This function returns a const reference to the internal structure
kpeter@1033
   197
      /// that stores the node sequence of the found tour.
kpeter@1033
   198
      ///
kpeter@1033
   199
      /// \pre run() must be called before using this function.
kpeter@1033
   200
      const std::vector<Node>& tourNodes() const {
kpeter@1033
   201
        return _path;
kpeter@1033
   202
      }
kpeter@1033
   203
kpeter@1033
   204
      /// \brief Gives back the node sequence of the found tour.
kpeter@1033
   205
      ///
kpeter@1033
   206
      /// This function copies the node sequence of the found tour into
kpeter@1033
   207
      /// the given standard container.
kpeter@1033
   208
      ///
kpeter@1033
   209
      /// \pre run() must be called before using this function.
kpeter@1033
   210
      template <typename Container>
kpeter@1033
   211
      void tourNodes(Container &container) const {
kpeter@1033
   212
        container.assign(_path.begin(), _path.end());
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
kpeter@1033
   218
      /// the given \ref concept::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]));
kpeter@1033
   226
        }
kpeter@1033
   227
        if (int(_path.size()) >= 2) {
kpeter@1033
   228
          path.addBack(_gr.arc(_path.back(), _path.front()));
kpeter@1033
   229
        }
kpeter@1033
   230
      }
kpeter@1033
   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