逆序对
题目描述
解题思路
将a数组离散化
Code
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n, tot;
int a[1000100], p[1001000], c[1000100];
void lsh()
{
for(int i=1; i<=n; i++)
p[i]=a[i];
sort(p+1, p+1+n); tot=unique(p+1, p+1+n)-1-p;
for(int i=1; i<=n; i++)
a[i]=lower_bound(p+1, p+1+tot, a[i])-p;
}
long long lowbit(long long x)
{ return x&-x; }
void add(long long x, long long y)
{
for(; x<=n; x+=lowbit(x))
c[x]+=y;
}
long long sum(long long x)
{
long long ans=0;
for(; x; x-=lowbit(x))
ans+=c[x];
return ans;
}
int main()
{
scanf("%d", &n);
for(int i=1; i<=n; i++)
scanf("%d", &a[i]);
lsh();
long long ans=0;
for(int i=1; i<=n; i++)
{
add(a[i], 1);
ans+=sum(tot)-sum(a[i]);
}
printf("%lld", ans);
return 0;
}