27 #include "../config.h"
28 #include "../serialization.h"
29 #include "../population.h"
30 #include "../problem/tsp.h"
34 namespace pagmo {
namespace algorithm {
68 catch (
const std::bad_cast& e)
70 pagmo_throw(value_error,
"Problem not of type pagmo::problem::tsp, nn_tsp can only be called on problem::tsp problems");
81 if (m_start_city < -1 || m_start_city > static_cast<int>(Nv-1)) {
82 pagmo_throw(value_error,
"invalid value for the first vertex");
86 size_t first_city, Nt;
87 if(m_start_city == -1){
92 first_city = m_start_city;
96 int length_best_tour, length_new_tour;
97 size_t nxt_city, min_idx;
98 std::vector<int> not_visited(Nv);
102 for (
size_t i = first_city; i < Nt; i++) {
104 for (
size_t j = 0; j < Nv; j++) {
108 std::swap(not_visited[new_tour[0]],not_visited[Nv-1]);
109 for (
size_t j = 1; j < Nv-1; j++) {
111 nxt_city = not_visited[0];
112 for (
size_t l = 1; l < Nv-j; l++) {
113 if(prob->distance(new_tour[j-1], not_visited[l]) < prob->distance(new_tour[j-1], nxt_city) )
116 nxt_city = not_visited[l];}
118 new_tour[j] = nxt_city;
119 length_new_tour += prob->distance(new_tour[j-1], nxt_city);
120 std::swap(not_visited[min_idx],not_visited[Nv-j-1]);
122 new_tour[Nv-1] = not_visited[0];
123 length_new_tour += prob->distance(new_tour[Nv-2], new_tour[Nv-1]);
124 length_new_tour += prob->distance(new_tour[Nv-1], new_tour[0]);
125 if(i == first_city || length_new_tour < length_best_tour){
126 best_tour = new_tour;
127 length_best_tour = length_new_tour;
141 pop.set_x(best_idx,best_tour);
152 return "Nearest neighbour algorithm";
boost::shared_ptr< base > base_ptr
Alias for shared pointer to base algorithm.
std::vector< double > decision_vector
Decision vector type.
const individual_type & get_individual(const size_type &) const
Get constant reference to individual at position n.
std::string get_name() const
Algorithm name.
As a vector of doubles in [0,1].
decision_vector::size_type get_n_cities() const
Getter for m_n_cities.
pagmo::decision_vector cities2full(const pagmo::decision_vector &) const
From CITIES to FULL encoding.
Nearest Neighbor Algorithm (NN)
base_ptr clone() const
Clone method.
void evolve(population &) const
Evolve implementation.
nn_tsp(int start_city=-1)
Constructor.
container_type::size_type size_type
Population size type.
decision_vector cur_x
Current decision vector.
As a matrix with ones and zeros.
Base TSP (Travelling Salesman Problem).
As a sequence of cities ids.
pagmo::decision_vector cities2randomkeys(const pagmo::decision_vector &, const pagmo::decision_vector &) const
From CITIES to RANDOMKEYS encoding.
decision_vector::size_type size_type
Problem's size type: the same as pagmo::decision_vector's size type.
encoding_type get_encoding() const
Getter for m_encoding.