Advertisement
meta1211

Untitled

Sep 24th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int** Create(int N, int maxRange)
  4. {
  5. int **Matrix = new int *[N];
  6. if (Matrix == NULL) //if N == 0
  7. return Matrix;
  8. srand(0);
  9. for (int i = 0; i < N; i++)
  10. {
  11. Matrix[i] = new int[N];
  12. for (int j = 0; j < N; j++)
  13. {
  14.  
  15. if (i == j)
  16. Matrix[i][j] = 0;
  17. else
  18. Matrix[i][j] = rand() % maxRange + 1;//from 1 to RANGE_MAX
  19. std::cout << Matrix[i][j] << ' ';
  20. }
  21. std::cout << '\n';
  22. }
  23. std::cout << '\n';
  24. return Matrix;
  25. }
  26.  
  27. void swap(int *i, int *j)
  28. {
  29. int s = *i;
  30. *i = *j;
  31. *j = s;
  32. }
  33.  
  34. bool NextSet(int *a, int n)
  35. {
  36. int j = n - 2;
  37. for (; j != -1 && a[j] >= a[j + 1]; j--);
  38. if (j == -1)
  39. return false; // больше перестановок нет
  40. int k = n - 1;
  41. for (; a[j] >= a[k]; k--);
  42. swap(&a[j], &a[k]);
  43. int l = j + 1, r = n - 1;
  44. while (l < r)
  45. {
  46. swap(&a[l++], &a[r--]);
  47. }
  48. return true;
  49. }
  50. template <typename T>
  51. void CopyArray(T *arr, T *source, int sourceLen, int start = 0)
  52. {
  53. for (int i = 0; i < sourceLen; i++)
  54. {
  55. arr[i + start] = source[i];
  56. }
  57. }
  58.  
  59. int FindPrice(int **matrix, int *order, int n)
  60. {
  61. int price = 0;
  62. for (int i = 1; i < n; i++)
  63. {
  64. price += matrix[order[i - 1]][order[i]];
  65. }
  66. price += matrix[order[n - 1]][order[0]];
  67. return price;
  68. }
  69.  
  70. int *FindBestWay(int **matrix,int citiesCount)
  71. {
  72. int *curentWay = new int[citiesCount];
  73. int *bestWay = new int[citiesCount];
  74. int bestWayLength = INT16_MAX;
  75. int curentWayLength;
  76. for (int i = 0; i < citiesCount; i++)
  77. {
  78. curentWay[i] = i;
  79. }
  80.  
  81. while (NextSet(curentWay, citiesCount))
  82. {
  83. curentWayLength = FindPrice(matrix, curentWay, citiesCount);
  84. if (curentWayLength < bestWayLength)
  85. {
  86. bestWayLength = curentWayLength;
  87. CopyArray(bestWay, curentWay, citiesCount);
  88. }
  89. }
  90. return bestWay;
  91. }
  92.  
  93. int main()
  94. {
  95. int **matrix = Create(4, 10);
  96. int *way = FindBestWay(matrix, 4);
  97. for (int i = 0; i < 4; i++)
  98. {
  99. std::cout << way[i] + 1 << ' ';
  100. }
  101. std::cout << '\n'<< "Way Lentgth: " << FindPrice(matrix, way, 4);
  102. return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement