#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
int a[510000],d[510000];
int n;
int lowbit(int x)
{
return x&-x;
}
int c[510000];
void change(int x,int k)
{
while(x<=n)
{
c[x]+=k;
x+=lowbit(x);
}
}
int getsum(int x)
{
LL sum=0;
while(x>0)
{
sum+=c[x];
x-=lowbit(x);
}
return sum;
}
int find(int x)
{
int l=1,r=n;
while(l<=r)
{
int mid=(l+r)/2;
if(a[mid]==x) return mid;
if(a[mid]>x) r=mid-1;
if(a[mid]<x) l=mid+1;
}
}
int cmp(const void*xx,const void*yy)
{
int n1=*(int *)xx;
int n2=*(int *)yy;
if(n1>n2) return 1;
if(n1<n2) return -1;
return 0;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
if(n==0) break;
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
d[i]=a[i];
}
qsort(a+1,n,sizeof(int ),cmp);
LL cnt=0;
for(int i=n;i>=1;i--)
{
int t=find(d[i]);
change(t,1);
cnt+=getsum(t-1);
}
printf("%lld\n",cnt);
}
return 0;
}
树状数组求逆序对数【poj2299】Ultra-QuickSort
最新推荐文章于 2020-02-15 23:34:00 发布