Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. int mergesort(int *,int);
  9. int _mergesort(int *,int *,int,int);
  10. int merge(int *,int *,int,int,int);
  11.  
  12. int mergesort(int arr[],int n)
  13. {
  14. int temp[n];
  15. return _mergesort(arr,temp,0,n-1);
  16. }
  17.  
  18. int _mergesort(int arr[],int temp[],int left,int right)
  19. {
  20. int mid,count=0;
  21. if(right>left)
  22. {
  23. mid=(left+right)/2;
  24. count=_mergesort(arr,temp,left,mid);
  25. count+=_mergesort(arr,temp,mid+1,right);
  26. count+=merge(arr,temp,left,mid+1,right);
  27. }
  28. return count;
  29. }
  30.  
  31. int merge(int arr[],int temp[],int left,int mid,int right)
  32. {
  33. int i, j, k;
  34. int count = 0;
  35. i = left;
  36. j = mid;
  37. k = left;
  38. while ((i <= mid - 1) && (j <= right))
  39. {
  40. if (arr[i] <= arr[j])
  41. {
  42. temp[k++] = arr[i++];
  43. }
  44. else
  45. {
  46. temp[k++] = arr[j++];
  47. count = count + (mid - i);
  48. }
  49. }
  50. while (i <= mid - 1)
  51. temp[k++] = arr[i++];
  52. while (j <= right)
  53. temp[k++] = arr[j++];
  54. for (i=left; i <= right; i++)
  55. arr[i] = temp[i];
  56.  
  57. return count;
  58. }
  59.  
  60. int main()
  61. {
  62. int n,tc,i;
  63. cin>>tc;
  64. while(tc)
  65. {
  66. cin>>n;
  67. int arr[n];
  68. for(i=0;i<n;i++)
  69. cin>>arr[i];
  70. cout<<mergesort(arr,n);
  71. tc--;
  72. }
  73. return 0;
  74. }
  75.  
  76. The example test case is
  77. Sample Input:
  78. 2
  79. 5
  80. 1 1 1 2 2
  81. 5
  82. 2 1 3 1 2
  83.  
  84. Sample Output:
  85. 0
  86. 4
  87.  
  88. 2: .
  89. 3: ..
  90. 4: ...
  91. 5: ....
  92.  
  93. swaps=0;
  94. for all keys in array{
  95. insert in Order statistic Tree;
  96. g=current one based index-Rank(key);
  97. count+=g;
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement