Advertisement
Guest User

Untitled

a guest
Nov 19th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. //NB: Do not add a package
  2.  
  3. //NB: Importing other classes is NOT ALLOWED
  4. import java.util.Scanner;
  5.  
  6. // NB: For the judge to run the program, do not modify the declaration of the class Main or
  7. // method main() below. The class has to be declared as "class Main { ... }"
  8. // and the method as "public static void main(String[] args) { ... }"
  9. class Main
  10. {
  11. public static void main(String[] args)
  12. {
  13. Scanner scanner = new Scanner(System.in);
  14. int ntestcases = scanner.nextInt();
  15.  
  16. for(int testno=0; testno<ntestcases; testno++)
  17. {
  18. int n = scanner.nextInt();
  19. int[] A = new int[n];
  20.  
  21. for(int i=0; i<n; i++)
  22. A[i] = scanner.nextInt();
  23.  
  24. System.out.println(solve(A));
  25. }
  26.  
  27. scanner.close();
  28. }
  29. //"A" is the input vector.
  30. //The number of elements of A can be accessed using A.length
  31. static int solve(int[] A)
  32. {
  33. return mergesort(A);
  34. }
  35.  
  36. private static int mergesort(int[] A) { //Array not sorted
  37. int left = 0;
  38. int numInversions=0;
  39. do {
  40. int right = -1;
  41. while (right < A.length-1) {
  42. left = right + 1;
  43. int middle = left;
  44. while (middle < A.length-1 && A[middle+1] >= A[middle]) {
  45. middle ++;
  46. }
  47. if (middle < A.length-1) {
  48. right = middle + 1;
  49. while (right < A.length-1 && A[right+1] >= A[right]) {
  50. right ++;
  51. }
  52. numInversions += merge(A, left, middle, right);
  53. } else {
  54. right = A.length-1;
  55. }
  56. }
  57. } while (left != 0);
  58. return numInversions;
  59. }
  60.  
  61.  
  62. public static int merge(int[] A, int left, int middle, int right) {
  63. int[] B = new int[A.length];
  64. for (int z = left; z <= right; z++) {
  65. B[z] = A[z];
  66. }
  67. int i = left;
  68. int j = middle + 1;
  69. int k = left;
  70. int numInversions = 0;
  71.  
  72. while ((i <= middle) && (j <= right)) {
  73. if (B[i] <= B[j]) {
  74. A[k] = B[i];
  75. i++;
  76. } else {
  77. A[k] = B[j];
  78. j++;
  79. numInversions += (middle-i+1);
  80. }
  81. k++;
  82. }
  83. return numInversions;
  84. }
  85.  
  86.  
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement