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
看了别人的代码做出来了。。 这题先用线段树的方法把读入数据的逆序值求出来,依次插入点,每插入一个点k就看[k+1,n]中前面插入的点有几个,即为该点的逆序值,然后再更新从根线段到[k,k]这些线段的值。点都插入完毕后,再一次把最前面的点移到最后面,此时总逆序数会减少a[i]-1,增加n-a[i],然后求出最小的逆序数就行了。
#include<stdio.h> #include<string.h> #define maxn 5005 int a[maxn]; struct node { int l,r,sum; }b[4*maxn]; void build(int l,int r,int i) { int mid; b[i].l=l; b[i].r=r; b[i].sum=0; if(l==r) return; mid=(l+r)/2; build(l,mid,i*2); build(mid+1,r,i*2+1); } int inverse(int l,int r,int i) { int mid; if(b[i].l==l && b[i].r==r) { return b[i].sum; } mid=(b[i].l+b[i].r)/2; if(l>mid) return inverse(l,r,i*2+1); else if(r<=mid) return inverse(l,r,i*2); else if(r>mid && l<=mid) return inverse(l,mid,i*2)+inverse(mid+1,r,i*2+1); } void change(int i,int id) { int mid; if(b[i].l==id && b[i].r==id) { b[i].sum=1; return; } mid=(b[i].l+b[i].r)/2; if(id<=mid) change(i*2,id); else if(id>mid) change(i*2+1,id); b[i].sum=b[i*2].sum+b[i*2+1].sum; } int main() { int n,m,i,j,ans,min; while(scanf("%d",&n)!=EOF) { build(1,n,1); ans=0; for(i=1;i<=n;i++) { scanf("%d",&a[i]); ans=ans+inverse(a[i]+1,n,1); change(1,a[i]); } min=ans; for(i=1;i<=n;i++) { ans=ans+n-2*a[i]-1; if(ans<min) min=ans; } printf("%d ",min); } }