Advertisement
ivnikkk

Untitled

Dec 19th, 2022
651
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #define debug(l) cerr<<#l<<' '<<l<<'\n';
  3. #include "bits/stdc++.h"
  4. using namespace std;
  5. #define all(mask) mask.begin(), mask.end()
  6. typedef long long ll;
  7. typedef pair<ll, ll> pll;
  8. typedef pair<int, int> pii;
  9. typedef long double ld;
  10. signed main() {
  11. #ifdef _DEBUG
  12.     freopen("input.txt", "r", stdin);
  13.     freopen("output.txt", "w", stdout);
  14. #endif
  15.     ios_base::sync_with_stdio(false);
  16.     cin.tie(nullptr);
  17.     cout.tie(nullptr);
  18.     map<int, int> log;
  19.     vector<vector<int>>ed;
  20.     int n;
  21.     cin >> n;
  22.     vector<vector<int>> gr;
  23.     gr.resize(n);
  24.     ed.resize(n, vector<int>(n));
  25.     for (int i = 0; i < n; i++) {
  26.         for (int j = 0; j < n; j++) {
  27.             cin >> ed[i][j];
  28.             if (ed[i][j] > 0) {
  29.                 gr[i].push_back(j);
  30.             }
  31.         }
  32.     }
  33.    
  34.     vector<vector<pll>> dp(1ll << n, vector<pll>(n, { 1e13,1e13 }));
  35.     dp[1][0] = { 0,-1 };
  36.     for (ll mask = 1; mask < (1ll << n); mask++) {
  37.         for (ll from = 0; from < n; from++) {
  38.             for (int& to : gr[from]) {
  39.                 if (((1ll << to) & mask) || !((1ll << from) & mask)) continue;
  40.                 dp[mask | (1ll << to)][to] = min(dp[mask | (1ll << to)][to], { dp[mask][from].first + ed[from][to], from });
  41.             }
  42.         }
  43.     }
  44.  
  45.     pll ans = { 1e13,-1 };
  46.     ll last = (1ll << n) - 1ll;
  47.     ll v;
  48.     for (ll i = 0; i < n; i++) {
  49.         ans = min(ans, dp[last][i]);
  50.         if (ans == dp[last][i]) {
  51.             v = i;
  52.         }
  53.     }
  54.     if (ans.first == 1e13) {
  55.         cout << -1 << '\n';
  56.         return 0;
  57.     }
  58.     cout << ans.first << '\n';
  59.     vector<ll> par;
  60.     while (v != -1) {
  61.         par.push_back(v);
  62.         ll x = v;
  63.         v = dp[last][v].second;
  64.         last ^= (1ll << x);
  65.     }
  66.     reverse(all(par));
  67.     for (ll& i : par) {
  68.         cout << i + 1 << ' ';
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement