Test instructions: Input 0 ~ n-1 Total n number, each time take the first number to the end of the sequence to form a new sequence, ask these series in reverse order the number of the least.
Example: Input 0,3,2,4,1,5
First, the number of reverse order, first put 0 to the last 3,2,4,1,5,0 and then the number of reverse order, go down, take the inverse number of the minimum value.
Use the line segment tree to find the inverse pair of the originally entered sequence.
There are two kinds of thinking in reverse order, one is: seeking A[i] The number of smaller than it, accumulate. The second is: A[i] before the number of large, cumulative. The line tree uses the second thought.
Each time the a[i] is inserted, the leaf node value of the interval is [i,i] 1.
If we ask [A[i], n-1] The number of 1 in the interval, that is, the number of a[i] larger than a[i], because the number is larger than the a[i] is inserted and in [A[i], n-1].
Each time you move the first number to the last face, the reverse order number changes is-a[i] + (n-1)-a[i]
Because A[i] has a[i] A number smaller than it, there are (n-1)-a[i] A number larger than it, so each move, reverse order to reduce a[i], increase (n-1)-a[i].
#include <iostream> #include <cstdio> #include <cstdlib> #include <ctime> #include < algorithm>using namespace Std;const int INF = 0x3f3f3f3f;const int maxn = 5050;int num[maxn << 2];void pushup (int RT) {Num[rt] = Num[rt << 1] + num[rt << 1 | 1];} void build (int l, int r, int rt) {if (L = = r) {Num[rt] = 0; Build leaf node value 0 return; } int mid = (L + r) >> 1; Build (L, Mid, RT << 1); Build (mid + 1, R, (RT << 1) +1); Pushup (RT);} void Update (int p, int l, int r, int rt) {if (L = = r) {Num[rt] + +; Insert a number and place its corresponding leaf node value at 1 return; } int mid = (L + r) >> 1; if (P <= mid) Update (P, L, Mid, RT << 1); else Update (p, mid + 1, R, (RT << 1) + 1); Pushup (RT);} int query (int ll,int rr,int l,int r,int RT) {if (LL <= l && R <= RR) {return NUM[RT]; } int mid = (l+r) >> 1; Intres = 0; if (ll <= mid) Res + = query (ll,rr,l,mid,rt << 1); if (RR > Mid) Res + = query (LL,RR,MID+1,R, (RT << 1) +1); return res;} int main () {int n; int A[MAXN]; while (~SCANF ("%d", &n)) {build (0,n-1,1); int res = 0; for (int i = 0; i< N; i++) {scanf ("%d", &a[i]); Res + = query (a[i],n-1,0,n-1,1); (a[i],n-1) The number of 1 in the interval update (a[i],0,n-1,1); } int ans = INF; for (int i = 0; i < n; i++) {res = Res-a[i] + n-1-a[i]; Not once moved, order to number change ans = ans < res? Ans:res; } printf ("%d\n", ans); }}
HDU 1394 Minimum Inversion number