hdu-1394Minimum Inversion Number
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
输入一个整数n,一个数列x[n],数列是由0~n-1这n个数组成的。该数列可以有多中变换。变换的规则是:每次变换只能移一次,只能将第一个数字移动到数列最后。求出每种变换之后的逆序数(包括原数列),输出这些逆序数中的最小值。
解题思路:
根据逆序数的性质,可以先求出原数列的逆序数,再递推出变换之后的逆序数。
例如:原数列的逆序数为sum,根据逆序数的性质,变换一次之后的逆序数就为:sum+(n-2*x[i]-1)
推导过程: 假设现在的数列为 a1,a2, a3,......an。此时的逆序数为sum。
如果在a1后面的数中有,比a1大的有max个,比a1小的有min个,易知,max=n-a1-1,min=n-1-max。
当进行一次变换之后,数列变成了a2,a3,......an,a1。那么之前在a1后面的数,全部到了a1的前面,所以此时的逆序数为sum+max-min。即sum+n-2*a1-1。推广到一般形式就是:sum+n-2*x[i]-1 (sum是变换前一次的逆序数)。
解题方法:
先用线段树求出原数列的逆序数,在用公式推导出每种形式的逆序数,最后求出最小值。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
#define maxn 5555
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int sum[maxn<<2];
void push(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
sum[rt]=0;
if(l==r)
return ;
int m=(r+l)>>1;
build(lson);
build(rson);
}
void updata(int p,int l,int r,int rt)
{
if(l==r)
{
sum[rt]++;
return ;
}
int m=(r+l)>>1;
if(p<=m)
updata(p,lson);
else
updata(p,rson);
push(rt);
}
int query(int L,int R,int l,int r,int rt)
{
if(L<=l&&r<=R)
{
return sum[rt];
}
int m=(r+l)>>1;
int ans=0;
if(L<=m)
ans+=query(L,R,lson);
if(R>m)
ans+=query(L,R,rson);
return ans;
}
int x[maxn<<1];
int main()
{
int n,sum;
while(~scanf("%d",&n))
{
build(0,n-1,1);
sum=0;
for(int i=0;i<n;i++)//求出原数列的逆序数sum
{
scanf("%d",&x[i]);
sum+=query(x[i],n-1,0,n-1,1);
updata(x[i],0,n-1,1);
}
int ans=sum;
for(int i=0;i<n-1;i++)//推出每种形式的逆序数,再进行比较,将较小的逆序数存在ans中
{
sum+=n-2*x[i]-1;
ans=min(ans,sum);
}
printf("%d\n",ans);
}
return 0;
}