Advertisement
Guest User

Untitled

a guest
May 4th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. /*
  2. Statement:
  3. ==========
  4. Let A[0...n - 1] be an array of n distinct positive integers. If i < j and A[i] > A[j] then the pair (i, j) is called an inversion of A. Given n and an array A your task is to find the number of inversions of A.
  5. Input
  6.  
  7. The first line contains t, the number of testcases followed by a blank space. Each of the t tests start with a number n (n <= 200000). Then n + 1 lines follow. In the ith line a number A[i - 1] is given (A[i - 1] <= 10^7). The (n + 1)th line is a blank space.
  8. Output
  9.  
  10. For every test output one line giving the number of inversions of A.
  11. Example
  12.  
  13. Input:
  14.  
  15. 2
  16.  
  17. 3
  18. 3
  19. 1
  20. 2
  21.  
  22. 5
  23. 2
  24. 3
  25. 8
  26. 6
  27. 1
  28.  
  29.  
  30. Output:
  31.  
  32. 2
  33. 5
  34. */
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. long long int count, *a;
  38. void merge(int,int,int);
  39. void f(int l,int r)
  40. {
  41. if(l<r)
  42. {
  43. int mid=(l+r)/2;
  44. f(l,mid);
  45. f(mid+1,r);
  46. merge(l,mid,r);
  47. }
  48. }
  49. void merge(int l,int mid,int r)
  50. {
  51. int temp[r-l+1],i=l,j=mid+1,k=0;
  52. while(i<=mid && j<=r)
  53. {
  54. if(a[i]>a[j] && i<=mid)
  55. {
  56. count+=1+mid-i;
  57. temp[k]=a[j];
  58. j++;
  59. k++;
  60. }
  61. else
  62. {
  63. temp[k]=a[i];
  64. i++;
  65. k++;
  66. }
  67. }
  68. while(i<=mid)temp[k++]=a[i++];
  69. while(j<=r)temp[k++]=a[j++];
  70. for(i=0;i<=r-l;i++)
  71. {
  72. a[l+i]=temp[i];
  73. }
  74. }
  75. int main()
  76. {
  77. int t;
  78. scanf("%d\n", &t);
  79. while(t--)
  80. {
  81. int n;
  82. count=0;
  83. scanf("%d",&n );
  84. a=(long long int*)malloc(sizeof (long long int)*n);
  85. for(int i=0;i<n;i++)scanf("%lld",&a[i] );
  86. f(0,n-1);
  87. printf("%lld\n", count);
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement