A sequence composed of 0 .. n-1. Each time, you can move the first element of the team to the end of the team to find the number of minimum reverse pairs of the N sequences.
Algorithm :
Returns the reverse order of a tree array. When element I is added, the value of a [I] under element I is + 1, from the end of the team to the first of the team,
The logarithm of the reverse order + = getsum (I-1) when you join the queue, that is, the number of elements whose subscript is greater than it but whose value is smaller than it.
Because the tree array cannot process the element whose subscript is 0, when each element enters the + 1, the corresponding other Program You must also adjust it accordingly.
After finding the number of reverse pairs of the original sequence, move the first element to the end of the team. The reverse logarithm is
The original reverse logarithm + number of elements greater than I-number of elements smaller than I, because it is 0 .. n, it is easy to calculate directly, every time you update Min.
# Include <stdio. h> # define maxn 10000int C [maxn], a [maxn], n; int min (int A, int B) {if (a <B) return; else return B;} int lowbit (int I) {return I &-I;} void Update (int I, int X) {While (I <= N) {c [I] + = x; I + = lowbit (I) ;}} int getsum (INT X) {int sum = 0; while (x> 0) {sum + = C [X]; X-= lowbit (x);} return sum;} int main () {While (scanf ("% d", & N) = 1) {for (INT I = 1; I <= N; I ++) C [I] = 0; int sum = 0; For (INT I = 1; I <= N; I ++) {scanf ("% d", & A [I]) ;}for (INT I = N; I> = 1; I --) {update (A [I] + 1, 1); sum + = getsum (A [I]);} int ans = sum; For (INT I = 1; I <= N; I ++) {sum = sum-A [I] + (n-A [I]-1); ans = min (ANS, sum );} printf ("% d \ n", ANS);} return 0 ;}