Link:http://acm.hdu.edu.cn/showproblem.php?pid=1394
10 1 3 6 9 0 8 5 7 4 2
16
#include
#include
#include
#include
#include
#include
#define MAXN 5010
using namespace std;
int c[MAXN],n,num[MAXN];
int lowbit(int p)
{
return p&(-p);
}
void up(int p,int v)
{
while(p<=n)
{
c[p]+=v;
p+=lowbit(p);
}
}
int sum(int p)
{
int s=0;
while(p>0)
{
s+=c[p];
p-=lowbit(p);
}
return s;
}
int main()
{
int t,ans;
while(~scanf("%d",&n))
{
ans=0;
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++)
{
scanf("%d",&num[i]);
up(num[i]+1,1);//注意加1!!!并且必须先更新再求和
ans+=i-sum(num[i]+1);
}
int tmp=ans;
for(int i=1;i<=n-1;i++)
{
tmp=tmp-num[i]+(n-1-num[i]);
ans=min(tmp,ans);
}
printf("%d\n",ans);
}
return 0;
}
#include
#include
#include
#include
#include
#include
#define MAXN 5001
using namespace std;
struct node{
int l,r,sum;
}tree[MAXN*4];
int ans,n;
int num[MAXN];
void build(int rt,int s,int e)
{
tree[rt].l=s;
tree[rt].r=e;
if(s==e)
{
tree[rt].sum=0;
return;
}
int mid=(s+e)/2;
build(rt*2,s,mid);
build(rt*2+1,mid+1,e);
tree[rt].sum=tree[rt*2].sum+tree[rt*2+1].sum;
}
void update(int rt,int pos,int val)
{
if(tree[rt].l==pos&&tree[rt].r==pos)
{
tree[rt].sum+=val;
return;
}
int mid=(tree[rt].l+tree[rt].r)/2;
if(pos<=mid)
{
update(rt*2,pos,val);
}
else
{
update(rt*2+1,pos,val);
}
tree[rt].sum=tree[rt*2].sum+tree[rt*2+1].sum;
}
void query(int rt,int ql,int qr)
{
int mid=(tree[rt].l+tree[rt].r)/2;
if(tree[rt].l==ql&&tree[rt].r==qr)
{
ans+=tree[rt].sum;
}
else if(qr<=mid)
{
query(rt*2,ql,qr);
}
else if(ql>mid)
{
query(rt*2+1,ql,qr);
}
else
{
query(rt*2,ql,mid);
query(rt*2+1,mid+1,qr);
}
}
int main()
{
int i,ans1;
while(~scanf("%d",&n))
{
build(1,0,n-1);
ans1=0;
for(i=0;i