#include <iostream> #include <cstring> #include <cstdlib> #include <climits> #include <vector> #define MAX_N 10 int d[MAX_N][MAX_N]; int dp[1<<MAX_N][MAX_N]; int n; using namespace std; int dfs_tsp(int S, int v) { if (dp[S][v] >= 0) { return dp[S][v]; } if ((1<<n)-1 == S && v == 0) { return dp[S][v] = 0; } int res = INT_MAX/2; for (int u=0; u<n; u++) { if (!((S>>u) & 1)) { res = min(res, dfs_tsp(S|(1<<u), u) + d[v][u]); } } return dp[S][v] = res; } void dfs_path(int S, int v, vector<int>& path) { if ((1<<n)-1 == S && v == 0) { return; } int res = INT_MAX / 2; int idx = -1; for (int u=0; u<n; u++) { int cdst = dp[S|(1<<u)][u] + d[v][u]; if (!((S>>u) & 1) && cdst < res) { idx = u; res = cdst; } } path.push_back(idx); dfs_path(S|(1<<idx), idx, path); } int main() { n = 5; memset(dp, -1, sizeof(dp)); for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { d[i][j] = INT_MAX/2; } } d[0][1] = 3; d[0][3] = 4; d[4][0] = 7; d[4][1] = 6; d[3][4] = 3; d[2][0] = 4; d[2][3] = 5; d[1][2] = 5; int dst = dfs_tsp(0, 0); cout<<dst<<endl; vector<int> path(1,0); dfs_path(0, 0, path); for (int e:path) { cout<<e<<" "; } system("pause"); return 0; }
挑战程序设计P193. 其实还可以反向着来,不过实现起来比这个稍烦一些。