NP-Nidzo

Traveling Salesman Problem

Aug 14th, 2020
2,072
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1.  
  2. /**------------------------
  3.     Author : NikolaP
  4.     Compiler : C++
  5. -------------------------*/
  6.  
  7. //{         Setup
  8.  
  9.     #include <bits/stdc++.h>
  10.     using namespace std;
  11.  
  12.     typedef long long int ll;
  13.     typedef long double ld;
  14.     typedef vector<int> vi;
  15.  
  16.     const int inf = INT_MAX;
  17.     const bool debug = 0;
  18.  
  19. //}
  20.  
  21. struct TSP{
  22.     int n;
  23.     vector<vi> graph;
  24.     vector<vi> dp;
  25.  
  26.     TSP(int _n, int m){
  27.         n = _n;
  28.         graph.assign(n,vi(n,inf));
  29.         dp.assign(n,vi((1 << n) - 1, inf));
  30.  
  31.         while(m--){
  32.             int from,to,cost;
  33.             cin >> from >> to >> cost;
  34.             graph[from][to] = cost;
  35.             graph[to][from] = cost;
  36.         }
  37.     }
  38.  
  39.     int tsp(int position, int visited, int start){
  40.         if(visited == (1 << n) - 1) return graph[position][start];
  41.  
  42.         if(dp[position][visited] != inf) return dp[position][visited];
  43.  
  44.         for(int i = 0; i < n; ++i){
  45.             if(i == position or (visited & (1 << i))) continue;
  46.  
  47.             int distance = graph[position][i] + tsp(i, visited | (1 << i), start);
  48.             dp[position][visited] = min(dp[position][visited] , distance);
  49.         }
  50.  
  51.         return dp[position][visited];
  52.     }
  53.  
  54.     int Solution(){
  55.         int ans = inf;
  56.  
  57.         for(int i = 0; i < n; ++i){
  58.             ans = min(ans, tsp(i, 1 << i, i));
  59.         }
  60.  
  61.         return ans;
  62.     }
  63. };
  64.  
  65. int main()
  66. {
  67.     ios::sync_with_stdio(false);
  68.     cin.tie(0);
  69.     cout.precision(8);
  70.     //cout << fixed;
  71.  
  72.     int n,m;
  73.     cin >> n >> m;
  74.     TSP idk = TSP(n,m);
  75.     cout << idk.Solution();
  76.     return 0;
  77. }
  78.  
  79.  
  80.  
  81.  
Advertisement
Add Comment
Please, Sign In to add comment