Advertisement
Tevronis

dp. comi

Feb 26th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstring>
  3. #include <ios>
  4.  
  5. using namespace std;
  6.  
  7. #define SIZE 16
  8. #define INF 1000000000
  9.  
  10. int n;
  11. int cost[SIZE][SIZE];
  12. int dp[1<<SIZE][SIZE];
  13.  
  14. int calcdp(int mask, int last) {
  15.    
  16.     int &res = dp[mask][last];
  17.    
  18.     if (res != -1)
  19.         return res;
  20.        
  21.     res = INF;
  22.    
  23.     if (mask == 1) {
  24.         if (cost[0][last])
  25.             res = cost[0][last];
  26.         return res;
  27.     }
  28.    
  29.     for (int i = 1; i < n; ++i) {
  30.         int m = 1 << i;
  31.         if (mask & m && cost[i][last]) {
  32.             res = min(res, calcdp(mask ^ m, i) + cost[i][last]);
  33.         }
  34.     }
  35.    
  36.     return res;
  37.    
  38. }
  39.  
  40. int main() {
  41.    
  42.     memset(dp, 255, sizeof(dp));
  43.    
  44.     scanf("%d", &n);
  45.     for (int i = 0; i < n; ++i)
  46.         for (int j = 0; j < n; ++j)
  47.             scanf("%d", &cost[i][j]);
  48.    
  49.     int res = calcdp((1<<n)-1, 0);     
  50.     printf("%d", res == INF ? -1 : res);
  51.    
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement