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