#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#define maxn 10000
using namespace std;
struct node
{
int l,r,val;
}tree[maxn*3];
void build(int left,int right,int root)
{
tree[root].l=left;
tree[root].r=right;
tree[root].val=0;//忘了这里的初始化
if(left==right) {tree[root].val=0;return ;}
int mid=(left+right)/2;
build(left,mid,root*2);
build(mid+1,right,root*2+1);
return ;
}
void update(int pos,int root)
{
int left=tree[root].l;
int right=tree[root].r;
if(left==right)
{
tree[root].val++;
}
else{
int mid=(left+right)/2;
if(pos<=mid) update(pos,root*2);
else update(pos,root*2+1);
tree[root].val=tree[root*2].val+tree[root*2+1].val;}
}
int query(int s,int t,int root)///left和right在s,t范围内
{
int left=tree[root].l;
int right=tree[root].r;
int mid=(left+right)/2;
if(s<=left && right<=t) return tree[root].val;
else{
int sum1=0;int sum2=0;
if(s<=mid) sum1=query(s,t,root*2);
if(t>mid) sum2=query(s,t,root*2+1);
return sum1+sum2;}
}
int a[maxn];
int mi;
int main()
{
// freopen("in.txt","r",stdin);
int n;
while(scanf("%d",&n)!=EOF)
{
build(0,n-1,1);
int sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(a[i]!=n-1)
{
int temp=query(a[i]+1,n-1,1);
sum+=temp;}
update(a[i],1);
}
int mi=sum;
for(int i=0;i<n;i++)
{
sum-=a[i];
sum+=(n-1-a[i]);
mi=min(sum,mi);
}
printf("%d\n",mi);
}
}
HDU 1394 线段树
最新推荐文章于 2020-07-07 19:40:15 发布