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