#include<cstdio>
#include<cstring>
#include<cstdlib>
const int maxn=50005;
int a[maxn],c[maxn],n;
int lowbit(int x)
{
return x&(-x);
}
int find(int x)
{
if(x>0)
{
return c[x]+find(x-lowbit(x));
}
return 0;
}
int Query(int x,int y)
{
return find(y)-find(x-1);
}
void Update(int x)
{
if(x<=n)
{
c[x]+=1;
Update(x+lowbit(x));
}
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
a[i]++;
}
memset(c,0,sizeof(c));
int sum=0;
for(int i=1;i<=n;i++)
{
sum+=Query(a[i]+1,n);
Update(a[i]);
}
int ans=sum;
for(int i=1;i<=n;i++)
{
sum+=(n-a[i])-(a[i]-1);
ans=ans<sum?ans:sum;
}
printf("%d\n",ans);
}
}
hdu1394树状数组
最新推荐文章于 2019-09-20 21:25:59 发布