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.
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
题意:就是给出一串数,当依次在将第一个数变为最后一个数的过程中,要你求它的最小逆序数。
逆序数:在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。逆序数为偶数的排列称为偶排列;逆序数为奇数的排列称为奇排列。如2431中,21,43,41,31是逆序,逆序数是4,为偶排列。
思路:可以用树状数组和线段数做。这里我是用线段树做的。建的是一棵空树,然后每插入一个点之前,统计大于这个数的有多少个,直到所有的数都插入完成,就结果了逆序树的统计。
要得出答案主要是利用了一个结论,如果是0到n的排列,那么如果把第一个数放到最后,对于这个数列,逆序数是减少a[i],而增加n-1-a[i]的.当然,你也可以是统计小于这个数的有多少个,然后再用已经插入树中i个元素减去小于这个数的个数,得出的结果也是在一样的。
代码:
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
int l,r,num;
}str[15000];
int a[5005],sum;
void build(int l,int r,int n)
{
str[n].l=l;
str[n].r=r;
str[n].num=0;
if(l==r)
return;
int temp=(l+r)/2;
build(l,temp,2*n);
build(temp+1,r,2*n+1);
}
int query(int l,int r,int n)
{
if(str[n].l==l&&str[n].r==r)
{
return str[n].num;
}
int temp=(str[n].l+str[n].r)/2;
if(r<=temp)
return query(l,r,2*n);
else if(l>temp)
return query(l,r,2*n+1);
else
{
return query(l,temp,2*n)+query(temp+1,r,2*n+1);
}
}
void mark(int bol,int n)
{
if(str[n].l==str[n].r)
{
if(str[n].l==bol)
str[n].num++;
return;
}
int temp=(str[n].l+str[n].r)/2;
if(bol<=temp)
mark(bol,2*n);
else
mark(bol,2*n+1);
str[n].num=str[2*n].num+str[2*n+1].num;
}
int main()
{
int n;
while(~scanf("%d",&n))
{
build(0,n-1,1);
sum=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
sum=sum+query(a[i],n-1,1);
mark(a[i],1);
}
int minn=9999999;
if(minn>sum)
minn=sum;
for(int i=0;i<n;i++)
{
sum=sum-a[i]+n-1-a[i];
if(sum<minn)
minn=sum;
}
printf("%d\n",minn);
}
}