1 /* -*- mode: C++; indent-tabs-mode: nil; -*-
3 * This file is a part of LEMON, a generic C++ optimization library.
5 * Copyright (C) 2003-2013
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_GREEDY_TSP_H
20 #define LEMON_GREEDY_TSP_H
24 /// \brief Greedy algorithm for symmetric TSP
28 #include <lemon/full_graph.h>
29 #include <lemon/unionfind.h>
35 /// \brief Greedy algorithm for symmetric TSP.
37 /// GreedyTsp implements the greedy heuristic for solving
38 /// symmetric \ref tsp "TSP".
40 /// This algorithm is quite similar to the \ref NearestNeighborTsp
41 /// "nearest neighbor" heuristic, but it maintains a set of disjoint paths.
42 /// At each step, the shortest possible edge is added to these paths
43 /// as long as it does not create a cycle of less than n edges and it does
44 /// not increase the degree of any node above two.
46 /// This method runs in O(n<sup>2</sup>) time.
47 /// It quickly finds a relatively short tour for most TSP instances,
48 /// but it could also yield a really bad (or even the worst) solution
51 /// \tparam CM Type of the cost map.
52 template <typename CM>
57 /// Type of the cost map
59 /// Type of the edge costs
60 typedef typename CM::Value Cost;
64 GRAPH_TYPEDEFS(FullGraph);
69 std::vector<Node> _path;
73 // Functor class to compare edges by their costs
79 EdgeComp(const CostMap &cost) : _cost(cost) {}
81 bool operator()(const Edge &a, const Edge &b) const {
82 return _cost[a] < _cost[b];
88 /// \brief Constructor
91 /// \param gr The \ref FullGraph "full graph" the algorithm runs on.
92 /// \param cost The cost map.
93 GreedyTsp(const FullGraph &gr, const CostMap &cost)
94 : _gr(gr), _cost(cost) {}
96 /// \name Execution Control
99 /// \brief Runs the algorithm.
101 /// This function runs the algorithm.
103 /// \return The total cost of the found tour.
107 if (_gr.nodeNum() == 0) return _sum = 0;
108 else if (_gr.nodeNum() == 1) {
109 _path.push_back(_gr(0));
113 std::vector<int> plist;
114 plist.resize(_gr.nodeNum()*2, -1);
116 std::vector<Edge> sorted_edges;
117 sorted_edges.reserve(_gr.edgeNum());
118 for (EdgeIt e(_gr); e != INVALID; ++e)
119 sorted_edges.push_back(e);
120 std::sort(sorted_edges.begin(), sorted_edges.end(), EdgeComp(_cost));
122 FullGraph::NodeMap<int> item_int_map(_gr);
123 UnionFind<FullGraph::NodeMap<int> > union_find(item_int_map);
124 for (NodeIt n(_gr); n != INVALID; ++n)
125 union_find.insert(n);
127 FullGraph::NodeMap<int> degree(_gr, 0);
129 int nodesNum = 0, i = 0;
130 while (nodesNum != _gr.nodeNum()-1) {
131 Edge e = sorted_edges[i++];
135 if (degree[u] <= 1 && degree[v] <= 1) {
136 if (union_find.join(u, v)) {
137 const int uid = _gr.id(u),
140 plist[uid*2 + degree[u]] = vid;
141 plist[vid*2 + degree[v]] = uid;
150 for (int i=0, n=-1; i<_gr.nodeNum()*2; ++i) {
151 if (plist[i] == -1) {
162 for (int i=0, next=0, last=-1; i!=_gr.nodeNum(); ++i) {
163 _path.push_back(_gr.nodeFromId(next));
164 if (plist[2*next] != last) {
166 next = plist[2*next];
169 next = plist[2*next+1];
173 _sum = _cost[_gr.edge(_path.back(), _path.front())];
174 for (int i = 0; i < int(_path.size())-1; ++i) {
175 _sum += _cost[_gr.edge(_path[i], _path[i+1])];
183 /// \name Query Functions
186 /// \brief The total cost of the found tour.
188 /// This function returns the total cost of the found tour.
190 /// \pre run() must be called before using this function.
191 Cost tourCost() const {
195 /// \brief Returns a const reference to the node sequence of the
198 /// This function returns a const reference to a vector
199 /// that stores the node sequence of the found tour.
201 /// \pre run() must be called before using this function.
202 const std::vector<Node>& tourNodes() const {
206 /// \brief Gives back the node sequence of the found tour.
208 /// This function copies the node sequence of the found tour into
209 /// an STL container through the given output iterator. The
210 /// <tt>value_type</tt> of the container must be <tt>FullGraph::Node</tt>.
213 /// std::vector<FullGraph::Node> nodes(countNodes(graph));
214 /// tsp.tourNodes(nodes.begin());
218 /// std::list<FullGraph::Node> nodes;
219 /// tsp.tourNodes(std::back_inserter(nodes));
222 /// \pre run() must be called before using this function.
223 template <typename Iterator>
224 void tourNodes(Iterator out) const {
225 std::copy(_path.begin(), _path.end(), out);
228 /// \brief Gives back the found tour as a path.
230 /// This function copies the found tour as a list of arcs/edges into
231 /// the given \ref lemon::concepts::Path "path structure".
233 /// \pre run() must be called before using this function.
234 template <typename Path>
235 void tour(Path &path) const {
237 for (int i = 0; i < int(_path.size()) - 1; ++i) {
238 path.addBack(_gr.arc(_path[i], _path[i+1]));
240 if (int(_path.size()) >= 2) {
241 path.addBack(_gr.arc(_path.back(), _path.front()));
249 }; // namespace lemon