Traveling Sales Person

Created: 2019-12-08 Sun 14:57

Table of Contents

Objectives

  • Understand how to use DP to solve the TSP problem.
  • Know the limit of \(n\) for brute force and DP problems.

TSP

The Problem

  • You are given a set of nodes with weighted edges
    • cities and cost / time for travel
  • Want to make a tour, visit all cities, return to start.
  • What is the cheapest way to do this?
  • Time complexity
    • \({\cal O}(n!)\) — check each permutation
    • Fix first city to take advantage of symmetry gives \((n-1)!\) solutions.
    • In a contest, brute force check can work up to about \(n=11\), max.

Using DP

  • We can use the bitmask technique and top-down DP to speed this up.
vi dp(65536);  // we can't solve more than this anyway
int n;
int tsp(vvi &costs, int &mx, int cur, int state) {
   if (dp[state]>0) return dp[state];
   if (state == mx) return costs[cur][0]; // return home

   int minleft = INF;
   int bit=2;

   for(int i=1; i<n; ++i)  {
     if ( (state & bit) == 0) { // i not visited
        minleft = min(minleft, costs[cur][i] + tsp(costs,mx,i,state | bit));
     }
     bit <<= 1;
   }
   return dp[state]=minleft;
}

Setup

int main() {
   cin >> n;
   vvi adj(n);

   for(i=0; i<n; ++i)
      for(j=0; j<n; ++j) {
         cin >> c;
         adj[i].push_back(c);
      }

   mx = (1 << n) - 1;
   cout << "Best path has cost " << tsp(adj,mx,0,1) << endl;
}