Try   HackMD

Problem

  • Input: number of cites, number of roads, a sequence of roads

  • Output: Minimum cost of travelling through all the cities.

All permutation of cities.

  • Time complexity:
    O(n!)
    , where
    n
    is the number of cities.

Dynamic Programming

f(s,C): the minimum cost to extend a path, which passes all cities in
C
and ends at
s
.

Answer:

f(1,{c1}) (if we started at city 1)

f(s,C)={ws,1,if C={c1,…,cn}mint∉C{f(t,C âˆª {t})+ws,t},otherwise

  • Time complexity:
    O(n2â‹…2n)

Implementation

int n; vector<vector<int>> w; vector<vector<int>> dp; // n * (1 << n) int travelling_salesperson(int s, int C) { if (dp[s][C] != -1) return dp[s][C] if (C == (1 << n) - 1) return dp[s][C] = w[s][0]; int ans = 0x3fffffff; for (int t = 1; t < n; ++t) { if (C & (1 << t)) continue; ans = min(ans, TSP(t, C | (1 << t)) + w[s][t]); } return dp[s][C] = ans; } // answer: TSP(0, 1)