lemon/christofides_tsp.h
author Alpar Juttner <alpar@cs.elte.hu>
Fri, 15 May 2015 10:15:30 +0200
changeset 1353 760a5f690163
parent 1250 97d978243703
permissions -rw-r--r--
Minor doc fixes
kpeter@1201
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
kpeter@1201
     2
 *
kpeter@1201
     3
 * This file is a part of LEMON, a generic C++ optimization library.
kpeter@1201
     4
 *
alpar@1270
     5
 * Copyright (C) 2003-2013
kpeter@1201
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
kpeter@1201
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
kpeter@1201
     8
 *
kpeter@1201
     9
 * Permission to use, modify and distribute this software is granted
kpeter@1201
    10
 * provided that this copyright notice appears in all copies. For
kpeter@1201
    11
 * precise terms see the accompanying LICENSE file.
kpeter@1201
    12
 *
kpeter@1201
    13
 * This software is provided "AS IS" with no warranty of any kind,
kpeter@1201
    14
 * express or implied, and with no claim as to its suitability for any
kpeter@1201
    15
 * purpose.
kpeter@1201
    16
 *
kpeter@1201
    17
 */
kpeter@1201
    18
f4c3@1199
    19
#ifndef LEMON_CHRISTOFIDES_TSP_H
f4c3@1199
    20
#define LEMON_CHRISTOFIDES_TSP_H
f4c3@1199
    21
kpeter@1201
    22
/// \ingroup tsp
kpeter@1201
    23
/// \file
kpeter@1201
    24
/// \brief Christofides algorithm for symmetric TSP
kpeter@1201
    25
f4c3@1199
    26
#include <lemon/full_graph.h>
f4c3@1199
    27
#include <lemon/smart_graph.h>
f4c3@1199
    28
#include <lemon/kruskal.h>
f4c3@1199
    29
#include <lemon/matching.h>
f4c3@1199
    30
#include <lemon/euler.h>
f4c3@1199
    31
f4c3@1199
    32
