#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int helpInverse(int A[],int start,int mid,int end){
int len=end-start+1;
vector<int>temp(len+1);
int i=start,j=mid+1;
int cnt=0,x=0;
while(i<=mid && j<=end){
if(A[i]<=A[j]){
temp[x++]=A[i++];
}else{
temp[x++]=A[j++];
cnt+=(mid-i)+1;
}
}
while(i<=mid){
temp[x++]=A[i++];
}
while(j<=end){
temp[x++]=A[j++];
}
int t=start;
for(int i=0;i<x;++i){
A[t++]=temp[i];
}
return cnt;
}
int countInversions(int A[],int start,int end){
int x=0;
if(start<end){
int mid=(start+end)/2;
x+=countInversions(A,start,mid);
x+=countInversions(A,mid+1,end);
x+=helpInverse(A,start,mid,end);
}
return x;
}
int main() {
// your code
int arr[5]={1, 20, 6, 4, 5};
cout<<"ans: "<<countInversions(arr,0,4)<<endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBoZWxwSW52ZXJzZShpbnQgQVtdLGludCBzdGFydCxpbnQgbWlkLGludCBlbmQpewoKCWludCBsZW49ZW5kLXN0YXJ0KzE7CgoJdmVjdG9yPGludD50ZW1wKGxlbisxKTsKCWludCBpPXN0YXJ0LGo9bWlkKzE7CglpbnQgY250PTAseD0wOwoJd2hpbGUoaTw9bWlkICYmIGo8PWVuZCl7CgoJCWlmKEFbaV08PUFbal0pewoJCQkJdGVtcFt4KytdPUFbaSsrXTsKCQl9ZWxzZXsKCQkJCXRlbXBbeCsrXT1BW2orK107CgkJCQljbnQrPShtaWQtaSkrMTsKCQl9CgoJfQoKCXdoaWxlKGk8PW1pZCl7CgkJdGVtcFt4KytdPUFbaSsrXTsKCX0KCgl3aGlsZShqPD1lbmQpewoJCXRlbXBbeCsrXT1BW2orK107Cgl9CgoJaW50IHQ9c3RhcnQ7Cglmb3IoaW50IGk9MDtpPHg7KytpKXsKCQlBW3QrK109dGVtcFtpXTs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