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
Output example:
5
Merge sorting is a powerful tool for finding reverse order pairs, and the monotonicity brought by sorting is used to find reverse order pairs at a time.
AC code:
#include<stdio.h>
int n;
int a[100010];
int temp[100010];
long long ans;
void merge_sort(int l,int r)
{
if(l==r) return;
int mid=l+((r-l)>>1);
merge_sort(l,mid);
merge_sort(mid+1,r);
for(int i=l;i<=r;++i) temp[i]=a[i];
int i1=l,i2=mid+1;
for(int i=l;i<=r;++i)
{
if(i1>mid) a[i]=temp[i2++];
else if(i2>r) a[i]=temp[i1++];
else if(temp[i1]<=temp[i2]) a[i]=temp[i1++];
//左半边i1之后的元素都比i2大
else if(temp[i1]>temp[i2]){
ans+=mid-i1+1;a[i]=temp[i2++];}
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i) scanf("%d",&a[i]);
merge_sort(1,n);
printf("%lld",ans);
return 0;
}