Advertisement
Guest User

Untitled

a guest
Oct 17th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Merges two subarrays of arr[].
  5. // First subarray is arr[l..m]
  6. // Second subarray is arr[m+1..r]
  7. void merge(int arr[], int l, int m, int r, int* count_crossline)
  8. {
  9. int i, j, k;
  10. int n1 = m - l + 1;
  11. int n2 = r - m;
  12.  
  13. /* create temp arrays */
  14. int L[n1], R[n2];
  15.  
  16. /* Copy data to temp arrays L[] and R[] */
  17. for (i = 0; i < n1; i++)
  18. L[i] = arr[l + i];
  19. for (j = 0; j < n2; j++)
  20. R[j] = arr[m + 1 + j];
  21.  
  22. /* Merge the temp arrays back into arr[l..r]*/
  23. i = 0; // Initial index of first subarray
  24. j = 0; // Initial index of second subarray
  25. k = l; // Initial index of merged subarray
  26. while (i < n1 && j < n2) {
  27. if (L[i] <= R[j]) {
  28. arr[k] = L[i];
  29. i++;
  30. }
  31. else {
  32. arr[k] = R[j];
  33.  
  34. //====================================//
  35. //======= MAIN PORTION OF CODE ======//
  36. //===================================//
  37. // add all line which is cross by current element
  38. *count_crossline += (n1 - i);
  39. j++;
  40. }
  41. k++;
  42. }
  43.  
  44. /* Copy the remaining elements of L[], if there
  45. are any */
  46. while (i < n1) {
  47. arr[k] = L[i];
  48. i++;
  49. k++;
  50. }
  51.  
  52. /* Copy the remaining elements of R[], if there
  53. are any */
  54. while (j < n2) {
  55. arr[k] = R[j];
  56. j++;
  57. k++;
  58. }
  59. }
  60.  
  61. /* l is for left index and r is right index of the
  62. sub-array of arr to be sorted */
  63. void mergeSort(int arr[], int l, int r, int* count_crossline)
  64. {
  65. if (l < r) {
  66.  
  67. // Same as (l+r)/2, but avoids overflow for
  68. // large l and h
  69. int m = l + (r - l) / 2;
  70.  
  71. // Sort first and second halves
  72. mergeSort(arr, l, m, count_crossline);
  73. mergeSort(arr, m + 1, r, count_crossline);
  74.  
  75. merge(arr, l, m, r, count_crossline);
  76. }
  77. }
  78.  
  79. // function return count of cross line in an array
  80. int countCrossLine(int arr[], int n)
  81. {
  82. int count_crossline = 0;
  83. mergeSort(arr, 0, n - 1, &count_crossline);
  84.  
  85. return count_crossline;
  86. }
  87.  
  88. // driver program to test above function
  89. int main()
  90. {
  91. int q;
  92. cin >> q;
  93. int n;
  94. int *arr;
  95. for (int i = 0; i < q; i++)
  96. {
  97. cin >> n;
  98. arr = new int[n];
  99. for (int j = 0; j < n; j++)
  100. {
  101. cin >> arr[j];
  102. }
  103. cout << countCrossLine(arr, n) << endl;
  104. }
  105.  
  106.  
  107. return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement