您的位置:首页 > 其它

HDU 1394 Minimum Inversion Number

2015-08-09 16:44 351 查看

Minimum Inversion Number

[align=left]Problem Description[/align]
The
inversion number of a given number sequence a1, a2, ..., an is the
number of pairs (ai, aj) that satisfy i < j and ai > aj.

For
a given sequence of numbers a1, a2, ..., an, if we move the first m
>= 0 numbers to the end of the seqence, we will obtain another
sequence. There are totally n such sequences as the following:

a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)

You are asked to write a program to find the minimum inversion number out of the above sequences.

[align=left]Input[/align]
The
input consists of a number of test cases. Each case consists of two
lines: the first line contains a positive integer n (n <= 5000); the
next line contains a permutation of the n integers from 0 to n-1.

[align=left]Output[/align]
For each case, output the minimum inversion number on a single line.

[align=left]Sample Input[/align]

10

1 3 6 9 0 8 5 7 4 2

[align=left]Sample Output[/align]

16

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

struct segtree
{
int l,r;
int num;
int mid()
{
return (l+r)>>1;
}
};

segtree tree[5005<<2];
int a[5005<<2];

void PushUp(int rt)
{
tree[rt].num=tree[rt<<1].num+tree[rt<<1|1].num;
}

void build(int l,int r,int rt)
{
tree[rt].l=l;
tree[rt].r=r;
tree[rt].num=0;
if(l==r)return;
int m=tree[rt].mid();
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
}

int query(int l,int r,int rt)
{
if(tree[rt].l==l&&tree[rt].r==r)
return tree[rt].num;
int m=tree[rt].mid();
if(r<=m)
return query(l,r,rt<<1);
else if(l>m)
return query(l,r,rt<<1|1);
else
return query(l,m,rt<<1)+query(m+1,r,rt<<1|1);
}

void update(int pos,int rt)
{
if(tree[rt].l==tree[rt].r)
{
tree[rt].num++;
return;
}
int m=tree[rt].mid();
if(pos<=m)update(pos,rt<<1);
else update(pos,rt<<1|1);
PushUp(rt);
}

int main()
{
int n,i,j;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
build(0,n-1,1);
int sum=0;
for(i=0;i<n;i++)
{
sum+=query(a[i],n-1,1);
update(a[i],1);
}
int ans=999999999;
ans=min(ans,sum);
for(i=0;i<n;i++)
{
sum=sum-a[i]+n-1-a[i];
ans=min(ans,sum);
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: