Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- include <iostream>
- #include <vector>
- #include <list>
- #include <algorithm>
- #include <cmath>
- using std::cin;
- using std::cout;
- using Matrix = std::vector<std::vector<double>>;
- double dist(std::pair<double, double> vertex1, std::pair<double, double> vertex2) {
- return sqrt((vertex1.first - vertex2.first) * (vertex1.first - vertex2.first)
- + (vertex1.second - vertex2.second) * (vertex1.second - vertex2.second));
- }
- std::vector<size_t> local_search(const Matrix& graph) {
- std::vector<size_t> path(graph.size() + 1);
- path[0] = 0;
- path[graph.size()] = 0;
- size_t cur = 0;
- std::vector<bool> visited(graph.size());
- visited[0] = true;
- double min = -1;
- for (size_t i = 1; i != graph.size(); ++i) {
- for (size_t j = 0; j != graph.size(); ++j) {
- if (j != path[i - 1]) {
- if ((min == -1 || graph[path[i - 1]][j] < min) && !visited[j]) {
- path[i] = j;
- min = graph[path[i - 1]][j];
- }
- }
- }
- visited[path[i]] = true;
- min = -1;
- }
- for (size_t k = 0; k != 10; ++k) {
- for (size_t i = 1; i != graph.size() - 1; ++i) {
- double difference = graph[path[i - 1]][path[i + 1]] + graph[path[i]][path[i + 2]]
- - graph[path[i - 1]][path[i]] - graph[path[i + 1]][path[i + 2]];
- // cout << "path num " << i << " diff" << difference << "\n";
- if (difference < 0) {
- std::swap(path[i], path[i + 1]);
- }
- }
- }
- for (size_t k = 0; k != 15; ++k) {
- for (size_t i = 1; i != graph.size() - 1; ++i) {
- for (size_t j = 1; j != graph.size() - 1; ++j) {
- if (i != j) {
- double difference =
- graph[path[i - 1]][path[j - 1]] + graph[path[i]][path[j]] -
- graph[path[i - 1]][path[i]] - graph[path[j - 1]][path[j]];
- if (difference < 0) {
- std::reverse(path.begin() + i, path.begin() + j);
- }
- }
- }
- }
- }
- return path;
- }
- int main() {
- size_t vertex_num;
- cin >> vertex_num;
- std::vector<std::pair<double, double>> vertexes(vertex_num);
- for (size_t i = 0; i != vertex_num; ++i) {
- int first, second;
- cin >> first >> second;
- vertexes[i] = std::make_pair(first, second);
- }
- if (vertex_num == 1) {
- cout << "1\n";
- return 0;
- } else if (vertex_num == 2) {
- cout << "1 2 1\n";
- return 0;
- }
- Matrix graph(vertex_num,
- std::vector<double>(vertex_num));
- for (size_t i = 0; i != vertex_num; ++i) {
- for (size_t j = 0; j != vertex_num; ++j) {
- graph[i][j] = dist(vertexes[i], vertexes[j]);
- }
- }
- auto result = local_search(graph);
- for (const auto& elem : result) {
- cout << elem + 1 << " ";
- }
- cout << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement