Problem Description
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.
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.
Input
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.
Output
For each case, output the minimum inversion number on a single line.
Sample Input
10 1 3 6 9 0 8 5 7 4 2
Sample Output
16
Author
CHEN, Gaoli
Source
Recommend
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;
}