diff --git a/src/Tour.cpp b/src/Tour.cpp index 1b93323..286d529 100755 --- a/src/Tour.cpp +++ b/src/Tour.cpp @@ -141,7 +141,7 @@ Node *findbestNodeTSP(Node *const start, Point &point) { return optimalNode; } -void Tour::insertSmallest(Point p) { +void Tour::insertOptimalHeuristic(Point p) { if (m_startNode == nullptr) { m_startNode = new Node(p); m_startNode->next = m_startNode; // Make it cirkular @@ -157,3 +157,34 @@ void Tour::insertSmallest(Point p) { auto *newNode = new Node(p, bestNode->next); bestNode->next = newNode; } + +void Tour::insertSmallest(Point p) { + if (m_startNode == nullptr) { + m_startNode = new Node(p); + m_startNode->next = m_startNode; // Make it cirkular + return; + } + if (m_startNode->next == nullptr) { + auto newNode = new Node(p, m_startNode); + m_startNode->next = newNode; + return; + } + + Node *bestNode = m_startNode; + double minIncrease = Q_INFINITY; + + Node *node = m_startNode; + do { + double increase = node->point.distanceTo(p) + + p.distanceTo(node->next->point) - + node->point.distanceTo(node->next->point); + if (increase < minIncrease) { + minIncrease = increase; + bestNode = node; + } + node = node->next; + } while (node != m_startNode); + + auto *newNode = new Node(p, bestNode->next); + bestNode->next = newNode; +} diff --git a/src/Tour.h b/src/Tour.h index 14e3f0f..808c186 100755 --- a/src/Tour.h +++ b/src/Tour.h @@ -24,6 +24,7 @@ public: double distance() const; void insertNearest(Point p); void insertSmallest(Point p); + void insertOptimalHeuristic(Point p); private: Node* m_startNode; diff --git a/src/tsp.cpp b/src/tsp.cpp index a2601ce..f41b77c 100755 --- a/src/tsp.cpp +++ b/src/tsp.cpp @@ -49,7 +49,7 @@ int main(int argc, char *argv[]) { auto timeStart = std::chrono::high_resolution_clock::now(); while (input >> x >> y) { Point p(x, y); - tour.insertSmallest(p); + tour.insertOptimalHeuristic(p); //uncomment the 4 lines below to animate //tour.draw(scene); //std::chrono::milliseconds dura(50);