Advertisement
urmisaha

Travelling Salesman Problem

Oct 24th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define n 4
  3.  
  4. using namespace std;
  5.  
  6. // int n=4;
  7. int dist[n][n] = {
  8.         {0,20,42,25},
  9.         {20,0,30,34},
  10.         {42,30,0,10},
  11.         {25,34,10,0}
  12. };
  13.  
  14. vector<vector<int> > dp((1<<n), vector<int>(n, -1));
  15. int VISITED_ALL = (1<<n)-1;
  16.  
  17.  
  18. int tsp(int mask, int pos){
  19.     if(mask == VISITED_ALL)
  20.         return dist[pos][0];
  21.     if(dp[mask][pos] != -1)
  22.         return dp[mask][pos];
  23.     int d = INT_MAX;
  24.     for(int city=0; city<n; ++city)
  25.         if((mask & (1<<city)) == 0){
  26.             int res = dist[pos][city] + tsp(mask|(1<<city), city);
  27.             d = min(d, res);
  28.         }
  29.     return dp[mask][pos] = d;
  30. }
  31.  
  32. int main(){
  33.     cout<<tsp(1, 0);
  34.     return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement