#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 5e5 + 10;
int a[N],t[N];
inline int read() {
static char c= getchar(); int x=0,f=1;
for(;c>'9'||c<'0';c=getchar()) if(c=='-') f=-1;
for(;c<='9'&&c>='0';c=getchar()) x=(x<<3)+(x<<1)+c-48;
return x*f;
}
ll Merge(int a[],int l,int r)
{
if(l >= r)return 0;
int mid = l + r >> 1;
int i = l,j = mid + 1,k = 0;
ll res = Merge(a,l,mid) + Merge(a,mid+1,r);;
while(i <= mid && j <= r)
{
if(a[i] <= a[j])t[k++] = a[i++];
else
{
res += mid + 1 - i;
t[k++] = a[j++];
}
}
while(i <= mid)t[k++] = a[i++];
while(j <= r)t[k++] = a[j++];
for(int i = l,j = 0;i <= r;i++,j++)a[i] = t[j];
return res;
}
int main()
{
int n;
n = read();
for(int i = 0;i < n;i++)
{
a[i] = read();
}
cout << Merge(a,0,n-1);
return 0;
}
求逆序对个数(归并排序)
最新推荐文章于 2024-06-17 14:24:00 发布