Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <math.h>
- #include <vector>
- using std::cin;
- using std::cout;
- double dist(std::pair<int, int> a,
- std::pair<int, int> b) {
- return sqrt(pow((a.first - b.first), 2) + pow((a.second - b.second), 2));
- }
- // double sum(std::vector<std::pair<int, int>>& graph,
- // std::vector<double>& vertexes) {
- // double res = 0;
- // for (int i = 0; i != graph.size(); ++i) {
- // sum += dist(graph[vertexes[i]], graph[vertexes[i + 1]]);
- // }
- // return sum;
- // }
- std::vector<int> greedyBoy(std::vector<std::pair<double, double>>& graph) {
- int n = graph.size();
- std::vector<int> used(n, 0);
- std::vector<int> res(n + 1);
- used[0] = 1;
- res[0] = 0;
- res[n] = 0;
- int current = 0;
- for (int i = 1; i != n; ++i) {
- double minDist = -1;
- int minVert;
- for (int j = 0; j != n; ++j) {
- if (used[j] == 0 && (minDist > dist(graph[j], graph[current]) || minDist < 0)) {
- minDist = dist(graph[j], graph[current]);
- minVert = j;
- }
- }
- used[minVert] = 1;
- res[i] = minVert;
- current = minVert;
- }
- return res;
- }
- int main() {
- int n;
- cin >> n;
- std::vector<std::pair<double, double>> graph(n);
- for (int i = 0; i != n; ++i) {
- cin >> graph[i].first >> graph[i].second;
- }
- std::vector<int> res = greedyBoy(graph);
- for (int counter = 0; counter != 60; ++counter) {
- for (int i = 1; i != graph.size() - 1; ++i) {
- for (int j = i + 1; j != graph.size(); ++j) {
- if (dist(graph[res[i]], graph[res[i + 1]]) +
- dist(graph[res[j]], graph[res[j + 1]]) >
- dist(graph[res[i]], graph[res[j]]) +
- dist(graph[res[i + 1]], graph[res[j + 1]])) {
- std::reverse(res.begin() + i + 1, res.begin() + j + 1);
- }
- }
- }
- }
- for (int i : res) {
- cout << i + 1 << " ";
- }
- cout << "\n";
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement