I have read the categories and Solutions of Not Only Success .. First obtain the reverse number of the original sequence, as, and then assume that the first element of the current team is a, then there is a A-1 after a smaller than, there are n-a elements larger than a, when put a at the end of the team, the number of reverse orders of elements smaller than a-1, that is, as-= A-1 and for, each element larger than a has an inverse order, that is, as + = n-a, so the smallest as can be found after one enumeration. Here is the algorithm for reverse query of the Line Segment tree: the build process is equivalent to the insert process, that is, to insert the element with the value of x into the line segment tree, and then find the current x + 1, the number y of n elements is the number of newly generated Reverse Order pairs, that is, as + = y. [Cpp] # include <stdio. h> # define lson l, mid, rt * 2 # define rson mid + 1, r, rt * 2 + 1 # define X 5010 int a [X * 4], B [X], ll, rr; void pushup (int rt) {a [rt] = a [rt * 2] + a [rt * 2 + 1];} void build (int x, int l, int r, int rt) {if (l = r) {a [rt] ++; return ;} int mid = l + r> 1; if (x <= mid) build (x, lson); else build (x, rson); pushup (rt );} int que (int l, int r, int rt) {if (ll <= l & rr> = r) return a [rt]; int as = 0, mid = l + r> 1; if (ll <= mid) as + = que (Lson); if (rr> mid) as + = que (rson); return as;} int main () {int I, n, x, as, tmp; while (~ Scanf ("% d", & n) {for (I = 1; I <= n * 4; I ++) a [I] = 0; tmp = 0; as = n * n; for (I = 1; I <= n; I ++) scanf ("% d", & B [I]), B [I] ++; for (I = 1; I <= n; I ++) {ll = B [I], rr = n; tmp + = que (1, n, 1); build (B [I], 1, n, 1) ;}for (I = 1; I <n; I ++) {tmp + = n + 1-2 * B [I]; as = tmp <? Tmp: as;} printf ("% d \ n", as);} return 0 ;}