Portal for HDU 1394
Problem Description
The inversion number of a given number sequence A1, A2, ..., the number of pairs (AI, AJ) that satisfy 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 o Btain 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
Main topic:
Give you an n number of permutations, and then you can put the first element to the last, to find the smallest of the n sequence number min;
Problem Solving Ideas:
Its inverse sequence number is N, if the t[i] is placed after the t[n], the number of inverse sequence will be reduced t[i], corresponding increase n (t[i]+1)
If the violence, the estimate will time out, so just use the number of line segments, note that line tree is just a tool,!!
On the code:
#include <iostream>#include <cstdio>using namespace STD;Const intmaxn=5005;intNUM[MAXN];struct{intL, R, Num;} tree[4*MAXN];voidBuildintRootintLintR) {tree[root].l=l; Tree[root].r=r; tree[root].num=0;if(L = = r)return;intMid= (L + R) >>1; Build (root<<1, L, mid); Build (root<<1|1, mid+1, r);}voidUpdateintRootintPOS) {if(TREE[ROOT].L = = TREE[ROOT].R) {tree[root].num++;return; }intMid= (TREE[ROOT].L+TREE[ROOT].R) >>1;if(pos<=mid) Update (root<<1, POS);ElseUpdate (root<<1|1, POS); tree[root].num=tree[root<<1].num+tree[root<<1|1].num;}intQueryintRootintLintR) {if(L <= tree[root].l && R >= TREE[ROOT].R)returnTree[root].num;intMid= (TREE[ROOT].L+TREE[ROOT].R)/2, ret=0;if(L <= mid) ret + = query (2*root, L, R);if(R>mid) Ret+=query (2*root+1, L, R);returnRET;}intMain () {intM while(~scanf("%d", &m)) {intsum=0; Build1,0, m); for(intI=1; i<=m; i++) {scanf("%d", &num[i]); Update1, Num[i]); Sum+=query (1, num[i]+1, m); }intAns=sum; for(intI=1; i<m; i++) {sum+= (M-1-num[i])-num[i];if(Sum<ans) Ans=sum; }printf("%d\n", ans); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hdu 1394 Minimum inversion number