Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //NB: Do not add a package
- //NB: Importing other classes is NOT ALLOWED
- import java.util.Scanner;
- // NB: For the judge to run the program, do not modify the declaration of the class Main or
- // method main() below. The class has to be declared as "class Main { ... }"
- // and the method as "public static void main(String[] args) { ... }"
- class Main
- {
- public static void main(String[] args)
- {
- Scanner scanner = new Scanner(System.in);
- int ntestcases = scanner.nextInt();
- for(int testno=0; testno<ntestcases; testno++)
- {
- int n = scanner.nextInt();
- int[] A = new int[n];
- for(int i=0; i<n; i++)
- A[i] = scanner.nextInt();
- System.out.println(solve(A));
- }
- scanner.close();
- }
- //"A" is the input vector.
- //The number of elements of A can be accessed using A.length
- static int solve(int[] A)
- {
- return mergesort(A);
- }
- private static int mergesort(int[] A) { //Array not sorted
- int left = 0;
- int numInversions=0;
- do {
- int right = -1;
- while (right < A.length-1) {
- left = right + 1;
- int middle = left;
- while (middle < A.length-1 && A[middle+1] >= A[middle]) {
- middle ++;
- }
- if (middle < A.length-1) {
- right = middle + 1;
- while (right < A.length-1 && A[right+1] >= A[right]) {
- right ++;
- }
- numInversions += merge(A, left, middle, right);
- } else {
- right = A.length-1;
- }
- }
- } while (left != 0);
- return numInversions;
- }
- public static int merge(int[] A, int left, int middle, int right) {
- int[] B = new int[A.length];
- for (int z = left; z <= right; z++) {
- B[z] = A[z];
- }
- int i = left;
- int j = middle + 1;
- int k = left;
- int numInversions = 0;
- while ((i <= middle) && (j <= right)) {
- if (B[i] <= B[j]) {
- A[k] = B[i];
- i++;
- } else {
- A[k] = B[j];
- j++;
- numInversions += (middle-i+1);
- }
- k++;
- }
- return numInversions;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement