Advertisement
mateuspl

caxeiro

Apr 2nd, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <string.h>
  3.  
  4. using namespace std;
  5.  
  6. int solve(int, long);
  7.  
  8. const int NOT_SOLVED = -1;
  9. const int MAX_INT = ~(1 << 31);
  10.  
  11. int nVertices;
  12. long allVisited;
  13. int** distances;
  14. int** solved;
  15.  
  16. int nReachedSolutionEnd = 0;
  17. int nSolvedAttribution = 0;
  18. int nSolvedUsed = 0;
  19.  
  20. int main()
  21. {
  22. cin >> nVertices;
  23.  
  24. if (nVertices > 65)
  25. {
  26. cout << "This algorithm can not solve this problem." << endl;
  27. cout << "The number of vertices, " << nVertices << ", is too hight!" << endl;
  28. cout << "The supported number of vertices is 65." << endl;
  29. return 1;
  30. }
  31.  
  32. allVisited = (1 << (nVertices - 1)) - 1;
  33.  
  34. distances = new int*[nVertices];
  35. solved = new int*[nVertices];
  36.  
  37. long solvedSize = allVisited - 1;
  38.  
  39. cout << "nVertices " << nVertices << endl;
  40. cout << "solvedSize " << solvedSize << endl;
  41.  
  42. cout << "allVisited ";
  43. for (int i = nVertices - 2; i >= 0; i--)
  44. cout << ((allVisited & (1 << i)) ? 1 : 0);
  45. cout << " (" << allVisited << ")" << endl;
  46.  
  47. for (int row = 0; row < nVertices; row++)
  48. {
  49. distances[row] = new int[nVertices];
  50.  
  51. for (int col = 0; col < nVertices; col++)
  52. cin >> distances[row][col];
  53.  
  54. solved[row] = new int[solvedSize];
  55. memset(solved[row], NOT_SOLVED, solvedSize * sizeof(int));
  56. }
  57.  
  58. cout << solve(0, 0) << endl;
  59. cout << "Reached solution end " << nReachedSolutionEnd << " times." << endl;
  60. cout << "Solved array alements were attributed " << nSolvedAttribution << " times." << endl;
  61. cout << "Used solved values " << nSolvedUsed << " times." << endl;
  62.  
  63. return 0;
  64. }
  65.  
  66. int solve(int from, long visited)
  67. {
  68. if (visited == allVisited)
  69. {
  70. nReachedSolutionEnd++;
  71. return distances[from][0];
  72. }
  73.  
  74. if (solved[from][visited] != NOT_SOLVED)
  75. {
  76. nSolvedUsed++;
  77. return solved[from][visited];
  78. }
  79.  
  80. cout << "At " << from << ", visited ";
  81. for (int i = nVertices - 2; i >= 0; i--)
  82. cout << ((visited & (1 << i)) ? 1 : 0);
  83. cout << " (" << visited << ")" << endl;
  84.  
  85. int shortest = MAX_INT;
  86.  
  87. for (int i = 1; i < nVertices; i++) {
  88. int vertice = 1L << (i - 1);
  89.  
  90. if (!(visited & vertice))
  91. {
  92. int distance = distances[from][i] + solve(i, visited | vertice);
  93. if (distance < shortest) shortest = distance;
  94. }
  95. }
  96.  
  97. nSolvedAttribution++;
  98. return solved[from][visited] = shortest;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement