Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 10117 Accepted Submission(s): 6203
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
解决方案:hdu上正确率60+%的题目还要看题解.......,看来线段树没学到家啊,好吧!其实这道题也可以暴力。本题是求逆序,可先求原始装态的逆序个数,然后对于每次移动,逆序个数会变成cnt+=N-a[i]-a[i]-1。即每次把第一个数移到最后,会增加N-a[i]-1,同时会减少a[i]对逆序。求初识逆序可用线段树。
code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define MMAX 5005
using namespace std;
int sum[4*MMAX],N,_min,_ant;
int _sum[MMAX],y[MMAX],a[MMAX];
void build(int rt,int L,int R)
{
if(L==R)
{
sum[rt]=0;
}
else
{
int M=(L+R)/2;
build(rt*2,L,M);
build(rt*2+1,M+1,R);
sum[rt]=0;
}
}
void query(int rt,int L,int R,int st,int en)
{
if(st<=L&&en>=R)
{
_ant+=sum[rt];
}
else
{
int M=(L+R)/2;
//cout<<rt<<endl;
//getchar();
if(st<=M) query(rt*2,L,M,st,en);
if(en>M) query(rt*2+1,M+1,R,st,en);
}
}
void update(int rt,int L,int R,int C)
{
if(L==R)
{
sum[rt]++;
}
else
{
int M=(L+R)/2;
if(C<=M)update(rt*2,L,M,C);
else update(rt*2+1,M+1,R,C);
sum[rt]=sum[rt*2]+sum[rt*2+1];
}
}
int main()
{
while(~scanf("%d",&N))
{
build(1,1,N);
_min=0;
for(int i=1;i<=N;i++)
scanf("%d",&a[i]);
for(int i=1; i<=N; i++)
{
_ant=0;
query(1,1,N,a[i]+1,N);
update(1,1,N,a[i]+1);
_min+=_ant;
// cout<<_ant<<endl;
}
int min_=_min;
for(int i=1; i<=N; i++)
{
_min+=N-2*a[i]-1;
min_=min(_min,min_);
}
printf("%d\n",min_);
}
return 0;
}