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