fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. const int MAX_N = 20;
  6. int n;
  7. double dist[MAX_N][MAX_N];
  8. int prev[MAX_N];
  9.  
  10. double optval = INFINITY;
  11. int optsol[MAX_N];
  12.  
  13. void solve(int u = 0) {
  14. bool end = true;
  15. for (int v = 0; v < n; ++v) {
  16. if (prev[v] == -1) {
  17. end = false;
  18. prev[v] = u;
  19. solve(v);
  20. prev[v] = -1;
  21. }
  22. }
  23. if (end) {
  24. double length = dist[u][0];
  25. for (int v = u; v != 0; v = prev[v])
  26. length += dist[prev[v]][v];
  27. if (length < optval) {
  28. optval = length;
  29. for (int i = 0; i < n; ++i)
  30. optsol[i] = prev[i];
  31. optsol[0] = u;
  32. }
  33. }
  34. }
  35.  
  36. int main() {
  37. // get input
  38. cin >> n;
  39. for (int i = 0; i < n; ++i)
  40. for (int j = 0; j < n; ++j)
  41. cin >> dist[i][j];
  42.  
  43. for (int i = 0; i < n; ++i)
  44. prev[i] = -1;
  45. prev[0] = 0;
  46.  
  47. solve();
  48.  
  49. for (int u = optsol[0]; u != 0; u = optsol[u])
  50. cout << u+1 << " <- ";
  51. cout << 1 << " : " << optval << endl;
  52. }
Success #stdin #stdout 0.01s 2816KB
stdin
  6
  0 470 550 420 300 200 
  470 0 800 900 770 560 
  550 800 0 330 650 750 
  420 900 330 0 450 400 
  300 770 650 450 0 180 
  200 560 750 400 180 0 
stdout
6 <- 5 <- 4 <- 3 <- 2 <- 1  :  2430