# include # include void perm_next ( int n, int p[], int &rank ); using namespace std; int main ( ) // // TRIP_COUNTING seeks the shortest round trip by checking every permutation. // { double dist[5][5] = { {0, 3, 4, 2, 7}, {3, 0, 4, 6, 3}, {4, 4, 0, 5, 8}, {2, 6, 5, 0, 6}, {7, 3, 8, 6, 0} }; double d, dmin; int i, n = 5, next, old, p[5], pmin[5], rank; dmin = 10000000; rank = -1; while ( true ) { // // Generate the next permutation. // perm_next ( n, p, rank ); if ( rank == -1 ) { break; } // // Compute the distance for this trip. // old = p[n-1]; d = 0.0; for ( i = 0; i < n; i++ ) { next = p[i]; d = d + dist[old][next]; old = next; } // // Is this distance shorter? // if ( d < dmin ) { dmin = d; for ( i = 0; i < n; i++ ) { pmin[i] = p[i]; } } } cout << "Shortest round trip has length " << dmin << "\n"; for ( i = 0; i < n; i++ ) { cout << " " << pmin[i]; } cout << "\n"; return 0; }