Advertisement
_Bad_Liar_

Untitled

Dec 14th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int MAX_INT = 2147483647;
  5. int dist[21][21];
  6. int otvet[10000000][21];
  7. int n_planet[10000000][21];
  8.  
  9. int rec(int mask, int pos, int n) {
  10.     if (otvet[mask][pos] != 0)
  11.         return otvet[mask][pos];
  12.     if (mask == (1 << n) - 1)
  13.         return 0;
  14.     int ans = MAX_INT;
  15.     for (int i = 0; i < n; i++) {
  16.         if (!((1 << i) & mask)) {
  17.             int x = rec(mask | (1 << i), i, n) + dist[pos][i];
  18.             ans = min(x, ans);
  19.             if (x == ans)
  20.                 n_planet[mask][pos] = i;
  21.         }
  22.     }
  23.     otvet[mask][pos] = ans;
  24.     return otvet[mask][pos];
  25. }
  26.  
  27.  
  28. int main() {
  29.     int n;
  30.     cin >> n;
  31.     int k;
  32.     for (int i = 0; i < n; i++) {
  33.         for (int j = 0; j < n; j++) {
  34.             cin >> k;
  35.             dist[i][j] = k;
  36.             if (i == j)
  37.                 dist[i][j] = 0;
  38.         }
  39.     }
  40.    
  41.     int ans = MAX_INT;
  42.     int planet;
  43.     for (int i = 0; i < n; i++) {
  44.         int tmp = rec(1 << i, i, n);
  45.         ans = min(tmp, ans);
  46.         if (tmp == ans)
  47.             planet = i;
  48.     }
  49.    
  50.     cout << ans << "\n";
  51.     cout << planet + 1<< " ";
  52.     int new_mask = 1 << planet;
  53.     for (int i = 0; i < n - 1; i++) {
  54.         cout << n_planet[new_mask][planet] + 1 << " ";
  55.         planet = n_planet[new_mask][planet];
  56.         new_mask = new_mask | (1 << planet);
  57.     }
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement