1 #ifndef LEMON_NEAREST_NEIGHBOUR_TSP_H
2 #define LEMON_NEAREST_NEIGHBOUR_TSP_H
5 #include <lemon/full_graph.h>
6 #include <lemon/path.h>
7 #include <lemon/maps.h>
13 L dequeConvert(const std::deque<FullGraph::Node> &_path) {
14 return L(_path.begin(), _path.end());
18 std::deque<FullGraph::Node> dequeConvert(const std::deque<FullGraph::Node> &_path) {
23 template <typename CM>
24 class NearestNeighborTsp {
26 GRAPH_TYPEDEFS(FullGraph);
30 typedef typename CM::Value Cost;
32 NearestNeighborTsp(const FullGraph &gr, const CostMap &cost) : _gr(gr), _cost(cost) {}
37 Edge min_edge1 = INVALID,
40 min_edge1 = mapMin(_gr, _cost);
42 FullGraph::NodeMap<bool> used(_gr, false);
44 Node n1 = _gr.u(min_edge1),
45 n2 = _gr.v(min_edge1);
55 while (int(_path.size()) != _gr.nodeNum()) {
56 if (min_edge1 == INVALID) {
57 for (IncEdgeIt e(_gr, n1); e!=INVALID; ++e) {
58 if (!used[_gr.runningNode(e)]) {
59 if (min_edge1==INVALID || _cost[min_edge1] > _cost[e])
65 if (min_edge2 == INVALID) {
66 for (IncEdgeIt e(_gr, n2); e!=INVALID; ++e) {
67 if (!used[_gr.runningNode(e)]) {
68 if (min_edge2==INVALID || _cost[min_edge2] > _cost[e])
74 if ( _cost[min_edge1] < _cost[min_edge2] ) {
75 n1 = (_gr.u(min_edge1) == n1) ? _gr.v(min_edge1) : _gr.u(min_edge1);
81 if (_gr.u(min_edge2)==n1 || _gr.v(min_edge2)==n1)
84 n2 = (_gr.u(min_edge2) == n2) ? _gr.v(min_edge2) : _gr.u(min_edge2);
90 if (_gr.u(min_edge1)==n2 || _gr.v(min_edge1)==n2)
95 _sum = _cost[ _gr.edge(_path.back(), _path.front()) ];
96 for (unsigned int i=0; i<_path.size()-1; ++i)
97 _sum += _cost[ _gr.edge(_path[i], _path[i+1]) ];
103 template <typename L>
104 void tourNodes(L &container) {
105 container(nn_helper::dequeConvert<L>(_path));
108 template <template <typename> class L>
109 L<Node> tourNodes() {
110 return nn_helper::dequeConvert<L<Node> >(_path);
113 const std::deque<Node>& tourNodes() {
117 Path<FullGraph> tour() {
122 for (unsigned int i=0; i<_path.size()-1; ++i) {
123 p.addBack(_gr.arc(_path[i], _path[i+1]));
125 p.addBack(_gr.arc(_path.back(), _path.front()));
136 const FullGraph &_gr;
137 const CostMap &_cost;
139 std::deque<Node> _path;
143 }; // namespace lemon