AcWing 788. 逆序对的数量(树状数组+离散化)
原题链接
简单
作者:
記得
,
2021-04-01 16:00:59
,
所有人可见
,
阅读 341
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long LL;
const int N=1e5+10;
int lowbit(int x);
void add(int a, int b);
int get_sum(int x);
int tfind(int l, int r, int x);
int n;
int a[N];
LL tr[N];
vector<int> alls;
signed main()
{
cin>>n;
alls.push_back(0);
for(int i=1;i<=n;i++)
{
scanf("%d", &a[i]);
alls.push_back(a[i]);
}
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());
LL ans=0;
for(int i=1;i<=n;i++)
{
int x=tfind(0, alls.size()-1, a[i]);
ans+=get_sum(alls.size()-1)-get_sum(x);
add(x, 1);
}
cout<<ans<<endl;
}
int tfind(int l, int r, int x)
{
while(l<r)
{
int mid=l+r>>1;
alls[mid]>=x?r=mid:l=mid+1;
}
return l;
}
void add(int a, int b)
{
for(int i=a;i<=alls.size()-1;i+=lowbit(i)) tr[i]+=b;
}
int get_sum(int x)
{
LL sum=0;
for(int i=x;i;i-=lowbit(i)) sum+=tr[i];
return sum;
}
int lowbit(int x)
{
return x&-x;
}