-
Notifications
You must be signed in to change notification settings - Fork 0
/
INVCNT.cpp
60 lines (60 loc) · 1003 Bytes
/
INVCNT.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//merge sort
#include<bits/stdc++.h>
typedef long long int ll;
using namespace std;
ll merge(vector<ll> &a,vector<ll> &aux,ll lo,ll mid,ll hi)
{
ll count=0;
ll i=lo,j=mid+1;
for(ll k=lo;k<=hi;k++)
aux[k]=a[k];
for(ll k=lo;k<=hi;k++)
{
if(i>mid)
a[k]=aux[j++];
else if(j>hi)
a[k]=aux[i++];
else if(aux[i]<=aux[j])
a[k]=aux[i++];
else
{
a[k]=aux[j++];
count+=(mid-i+1);
}
}
return count;
}
ll msort(vector<ll> &a,vector<ll> &aux,ll lo,ll hi)
{
ll inv_count=0;
if(lo<hi)
{
ll mid=(hi+lo)/2;
inv_count=msort(a,aux,lo,mid);
inv_count+=msort(a,aux,mid+1,hi);
inv_count+=merge(a,aux,lo,mid,hi);
}
return inv_count;
}
ll merge_sort(vector<ll> &a)
{
vector<ll> aux(a.size());
return msort(a,aux,0,a.size()-1);
}
int main()
{
ll t,n;
scanf("%lld",&t);
while(t--)
{
scanf("%lld",&n);
vector<ll> v(n);
for(ll i=0;i<n;i++)
{
scanf("%lld",&v[i]);
}
ll ans=merge_sort(v);
printf("%lld\n",ans);
}
return 0;
}