Raslboyy

3785

Oct 2nd, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <math.h>
  6. #include <functional>
  7. #define x first
  8. #define y second
  9.  
  10. using namespace std;
  11.  
  12. typedef pair<double, double> pr;
  13.  
  14. double dist(pr a, pr b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); }
  15.  
  16. int main() {
  17.     ifstream fin("input.txt");
  18.     ofstream fout("output.txt");
  19.  
  20.     int n; fin >> n;
  21.     vector<pr> vec(n); for (int i = 0; i < n; i++) fin >> vec[i].x >> vec[i].y;
  22.     vector<vector<double>> dp(n, vector<double>(1 << n, 1e9)); dp[0][0] = 0;
  23.  
  24.     for (int mask = 0; mask < (1 << n); mask++) {
  25.         for (int from = 0; from < n; from++) {
  26.             if (dp[from][mask] == 1e9) continue;
  27.             for (int to = 0; to < n; to++) {
  28.                 if (!((mask >> to) & 1))
  29.                     if (dp[from][mask] + dist(vec[from], vec[to]) < dp[to][mask | (1 << to)]) {
  30.                         dp[to][mask | (1 << to)] = dp[from][mask] + dist(vec[from], vec[to]);
  31.                     }
  32.             }
  33.         }
  34.  
  35.     }
  36.     fout << fixed << dp[0][(1 << n) - 1] << endl;
  37.     function<void(int, int)> print = [&](int cur, int mask) {
  38.         if (cur == 0 && mask == 0) return;
  39.         for (int i = 1; i < n; i++) {
  40.             if (i != cur && dp[cur][mask] == dp[i][(mask & (~(1 << cur)))] + dist(vec[i], vec[cur])) {
  41.                 print(i, mask & (~(1 << cur)));
  42.                 fout << i + 1 << " "; break;
  43.             }
  44.         }
  45.     };
  46.     print(0, (1 << n) - 1);
  47.  
  48.     fin.close();
  49.     fout.close();
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment