Minimum Inversion numberTime
limit:1000MS
Memory Limit:32768KB
64bit IO Format:%i64d &%i64 U SubmitStatusPracticeHDU 1394
Description
The inversion number of a given number sequence A1, A2, ..., 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'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.
Input
The 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.
Output
For each case, output the minimum inversion number in a single line.
Sample Input
101 3 6 9 0 8 5 7 4 2
Sample Output
16
1#include <stdio.h>2#include <string.h>3#include <algorithm>4 using namespacestd;5 6 intn,c[5050];7 8 intLowbit (intx)9 {Ten returnx& (-x); One } A - voidAddintIintval) - { the while(i<=N) - { -c[i]=c[i]+Val; -i=i+lowbit (i); + } - } + A intSuminti) at { - ints=0; - while(i) - { -s=s+C[i]; -i=i-lowbit (i); in } - returns; to } + - intMain () the { * inti,j,k; $ inta[5050];Panax Notoginseng while(SCANF ("%d", &n)! =EOF) - { the intCnt=0; +Memset (c,0,sizeof(c)); A for(i=1; i<=n;i++) the { +scanf"%d",&a[i]); -a[i]++; $Cnt=cnt+sum (N)-sum (a[i]); $Add (A[i],1); - } - intMi=CNT; the for(i=1; i<n;i++) - {Wuyicnt=cnt-(a[i]-1) + (na[i]); the if(cnt<mi) -Mi=CNT; Wu } -printf"%d\n", MI); About } $ return 0; -}View Code
Minimum Inversion Number array