Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <math.h>
- #include <ctime>
- #include <cstdlib>
- using namespace std;
- void travel(const vector<vector<double>>& graph, vector<int>& path, double& l) {
- int f, f1, s, s1, flag = 0;
- int n = graph.size();
- double tmp;
- for (size_t i = 0; i <= n - 3; ++i) {
- for (size_t j = i + 2; j <= n - 1; ++j) {
- if (i != 0 || j != n - 1) {
- f = path[i];
- f1 = path[i + 1];
- s = path[j];
- s1 = path[(j + 1) % n];
- /* for (auto i : ptr) {
- cout << i << " ";
- }
- cout << endl; */
- tmp = l - graph[f][f1] - graph[s][s1] + graph[f][s] + graph[f1][s1];
- if (tmp < l) {
- l = tmp;
- reverse(path.begin() + i + 1, path.begin() + j + 1);
- flag = 1;
- }
- }
- }
- }
- if (flag == 1) {
- travel(graph, path, l);
- }
- }
- int main() {
- std::srand(unsigned(std::time(0)));
- int n;
- cin >> n;
- vector<pair<int, int>> cities;
- for (size_t i = 0; i < n; ++i) {
- int x, y;
- cin >> x >> y;
- cities.push_back(make_pair(x, y));
- }
- vector<vector<double>> graph(n);
- for (size_t i = 0; i < n; ++i) {
- graph[i].resize(n);
- }
- if (n == 1) {
- cout << 1;
- return 0;
- }
- if (n == 2) {
- cout << " 1 2 1";
- return 0;
- }
- for (size_t i = 0; i < n; ++i) {
- for (size_t j = 0; j < n; ++j) {
- if (i != j) {
- graph[i][j] =
- sqrt((cities[i].first - cities[j].first) *
- (cities[i].first - cities[j].first) +
- (cities[i].second - cities[j].second) *
- (cities[i].second - cities[j].second));
- }
- }
- }
- vector<int> path(n), best, visited(n);
- double l = 0, best_l;
- best.push_back(0);
- visited[0] = 1;
- for (size_t i = 1; i <= n; ++i) {
- float tmp = 100000000000;
- int ptr;
- ptr = -1;
- for (size_t j = 1; j < n; ++j) {
- if (visited[j] != 1 && best[i - 1] != j) {
- if (graph[best[i - 1]][j] < tmp) {
- ptr = j;
- tmp = graph[best[i - 1]][j];
- }
- }
- }
- if (ptr == -1) {
- } else {
- best.push_back(ptr);
- visited[ptr] = 1;
- }
- }
- best.push_back(0);
- for (size_t i = 0; i < n; ++i) {
- l += graph[best[i]][best[(i + 1) % n]];
- }
- travel(graph, best, l);
- path = best;
- best_l = l;
- random_shuffle(best.begin() + 1, best.end() - 1);
- for (size_t k = 0; k <= 20; ++k) {
- random_shuffle(best.begin() + 1, best.end() - 1);
- l = 0;
- for (size_t i = 0; i < n; ++i) {
- l += graph[best[i]][best[(i + 1) % n]];
- }
- travel(graph, best, l);
- if (l < best_l) {
- path = best;
- random_shuffle(best.begin() + 1, best.end() - 1);
- }
- }
- for (auto i : path) {
- cout << i + 2 - 1 << " ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement