Minimum inversion number Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 19452 Accepted Submission (s): 11701
Problem Description the inversion number of a given number sequence A1, A2, ..., the number of pairs (AI, AJ) that s Atisfy 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
10 1 3 6 9 0 8 5 7 4 2
Sample Output
16
Approximate test instructions:
For the given array, each time the first element is moved to the last, the smallest number of reverse order in the process is obtained.
General idea:
You can use merge to sort the request. This is the solution of the line tree.
Handle the initial array: For each number, look for the number of numbers that are already in the segment tree that are larger than him. This number is then added to the segment tree.
Every move: Suppose this move is M, then he is smaller than M has m-1, bigger than M has n-m, so the new reverse number equals the original reverse number-(m-1) + n-m.
#include <cstdio> #include <cstring> #include <iostream> using namespace std;
#define _MAX 5010 int Seg [_max<<2];
int A [_max];
int n;
int Query (int p, int l, int r, int x, int y) {if (x<=l && y>=r) return seg[p];
int mid = (l+r) >>1,ans = 0;
if (x<=mid) ans + = Query (2*p, L, Mid, X, y);
if (y> mid) ans + = Query (2*p+1, mid+1, R, X, y);
return ans;
} void Update (int p, int l, int r, int x) {if (l==r) {seg[p]++;
Return
} int mid = (l+r) >>1;
if (x<=mid) Update (2*p, L, Mid, X);
else Update (2*p+1, mid+1, R, X);
SEG[P] = Seg[2*p] + seg[2*p+1];
} int main () {//freopen ("In.txt", "R", stdin);
while (scanf ("%d", &n)! = EOF) {memset (seg,0,sizeof (Seg));
for (int i=1; i<=n; i++) {scanf ("%d", a+i);
a[i]++;
} int ans = 0;
for (int i=1; i<=n; i++) {ans + = Query (1, 1, N, A[i], n);
Update (1, 1, N, A[i]);
} int Min = ans;
for (int i=1; i<=n; i++) {ans = Ans-a[i] + 1 + n-a[i]; if (ans<min) Min = ans;
} printf ("%d\n", Min);
} return 0; }