AcWing 107. 超快速排序(树状数组+离散化)
原题链接
简单
作者:
記得
,
2021-03-17 14:30:35
,
所有人可见
,
阅读 597
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cstring>
using namespace std;
typedef long long LL;
const int N=5e5+10;
int tfind(int x);
LL lowbit(LL x);
LL get_sum(int x);
void add(int a, int b);
int n;
LL a[N];
LL tr[N];
vector<LL> alls;
signed main()
{
while(scanf("%d", &n), n)
{
alls.clear();
for(int i=1;i<=n;i++)
{
scanf("%lld", &a[i]);
alls.push_back(a[i]);
}
sort(alls.begin(), alls.end());
alls.erase(unique(alls.begin(), alls.end()), alls.end());
LL res=0;
memset(tr, 0, sizeof tr);
for(int i=1;i<=n;i++)
{
int site=tfind(a[i]);
res+=get_sum(alls.size())-get_sum(site);
add(site, 1);
}
printf("%lld\n", res);
}
}
LL get_sum(int x)
{
LL sum=0;
for(int i=x;i;i-=lowbit(i)) sum+=tr[i];
return sum;
}
void add(int a, int b)
{
for(int i=a;i<=alls.size();i+=lowbit(i)) tr[i]+=b;
}
LL lowbit(LL x)
{
return x&-x;
}
int tfind(int x)
{
int l=0, r=alls.size()-1;
while(l<r)
{
int mid=l+r>>1;
alls[mid]>=x?r=mid:l=mid+1;
}
return l+1;
/*return lower_bound(alls.begin(), alls.end(), x)-alls.begin()+1;*/
}