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
給你一串数字(0~n-1,顺序被打乱),你可以将前a(0<=a<=n)个数字移到后面,这a个数字顺序不可被打乱,剩下的n-a个数字顺序不可被打乱,输出所有情况中含逆序对最少的那个串的逆序对数。
关于逆序对问题:要用 树状数组 或 线段树求解.
以下用的是树状数组。
为什么要用树状数组?因为树状数组快啊
方法都是暴力,不用树状数组,需要用两重循环。对每个数,求小于它的数在它前面出现了几个,O(n^2)的复杂度
树状数组将复杂度降到O(nlogn) , 树状数组优点:求和快
好,求出原串的逆序对,但还不满足要求,因为可以重构串,(类似环排列,重新选起点)
暴力?重构串,求逆序对,O(n^2)
其他情况是怎么来的,是原串将最前面那个数移到最后得到的,之后将所得到串的最前面那个数移到最后,一直重复n-1,第n次就变成了开始那个串。
若能求出最前面那个数在这串有多少个小于它的数就好了,开始那个串的逆序对数已知,该逆序对数记为为A,最前面那个数在这串有多少个小于它的数为x,将最前面那个数移到最后,逆序对数为,A-x+(n-x-1)
想一下原串中的数字,若3在某次串在最前面,是不是我们已经知道在它后面有多少个数小于它,有多少个数大于它。(数只可能是0~n-1,并且不会重复)
所以用现在的串的最前面那个数。(开始时想在C数组中找线索,唉,思维题)
#include <cstdio>
#include <algorithm>
#define Lowbit(x) (x&-x)
#define Lim 5000 + 10
#define INF 0x3f3f3f3f
using namespace std;
void Update(int *C,int p,int v)
{
for(int i=p; i<=Lim; i+=Lowbit(i))
C[i]+=v;
}
int Sum(int *C,int p)
{
int ans=0;
for(int i=p; i>0; i-=Lowbit(i))
ans+=C[i];
return ans;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i,t=0,ans;
int C[Lim]= {0};
int Rop[Lim]= {0};
int sam[Lim]= {0};
for(i=1; i<=n; i++)
{
scanf("%d",&sam[i]);
sam[i]++;
Update(C,sam[i],1);
Rop[sam[i]]=i-Sum(C,sam[i]);
t+=Rop[sam[i]];
}
ans=t;
for(i=1; i<n; i++)
{
t+=n-sam[i]-(sam[i]-1);
ans=min(t,ans);
}
printf("%d\n",ans);
}
return 0;
}