您的位置:首页 > 编程语言 > C语言/C++

HDU 1394 Minimum Inversion Number

2016-11-15 11:05 465 查看
[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

 

[align=left]Author[/align]
CHEN, Gaoli
 

[align=left]Source[/align]
ZOJ Monthly, January 2003

 

[align=left]Recommend[/align]
Ignatius.L   |   We have carefully selected several similar problems for you:  1698 1540 1542 1255 2795 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

线段树求逆序对~

这种做法只适用于题目中这样的从0~n-1的数列,如果中间有空下的数,就要多次计算了~

维护一棵线段树,从0~n-1分别记录该数是否出现过,然后每次输入的时候计算当前有哪些大于它的数已输入,就计算出了初始情况下的num。

然后,对于每个在开头的数,把它移到末尾,num+所有大于它的数-所有小于它的数,递推即可;这个式子可以化简为:sum=sum-2*num[i]+n-1,因为数是连续不断的~

#include<cstdio>
#include<iostream>
using namespace std;

int n,a[5000<<2],num[5000],ans,sum;

void build(int l,int r,int u)
{
a[u]=0;
if(l==r) return;
int mid=(l+r)>>1;
build(l,mid,u<<1);build(mid+1,r,u<<1|1);
}

void add(int l,int r,int u,int v)
{
if(l==r)
{
a[u]=1;return;
}
int mid=(l+r)>>1;
if(v<=mid) add(l,mid,u<<1,v);
else add(mid+1,r,u<<1|1,v);
a[u]=a[u<<1]+a[u<<1|1];
}

int query(int l,int r,int u,int v,int k)
{
if(l==v && r==k) return a[u];
int mid=(l+r)>>1;
if(v>mid) return query(mid+1,r,u<<1|1,v,k);
if(k<=mid) return query(l,mid,u<<1,v,k);
return query(l,mid,u<<1,v,mid)+query(mid+1,r,u<<1|1,mid+1,k);
}

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