ibragimova_mariam

Задача коммивояжера

Mar 24th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Test
  4. {
  5. static int n;
  6. static int[][] a;
  7. static boolean[] used;
  8. static int[] curr_ans;
  9. static int min_len = Integer.MAX_VALUE;
  10.  
  11. static int[] ans;
  12.  
  13. private static void bal(int idx, int len, int last_city)
  14. {
  15. if (len >= min_len)
  16. return;
  17.  
  18. if (idx == n)
  19. {
  20. len += a[last_city][0];
  21. if (len >= min_len)
  22. return;
  23.  
  24. for (int i = 0; i < n; i++)
  25. {
  26. ans[i] = curr_ans[i];
  27. }
  28. min_len = len;
  29. return;
  30. }
  31.  
  32. for (int i = 1; i < n; i++)
  33. {
  34. if (used[i])
  35. continue;
  36.  
  37. used[i] = true;
  38. curr_ans[idx] = i;
  39. bal(idx + 1, len + a[last_city][i], i);
  40. used[i] = false;
  41. }
  42. }
  43.  
  44. public static void main(String[] args)
  45. {
  46. readInput();
  47.  
  48. int idx = 0;
  49. curr_ans[idx++] = 0;
  50.  
  51. for (int i = 1; i < n; i++)
  52. {
  53. used[i] = true;
  54. curr_ans[idx] = i;
  55. bal(idx + 1, a[0][i], i);
  56. used[i] = false;
  57. }
  58.  
  59. printAns();
  60. }
  61.  
  62. static void readInput()
  63. {
  64. System.out.println("Enter values: ");
  65. Scanner sc = new Scanner(System.in);
  66. n = sc.nextInt();
  67. a = new int[n][n];
  68. used = new boolean[n];
  69. curr_ans = new int[n];
  70. for (int i = 0; i < n; i++)
  71. {
  72. for (int j = 0; j < n; j++)
  73. {
  74. a[i][j] = sc.nextInt();
  75. }
  76. }
  77. ans = new int[n];
  78. }
  79.  
  80. static void printAns()
  81. {
  82. System.out.println("ans_len: " + min_len);
  83. for (int i = 0; i < n; i++)
  84. {
  85. System.out.print(ans[i] + " " );
  86. }
  87. }
  88. }
Add Comment
Please, Sign In to add comment