fork(1) download
  1. #include <iostream>
  2. typedef long long int typex;
  3. using namespace std;
  4. long long int count,arr[200001];
  5. void merge(typex p,typex q,typex r)
  6. {
  7.  
  8. //first array has indices from p to q
  9. //second array has indices from q to p
  10. typex i,li,ri,n1,n2;
  11. n1=q-p+1;
  12. n2=r-q;
  13. typex *lt= new typex [n1];
  14. typex *rt= new typex [n2];//[q-(r+1)+1]
  15. for(i=0;i<n1;i++)
  16. {
  17. lt[i]=arr[p+i];
  18. }
  19. for(i=0;i<n2;i++)
  20. {
  21. rt[i]=arr[q+1+i];
  22. }
  23.  
  24. //left and right array is ready which is all ready sorted
  25. //now we will merge
  26. li=ri=0;i=p;
  27. while(li<n1&&ri<n2)
  28. {
  29. if(lt[li]>rt[ri])
  30. {
  31. arr[i++]=rt[ri++];
  32. count=count+n1-li;
  33. }
  34. else //right hand side elemnt is greater that is inversion pair
  35. {
  36. arr[i++]=lt[li++];
  37. }
  38. }
  39. //inversion pairs have been counted till this stage, do not count again;
  40. while(li<n1)
  41. {
  42. arr[i++]=lt[li++];
  43.  
  44. }
  45.  
  46. while(ri<n2)
  47. {
  48. arr[i++]=rt[ri++];
  49. }
  50.  
  51. }
  52. void mergesort(typex p,typex r)
  53. {
  54. if(p<r)
  55. {
  56. typex q=(p+r)/2;
  57. mergesort(p,q);
  58. mergesort(q+1,r);
  59. merge(p,q,r);
  60. }
  61.  
  62.  
  63. }
  64. int main()
  65. {
  66. int t;
  67. long long int n,i;
  68. cin>>t;
  69. while(t--)
  70. {
  71. cin>>n;
  72. for(i=0;i<n;i++)
  73. {
  74. cin>>arr[i];
  75. }
  76. count=0;
  77. mergesort(0,n-1);
  78. cout<<"\n"<<count;
  79. }
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0s 4792KB
stdin
2

3
3
1
2

5
2
3
8
6
1
stdout
2
5