#include <iostream>#include<cstring>#include<cstdlib>#include<climits>#include<vector>#defineMax_n 10intD[max_n][max_n];intdp[1<<Max_n] [Max_n];intN;using namespacestd;intDFS_TSP (intSintv) {if(Dp[s][v] >=0) { returnDp[s][v]; } if((1<<n)-1= = S && v = =0) { returnDP[S][V] =0; } intres = int_max/2; for(intu=0; u<n; u++) { if(! ((S>>u) &1) ) {res= Min (res, DFS_TSP (s| (1<<u), u) +D[v][u]); } } returnDP[S][V] =Res;}voidDfs_path (intSintV, vector<int>&path) { if((1<<n)-1= = S && v = =0) { return; } intres = INT_MAX/2; intIDX =-1; for(intu=0; u<n; u++) { intCDST = 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);}intMain () {n=5; Memset (DP,-1,sizeof(DP)); for(intI=0; i<n; i++) { for(intj=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; intDST = DFS_TSP (0,0); cout<<dst<<Endl; Vector<int> Path (1,0); Dfs_path (0,0, path); for(intE:path) {cout<<e<<" "; } System ("Pause"); return 0;}
Challenge Programming P193. In fact, it can be reversed, but the implementation is slightly more annoying.
tsp-Travel Business Issues