Guest User

Untitled

a guest
Sep 29th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Solution {
  5.  
  6. public static void main(String[] args) {
  7. int t,n,res;
  8. Integer[] a;
  9. Scanner scn = new Scanner(System.in);
  10.  
  11. t = scn.nextInt();
  12. while(t -- > 0){
  13. n = scn.nextInt();
  14. a = new Integer[n];
  15. for(int i = 0; i < n; ++i)
  16. a[i] = scn.nextInt();
  17. res = sortAndCount(a,0,n - 1);
  18. System.out.println(res);
  19. }
  20. }
  21.  
  22. public static int sortAndCount(Integer[] a, int l, int r){
  23. if(l < r){
  24. int mid = (l + r) / 2;
  25. int leftAns = sortAndCount(a,l,mid);
  26. int rightAns = sortAndCount(a,mid + 1, r);
  27. int leftAndRightAns = mergeAndCount(a,l,r,mid);
  28. return leftAns + rightAns + leftAndRightAns;
  29. }
  30. return 0;
  31. }
  32.  
  33. public static int mergeAndCount(Integer[] a, int l, int r, int mid){
  34. int n1 = mid - l + 1, n2 = r - mid;
  35. Integer[] left = new Integer[n1], right = new Integer[n2];
  36. int inversions = 0;
  37.  
  38. System.arraycopy(a,l,left,0,n1);
  39. System.arraycopy(a,mid + 1,right,0,n2);
  40.  
  41. int li = 0, ri = 0, ai = l;
  42. while(li < n1 && ri < n2){
  43. if(left[li] <= right[ri]){
  44. a[ai++] = left[li++];
  45. }else {
  46. inversions += (mid - (l + li) + 1);
  47. a[ai++] = right[ri++];
  48. }
  49. }
  50. while(li < n1){
  51. a[ai++] = left[li++];
  52. }
  53. while(ri < n2){
  54. a[ai++] = right[ri++];
  55. }
  56.  
  57. return inversions;
  58. }
  59. }
Add Comment
Please, Sign In to add comment