ann8497

mr lee airfare tsp samsung

Aug 17th, 2019
1,377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. #define INT_MAX 999999
  5.  
  6. int n=4;
  7. int dp[16][4];
  8.  
  9. // Adj Matrix which defines the graph
  10. int dist[10][10] = {
  11.         {0,20,42,25},
  12.         {20,0,30,34},
  13.         {42,30,0,10},
  14.         {25,34,10,0}
  15. };
  16.  
  17. //mask for all cities have been visited
  18. int VISITED_ALL = (1<<n) - 1;
  19.  
  20. int tsp(int mask,int pos){
  21.    
  22.     // base case
  23.     if(mask==VISITED_ALL){
  24.         return dist[pos][0];
  25.     }
  26.     //Lookup
  27.     if(dp[mask][pos]!=-1){
  28.         return dp[mask][pos];
  29.     }
  30.    
  31.     int ans = INT_MAX;
  32.  
  33.     //Try to goto an unvisited city
  34.     for(int city=0;city<n;city++){
  35.        
  36.         if((mask&(1<<city))==0){
  37.            
  38.             int newAns = dist[pos][city] + tsp( mask|(1<<city),city);
  39.             ans = min(ans,newAns);
  40.            
  41.         }
  42.     }
  43.     return dp[mask][pos] = ans;
  44. }
  45.  
  46. int main() {
  47.    
  48.     for(int i=0;i<(1<<n);i++){
  49.         for(int j=0;j<n;j++){
  50.             dp[i][j] = -1;
  51.         }
  52.     }
  53.    
  54.     cout<<tsp(1,0)<<endl;
  55.     return 0;
  56. }
Add Comment
Please, Sign In to add comment