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
Test Instructions: A series of length n can be changed to n different series (each time the first element is placed to the last one), the number of reverse order in these sequences is the minimum number, reverse: I < J and Ai > aj, subscript Less than the subscript of the element, the value is greater than the element.
You can first use the segment tree to find out the number of reverse order in its own sequence, and then determine whether each element is placed in the last one when the number of reverse order is less than the number of reversed sequence, successive updates.
#include <stdio.h>#include<string.h>#include<algorithm>using namespacestd;Const intinf=0x3f3f3f3f;Const intn=5010;structnode{intLeft , right, num;} no[4*N];intMin;voidBulid (intLeftintRightintroot) { intmid; No[root].left=Left ; No[root].right=Right ; No[root].num=0; if(left = right)return ; Mid= (left+right)/2; Bulid (left, Mid, Root*2); Bulid (Mid+1, right, root*2+1);}voidInsert (intPintRoot///the number of reverse order numbers can be counted when inserting data{ intmid; No[root].num++; if(No[root].left = = no[root].right)return ; Mid= (no[root].left+no[root].right)/2; if(P <=mid) {Min+ = no[root*2+1].num; Insert (p, Root*2); } ElseInsert (P, root*2+1);}intMain () {intI, N, P[n], ans; while(SCANF ("%d", &n)! =EOF) {Bulid (0, N-1,1); Min=0; for(i =1; I <= N; i++) {scanf ("%d", &P[i]); Insert (P[i],1); } ans=Min; for(i =1; I <= N; i++) {Min+ = (n1-p[i])-p[i];///when the first move to the last one, the number of reverse orders plus those larger than it, minus those smaller than the number of numbers (because the elements of the sequence are 0~n-1)Ans =min (ans, min); } printf ("%d\n", ans); } return 0;}
HDU 1394 Minimum Inversion number