namespace lemon {
alpar@1270
    33
kpeter@1202
    34
  /// \ingroup tsp
kpeter@1202
    35
  ///
kpeter@1201
    36
  /// \brief Christofides algorithm for symmetric TSP.
kpeter@1201
    37
  ///
kpeter@1201
    38
  /// ChristofidesTsp implements Christofides' heuristic for solving
kpeter@1201
    39
  /// symmetric \ref tsp "TSP".
kpeter@1201
    40
  ///
kpeter@1201
    41
  /// This a well-known approximation method for the TSP problem with
kpeter@1202
    42
  /// metric cost function.
kpeter@1204
    43
  /// It has a guaranteed approximation factor of 3/2 (i.e. it finds a tour
kpeter@1204
    44
  /// whose total cost is at most 3/2 of the optimum), but it usually
kpeter@1204
    45
  /// provides better solutions in practice.
kpeter@1201
    46
  /// This implementation runs in O(n<sup>3</sup>log(n)) time.
kpeter@1201
    47
  ///
kpeter@1201
    48
  /// The algorithm starts with a \ref spantree "minimum cost spanning tree" and
kpeter@1201
    49
  /// finds a \ref MaxWeightedPerfectMatching "minimum cost perfect matching"
kpeter@1201
    50
  /// in the subgraph induced by the nodes that have odd degree in the
kpeter@1201
    51
  /// spanning tree.
kpeter@1201
    52
  /// Finally, it constructs the tour from the \ref EulerIt "Euler traversal"
kpeter@1201
    53
  /// of the union of the spanning tree and the matching.
kpeter@1201
    54
  /// During this last step, the algorithm simply skips the visited nodes
kpeter@1201
    55
  /// (i.e. creates shortcuts) assuming that the triangle inequality holds
kpeter@1201
    56
  /// for the cost function.
kpeter@1201
    57
  ///
kpeter@1201
    58
  /// \tparam CM Type of the cost map.
kpeter@1201
    59
  ///
kpeter@1202
    60
  /// \warning CM::Value must be a signed number type.
f4c3@1199
    61
  template <typename CM>
kpeter@1201
    62
  class ChristofidesTsp
kpeter@1201
    63
  {
kpeter@1201
    64
    public:
kpeter@1201
    65
kpeter@1201
    66
      /// Type of the cost map
kpeter@1201
    67
      typedef CM CostMap;
kpeter@1201
    68
      /// Type of the edge costs
kpeter@1201
    69
      typedef typename CM::Value Cost;
kpeter@1201
    70
f4c3@1199
    71
    private:
kpeter@1201
    72
kpeter@1201
    73
      GRAPH_TYPEDEFS(FullGraph);
kpeter@1201
    74
kpeter@1201
    75
      const FullGraph &_gr;
kpeter@1201
    76
      const CostMap &_cost;
kpeter@1201
    77
      std::vector<Node> _path;
kpeter@1201
    78
      Cost _sum;
f4c3@1199
    79
f4c3@1199
    80
    public:
f4c3@1199
    81
kpeter@1201
    82
      /// \brief Constructor
kpeter@1201
    83
      ///
kpeter@1201
    84
      /// Constructor.
kpeter@1201
    85
      /// \param gr The \ref FullGraph "full graph" the algorithm runs on.
kpeter@1201
    86
      /// \param cost The cost map.
kpeter@1201
    87
      ChristofidesTsp(const FullGraph &gr, const CostMap &cost)
kpeter@1201
    88
        : _gr(gr), _cost(cost) {}
kpeter@1201
    89
kpeter@1201
    90
      /// \name Execution Control
kpeter@1201
    91
      /// @{
kpeter@1201
    92
kpeter@1201
    93
      /// \brief Runs the algorithm.
kpeter@1201
    94
      ///
kpeter@1201
    95
      /// This function runs the algorithm.
kpeter@1201
    96
      ///
kpeter@1201
    97
      /// \return The total cost of the found tour.
f4c3@1199
    98
      Cost run() {
f4c3@1199
    99
        _path.clear();
kpeter@1201
   100
kpeter@1201
   101
        if (_gr.nodeNum() == 0) return _sum = 0;
kpeter@1201
   102
        else if (_gr.nodeNum() == 1) {
kpeter@1201
   103
          _path.push_back(_gr(0));
kpeter@1201
   104
          return _sum = 0;
kpeter@1201
   105
        }
kpeter@1201
   106
        else if (_gr.nodeNum() == 2) {
kpeter@1201
   107
          _path.push_back(_gr(0));
kpeter@1201
   108
          _path.push_back(_gr(1));
kpeter@1201
   109
          return _sum = 2 * _cost[_gr.edge(_gr(0), _gr(1))];
kpeter@1201
   110
        }
alpar@1270
   111
kpeter@1201
   112
        // Compute min. cost spanning tree
kpeter@1201
   113
        std::vector<Edge> tree;
kpeter@1201
   114
        kruskal(_gr, _cost, std::back_inserter(tree));
alpar@1270
   115
kpeter@1201
   116
        FullGraph::NodeMap<int> deg(_gr, 0);
kpeter@1201
   117
        for (int i = 0; i != int(tree.size()); ++i) {
kpeter@1201
   118
          Edge e = tree[i];
kpeter@1201
   119
          ++deg[_gr.u(e)];
kpeter@1201
   120
          ++deg[_gr.v(e)];
kpeter@1201
   121
        }
kpeter@1201
   122
kpeter@1201
   123
        // Copy the induced subgraph of odd nodes
kpeter@1201
   124
        std::vector<Node> odd_nodes;
kpeter@1201
   125
        for (NodeIt u(_gr); u != INVALID; ++u) {
kpeter@1201
   126
          if (deg[u] % 2 == 1) odd_nodes.push_back(u);
kpeter@1201
   127
        }
alpar@1270
   128
kpeter@1201
   129
        SmartGraph sgr;
kpeter@1201
   130
        SmartGraph::EdgeMap<Cost> scost(sgr);
kpeter@1201
   131
        for (int i = 0; i != int(odd_nodes.size()); ++i) {
kpeter@1201
   132
          sgr.addNode();
kpeter@1201
   133
        }
kpeter@1201
   134
        for (int i = 0; i != int(odd_nodes.size()); ++i) {
kpeter@1201
   135
          for (int j = 0; j != int(odd_nodes.size()); ++j) {
kpeter@1201
   136
            if (j == i) continue;
kpeter@1201
   137
            SmartGraph::Edge e =
kpeter@1201
   138
              sgr.addEdge(sgr.nodeFromId(i), sgr.nodeFromId(j));
kpeter@1201
   139
            scost[e] = -_cost[_gr.edge(odd_nodes[i], odd_nodes[j])];
f4c3@1199
   140
          }
f4c3@1199
   141
        }
alpar@1270
   142
kpeter@1201
   143
        // Compute min. cost perfect matching
kpeter@1201
   144
        MaxWeightedPerfectMatching<SmartGraph, SmartGraph::EdgeMap<Cost> >
kpeter@1201
   145
          mwpm(sgr, scost);
kpeter@1201
   146
        mwpm.run();
alpar@1270
   147
kpeter@1201
   148
        for (SmartGraph::EdgeIt e(sgr); e != INVALID; ++e) {
kpeter@1201
   149
          if (mwpm.matching(e)) {
kpeter@1201
   150
            tree.push_back( _gr.edge(odd_nodes[sgr.id(sgr.u(e))],
kpeter@1201
   151
                                     odd_nodes[sgr.id(sgr.v(e))]) );
f4c3@1199
   152
          }
f4c3@1199
   153
        }
alpar@1270
   154
alpar@1270
   155
        // Join the spanning tree and the matching
kpeter@1201
   156
        sgr.clear();
kpeter@1201
   157
        for (int i = 0; i != _gr.nodeNum(); ++i) {
kpeter@1201
   158
          sgr.addNode();
kpeter@1201
   159
        }
kpeter@1201
   160
        for (int i = 0; i != int(tree.size()); ++i) {
kpeter@1201
   161
          int ui = _gr.id(_gr.u(tree[i])),
kpeter@1201
   162
              vi = _gr.id(_gr.v(tree[i]));
kpeter@1201
   163
          sgr.addEdge(sgr.nodeFromId(ui), sgr.nodeFromId(vi));
kpeter@1201
   164
        }
kpeter@1201
   165
kpeter@1201
   166
        // Compute the tour from the Euler traversal
kpeter@1201
   167
        SmartGraph::NodeMap<bool> visited(sgr, false);
kpeter@1201
   168
        for (EulerIt<SmartGraph> e(sgr); e != INVALID; ++e) {
kpeter@1201
   169
          SmartGraph::Node n = sgr.target(e);
kpeter@1201
   170
          if (!visited[n]) {
kpeter@1201
   171
            _path.push_back(_gr(sgr.id(n)));
kpeter@1201
   172
            visited[n] = true;
f4c3@1199
   173
          }
f4c3@1199
   174
        }
f4c3@1199
   175
kpeter@1201
   176
        _sum = _cost[_gr.edge(_path.back(), _path.front())];
kpeter@1201
   177
        for (int i = 0; i < int(_path.size())-1; ++i) {
kpeter@1201
   178
          _sum += _cost[_gr.edge(_path[i], _path[i+1])];
kpeter@1201
   179
        }
f4c3@1199
   180
f4c3@1199
   181
        return _sum;
f4c3@1199
   182
      }
f4c3@1199
   183
kpeter@1201
   184
      /// @}
alpar@1270
   185
kpeter@1201
   186
      /// \name Query Functions
kpeter@1201
   187
      /// @{
alpar@1270
   188
kpeter@1201
   189
      /// \brief The total cost of the found tour.
kpeter@1201
   190
      ///
kpeter@1201
   191
      /// This function returns the total cost of the found tour.
kpeter@1201
   192
      ///
kpeter@1201
   193
      /// \pre run() must be called before using this function.
kpeter@1201
   194
      Cost tourCost() const {
f4c3@1199
   195
        return _sum;
f4c3@1199
   196
      }
alpar@1270
   197
kpeter@1201
   198
      /// \brief Returns a const reference to the node sequence of the
kpeter@1201
   199
      /// found tour.
kpeter@1201
   200
      ///
kpeter@1202
   201
      /// This function returns a const reference to a vector
kpeter@1201
   202
      /// that stores the node sequence of the found tour.
kpeter@1201
   203
      ///
kpeter@1201
   204
      /// \pre run() must be called before using this function.
kpeter@1201
   205
      const std::vector<Node>& tourNodes() const {
kpeter@1201
   206
        return _path;
kpeter@1201
   207
      }
f4c3@1199
   208
kpeter@1201
   209
      /// \brief Gives back the node sequence of the found tour.
kpeter@1201
   210
      ///
kpeter@1201
   211
      /// This function copies the node sequence of the found tour into
kpeter@1205
   212
      /// an STL container through the given output iterator. The
kpeter@1205
   213
      /// <tt>value_type</tt> of the container must be <tt>FullGraph::Node</tt>.
kpeter@1205
   214
      /// For example,
kpeter@1205
   215
      /// \code
kpeter@1205
   216
      /// std::vector<FullGraph::Node> nodes(countNodes(graph));
kpeter@1205
   217
      /// tsp.tourNodes(nodes.begin());
kpeter@1205
   218
      /// \endcode
kpeter@1205
   219
      /// or
kpeter@1205
   220
      /// \code
kpeter@1205
   221
      /// std::list<FullGraph::Node> nodes;
kpeter@1205
   222
      /// tsp.tourNodes(std::back_inserter(nodes));
kpeter@1205
   223
      /// \endcode
kpeter@1201
   224
      ///
kpeter@1201
   225
      /// \pre run() must be called before using this function.
kpeter@1205
   226
      template <typename Iterator>
kpeter@1205
   227
      void tourNodes(Iterator out) const {
kpeter@1205
   228
        std::copy(_path.begin(), _path.end(), out);
kpeter@1201
   229
      }
alpar@1270
   230
kpeter@1201
   231
      /// \brief Gives back the found tour as a path.
kpeter@1201
   232
      ///
kpeter@1201
   233
      /// This function copies the found tour as a list of arcs/edges into
alpar@1250
   234
      /// the given \ref lemon::concepts::Path "path structure".
kpeter@1201
   235
      ///
kpeter@1201
   236
      /// \pre run() must be called before using this function.
kpeter@1201
   237
      template <typename Path>
kpeter@1201
   238
      void tour(Path &path) const {
kpeter@1201
   239
        path.clear();
kpeter@1201
   240
        for (int i = 0; i < int(_path.size()) - 1; ++i) {
kpeter@1201
   241
          path.addBack(_gr.arc(_path[i], _path[i+1]));
kpeter@1201
   242
        }
kpeter@1201
   243
        if (int(_path.size()) >= 2) {
kpeter@1201
   244
          path.addBack(_gr.arc(_path.back(), _path.front()));
kpeter@1201
   245
        }
kpeter@1201
   246
      }
alpar@1270
   247
kpeter@1201
   248
      /// @}
alpar@1270
   249
f4c3@1199
   250
  };
f4c3@1199
   251
f4c3@1199
   252
}; // namespace lemon
f4c3@1199
   253
f4c3@1199
   254
#endif