Given an integer sequence of length n, please count the number of reverse pairs in the sequence.
The definition of the reverse order pair is as follows: For the i-th and j-th elements of the sequence, if i <j and a[i]> a[j] are satisfied, then it is a reverse-order pair; otherwise, it is not.
Input format The
first line contains the integer n, which represents the length of the sequence.
The second line contains n integers, representing the entire sequence.
Output format
Output an integer, indicating the number of pairs in reverse order.
Data range
1≤n≤100000
input example:
6
2 3 4 5 6 1
Sample output:
5
The C++ code is as follows:
#include<iostream>
using namespace std;
#define N 100050
int sum = 0;
int tmp[N];
void merge_sort(int q[],int l ,int r)
{
if(l>=r) return;
int mid= l + r >> 1;
merge_sort(q,l,mid);
merge_sort(q,mid+1,r);
int k= 0,i=l,j=mid+1;
while(i<=mid&&j<=r)
if(q[i]<=q[j]){
tmp[k++] = q[i++];
}
else{
sum += mid - i + 1;
tmp[k++] = q[j++];
}
while(i<=mid) tmp[k++] = q[i++];
while(j<=r) tmp[k++] = q[j++];
for(i=l,j=0;i<=r;i++,j++)
q[i]= tmp[j];
}
int main()
{
int q[N];
int n;
cin >> n;
for(int i = 0 ; i < n ; i ++) cin >> q[i];
merge_sort(q,0,n-1);
cout << sum;
return 0;
}