DuongNhi99

BCTSP

Dec 10th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 20;
  5.  
  6. int n;
  7. int a[N][N];
  8. int cache[N][1 << N];
  9. int FULL;
  10.  
  11. bool get_bit(int x, int k) {
  12.     return (x >> k) & 1;
  13. }
  14.  
  15. int dp(int i, int mask) {
  16.     if(mask == FULL) return a[i][1];
  17.     if(cache[i][mask] != -1) return cache[i][mask];
  18.  
  19.     int ans = 1e8;
  20.     for(int j = 1; j <= n; ++j) {
  21.         if(get_bit(mask, j)) continue;
  22.  
  23.         ans = min(ans, dp(j, mask | (1 << j)) + a[i][j]);
  24.     }
  25.  
  26.     return cache[i][mask] = ans;
  27. }
  28.  
  29. int main() {
  30.     //freopen("in.txt", "r", stdin);
  31.     //freopen("BCTSP.inp", "r", stdin);
  32.     //freopen("BCTSP.out", "w", stdout);
  33.     ios_base::sync_with_stdio(false);
  34.     cin.tie(NULL); cout.tie(NULL);
  35.  
  36.     cin >> n;
  37.     for(int i = 1; i <= n; ++i)
  38.         for(int j = 1; j <= n; ++j)
  39.             cin >> a[i][j];
  40.  
  41.     FULL = ((1 << n) - 1) << 1;
  42.     memset(cache, -1, sizeof(cache));
  43.  
  44.     cout << dp(1, 1 << 1);
  45.  
  46.     return 0;
  47. }
  48.  
Add Comment
Please, Sign In to add comment