Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19603 Accepted Submission(s): 11774
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
题意:
给长度是n的序列,每次将第一个数放到最后,直到数列再次变成最初的数列,求过程中最小的逆序数。
代码:
//求出最初的逆序数sum,每次操作将a[i]放到最后时更新sum: //加上a[i]向后的顺序数(比他大的数的个数),减去a[i]向后的 //逆序数(比她小的数的个数),加上a[i]向前的(他前面的数放到后面了) //顺序数减去a[i]向前的逆序数。所以两遍树状数组就解决了。 #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn=5000; int n,c[maxn*4+10],a[maxn+10],sh[maxn+10],ni[maxn+10]; int lowbit(int x) {return x&(-x);} void add(int id) { while(id<=5000){ c[id]++; id+=lowbit(id); } } int query(int id) { int s=0; while(id>0){ s+=c[id]; id-=lowbit(id); } return s; } int main() { int n; while(scanf("%d",&n)==1){ int sum=0; memset(c,0,sizeof(c)); memset(sh,0,sizeof(sh)); memset(ni,0,sizeof(ni)); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); a[i]++; add(a[i]); sh[i]=query(a[i]-1); ni[i]=i-sh[i]-1; sum+=ni[i]; } //for(int i=1;i<=n;i++) cout<<sh[i]<<" "<<ni[i]<<endl; memset(c,0,sizeof(c)); for(int i=n;i>=1;i--){ add(a[i]); int tmp=query(a[i]-1); sh[i]+=tmp; ni[i]+=n-i+1-tmp-1; } //for(int i=1;i<=n;i++) cout<<sh[i]<<" "<<ni[i]<<endl; int ans=sum; for(int i=1;i<=n;i++){ sum=sum+ni[i]-sh[i]; ans=min(ans,sum); } printf("%d ",ans); } return 0; }