Advertisement
great_lexa

Untitled

Oct 4th, 2018
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <math.h>
  4. #include <vector>
  5.  
  6. using std::cin;
  7. using std::cout;
  8.  
  9. double dist(std::pair<int, int> a,
  10.             std::pair<int, int> b) {
  11.     return sqrt(pow((a.first - b.first), 2) + pow((a.second - b.second), 2));
  12. }
  13.  
  14. // double sum(std::vector<std::pair<int, int>>& graph,
  15. //         std::vector<double>& vertexes) {
  16. //     double res = 0;
  17. //     for (int i = 0; i != graph.size(); ++i) {
  18. //         sum += dist(graph[vertexes[i]], graph[vertexes[i + 1]]);
  19. //     }
  20. //     return sum;
  21. // }
  22.  
  23. std::vector<int> greedyBoy(std::vector<std::pair<double, double>>& graph) {
  24.     int n = graph.size();
  25.     std::vector<int> used(n, 0);
  26.     std::vector<int> res(n + 1);
  27.     used[0] = 1;
  28.     res[0] = 0;
  29.     res[n] = 0;
  30.     int current = 0;
  31.     for (int i = 1; i != n; ++i) {
  32.         double minDist = -1;
  33.         int minVert;
  34.         for (int j = 0; j != n; ++j) {
  35.             if (used[j] == 0 && (minDist > dist(graph[j], graph[current]) || minDist < 0)) {
  36.                 minDist = dist(graph[j], graph[current]);
  37.                 minVert = j;
  38.             }
  39.         }
  40.         used[minVert] = 1;
  41.         res[i] = minVert;
  42.         current = minVert;
  43.     }
  44.     return res;
  45. }
  46.  
  47. int main() {
  48.     int n;
  49.     cin >> n;
  50.     std::vector<std::pair<double, double>> graph(n);
  51.  
  52.     for (int i = 0; i != n; ++i) {
  53.         cin >> graph[i].first >> graph[i].second;
  54.     }
  55.  
  56.     std::vector<int> res = greedyBoy(graph);
  57.  
  58.     for (int counter = 0; counter != 60; ++counter) {
  59.         for (int i = 1; i != graph.size() - 1; ++i) {
  60.             for (int j = i + 1; j != graph.size(); ++j) {
  61.                 if (dist(graph[res[i]], graph[res[i + 1]]) +
  62.                         dist(graph[res[j]], graph[res[j + 1]]) >
  63.                     dist(graph[res[i]], graph[res[j]]) +
  64.                         dist(graph[res[i + 1]], graph[res[j + 1]])) {
  65.                     std::reverse(res.begin() + i + 1, res.begin() + j + 1);
  66.                 }
  67.             }
  68.         }
  69.     }
  70.  
  71.     for (int i : res) {
  72.         cout << i + 1 << " ";
  73.     }
  74.     cout << "\n";
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement