AcWing 788. The number of reverse
Title Description
Given a length n of the integer sequence number, please number of reverse calculation of the number of columns.
Reverse pairs defined as follows: for i-th and j-th element of the column number, if satisfied i <j and a [i]> a [j], which is the reverse of a; otherwise not.
Input Format
The first row contains an integer n, denotes the length of the sequence.
The second line contains n integer representing the entire number of columns.
data range
1≤n≤100000
SAMPLE INPUT
6
2 3 4 5 6 1
Sample Output
5
Topic ideas
Using merge sort algorithm, ideas and merge sort is the same
#include<iostream>
using namespace std;
const int N = 1e5+10;
int q[N],tmp[N];
long long int merge_sort(int q[],int l,int r)
{
if(l>=r) return 0;
int mid = l+r>>1;
long long int res = 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 tmp[k++] = q[j++],res+=mid-i+1;//如果左半边的元素大于右边该数,左边元素后面的每个数也大于它,一共有mid-i+1个。
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];
return res;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%d",&q[i]);
printf("%ld",merge_sort(q,0,n-1));
return 0;
}