Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class Solution {
- public static void main(String[] args) {
- int t,n,res;
- Integer[] a;
- Scanner scn = new Scanner(System.in);
- t = scn.nextInt();
- while(t -- > 0){
- n = scn.nextInt();
- a = new Integer[n];
- for(int i = 0; i < n; ++i)
- a[i] = scn.nextInt();
- res = sortAndCount(a,0,n - 1);
- System.out.println(res);
- }
- }
- public static int sortAndCount(Integer[] a, int l, int r){
- if(l < r){
- int mid = (l + r) / 2;
- int leftAns = sortAndCount(a,l,mid);
- int rightAns = sortAndCount(a,mid + 1, r);
- int leftAndRightAns = mergeAndCount(a,l,r,mid);
- return leftAns + rightAns + leftAndRightAns;
- }
- return 0;
- }
- public static int mergeAndCount(Integer[] a, int l, int r, int mid){
- int n1 = mid - l + 1, n2 = r - mid;
- Integer[] left = new Integer[n1], right = new Integer[n2];
- int inversions = 0;
- System.arraycopy(a,l,left,0,n1);
- System.arraycopy(a,mid + 1,right,0,n2);
- int li = 0, ri = 0, ai = l;
- while(li < n1 && ri < n2){
- if(left[li] <= right[ri]){
- a[ai++] = left[li++];
- }else {
- inversions += (mid - (l + li) + 1);
- a[ai++] = right[ri++];
- }
- }
- while(li < n1){
- a[ai++] = left[li++];
- }
- while(ri < n2){
- a[ai++] = right[ri++];
- }
- return inversions;
- }
- }
Add Comment
Please, Sign In to add comment