Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 15387 Accepted Submission (s): 9387
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
Single point update, Interval summation. Query and update synchronization, each update a number, the number of larger than its and, that is, the number of new reverse order. The complexity of time is nlogn.
Finally, each number as the first element appears in the sequence of the number of reverse order, to find the minimum value can be easily introduced, each time the number of replacement head, the new number of reverse order (the original number of reverse) minus (the number of numbers) plus (the total number minus the number of the numerical subtraction).
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include < Algorithm>using namespaceStd;ConstintN =5555;intNum[N<<2];intHehe[N];voidAdd(intI){Num[I] =Num[I *2] +Num[I *2 +1]; Update Father node}voidBuild(intLeft,intRight,intI) {//AchievementsNum[I] =0;if(Left ==Right)return;intMid = (Left +Right) /2;Build(Left,Mid,I *2);Build(Mid +1,Right,I *2 +1); }voidUpdate(intNumber,intLeft,intRight,intI) {//Update nodeif(Left ==Right){Num[I]++;return; }intMid;Mid = (Left +Right) /2;if(Number<=Mid)Update(Number,Left,Mid,I *2);ElseUpdate(Number,Mid +1,Right,I *2 +1);Add(I);}intQuery(intll,intRr,intLeft,intRight,intI) {//interval query andif(ll<=Left&&Rr>=Right)returnNum[I];intMid;Mid = (Left +Right) /2;inthaha =0;if(ll<=Mid)haha +=Query(ll,Rr,Left,Mid,I *2);if(Rr>Mid)haha +=Query(ll,Rr,Mid +1,Right,I *2 +1);returnhaha;}intMain(){intN; while(~scanf("%d", &N)){Build(0,N -1,1);intI,Sum =0; for(I =0;I<N;I++) {scanf("%d", &Hehe[I]);Sum +=Query(Hehe[I],N -1,0 ,N -1,1);Update(Hehe[I],0,N -1,1); }intHoHo =Sum; for(I =0;I<N;I++) {Sum +=N -2 *Hehe[I] -1; A formula for calculating the poor number of reverse orderHoHo =Min(Sum,HoHo); }Printf("%d\n",HoHo); }return0;}
Hdu 1394 Minimum inversion number (line segment tree)