Saleh127

SPOJ INVCNT / Mergesort Technique

Feb 17th, 2022
881
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. /***
  2.  created: 2022-02-17-21.40.43
  3. ***/
  4.  
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. #define ll long long
  8. #define test int tt; cin>>tt; for(int cs=1;cs<=tt;cs++)
  9. #define get_lost_idiot return 0
  10. #define nl '\n'
  11.  
  12. ll x[200008],y[200005],a[200005];
  13. ll ans=0;
  14. void merge_array(ll l,ll mid,ll mid1,ll h)
  15. {
  16.  
  17.     for(ll i=l; i<=mid; i++) x[i]=a[i];
  18.     for(ll i=mid1; i<=h; i++) y[i]=a[i];
  19.  
  20.     ll ls=l,rs=mid1;
  21.  
  22.     for(ll i=l; i<=h; i++)
  23.     {
  24.         if(ls>mid)
  25.         {
  26.             a[i]=y[rs];
  27.             rs++;
  28.         }
  29.         else if(rs>h)
  30.         {
  31.             a[i]=x[ls];
  32.             ls++;
  33.         }
  34.         else
  35.         {
  36.             if(x[ls]<y[rs])
  37.             {
  38.                 a[i]=x[ls];
  39.                 ls++;
  40.             }
  41.             else
  42.             {
  43.                 a[i]=y[rs];
  44.                 rs++;
  45.                 ans+=(mid-ls+1);
  46.             }
  47.         }
  48.     }
  49.  
  50. }
  51.  
  52. void merge_sort(ll l,ll h)
  53. {
  54.     if(l<h)
  55.     {
  56.         ll mid=(l+h)/2;
  57.  
  58.         merge_sort(l,mid);
  59.         merge_sort(mid+1,h);
  60.  
  61.         merge_array(l,mid,mid+1,h);
  62.     }
  63.     return ;
  64. }
  65.  
  66. int main()
  67. {
  68.     ios_base::sync_with_stdio(0);
  69.     cin.tie(0);
  70.     cout.tie(0);
  71.  
  72.     test
  73.     {
  74.         ll n,m,i,j,k,l;
  75.  
  76.         cin>>n;
  77.  
  78.       //  ll a[n+4];
  79.  
  80.         for(i=1; i<=n; i++)
  81.         {
  82.             cin>>a[i];
  83.         }
  84.  
  85.         merge_sort(1,n);
  86.  
  87.         cout<<ans<<nl;
  88.  
  89.         ans=0;
  90.     }
  91.  
  92.     get_lost_idiot;
  93. }
  94.  
  95.  
Advertisement
Add Comment
Please, Sign In to add comment