Problem DescriptionThe Inversion number of a given number sequence A1, A2, ..., the number of pairs (AI, aj) that SA Tisfy 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'll Obtain another sequence. There is 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 is asked to write a program to find the minimum inversion number out of the above sequences.
Inputthe input consists of a number of test cases. Each case consists of the 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.
Outputfor each case, output the minimum inversion number to a single line.
Sample Input101 3 6 9 0 8 5 7 4 2
Sample Output16 Minimum value for reverse order number
1#include <iostream>2#include <cstdio>3#include <algorithm>4 using namespacestd;5 Const intmaxn=5010;6 intsum[maxn<<2];7 voidPUSH_UP (intRT)8 {9sum[rt]=sum[rt<<1]+sum[rt<<1|1];Ten } One voidBuildintRtintFirstintend) A { -sum[rt]=0; - if(first==end) the return ; - intMid= (first+end) >>1; -Build (rt<<1, first,mid); -Build (rt<<1|1, mid+1, end); + } - intQuary (intRtintFirstintEndintLeftintRight ) + { A if(Left<=first && right>=end) at returnSum[rt]; - intMid= (first+end) >>1; - intans=0; - if(left<=mid) -Ans+=quary (rt<<1, first,mid,left,right); - if(right>mid) inAns+=quary (rt<<1|1, mid+1, end,left,right); - returnans; to } + voidUpdateintRtintFirstintEndinta) - { the if(first==end) * { $sum[rt]++;Panax Notoginseng return ; - } the intMid= (first+end) >>1; + if(a<=mid) AUpdate (rt<<1, first,mid,a); the Else +Update (rt<<1|1, mid+1, end,a); - push_up (RT); $ } $ intA[MAXN]; - intMain () - { the intN; - while(cin>>N)Wuyi { theBuild1,0, N-1); - intsum=0; Wu for(intI=0; i<n;i++) - { AboutCin>>A[i]; $Sum+=quary (1,0, N-1, a[i],n-1); -Update1,0, N-1, A[i]); - } - intans=sum; A for(intI=0; i<n;i++) + { thesum+=n-a[i]-a[i]-1; -ans=min (ans,sum); $ } thecout<<ans<<Endl; the } the return 0; the}
View Code
HDU 1394 Minimum Inversion number segment tree