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