original title link:http://poj.org/problem?id=2299
Test Instructions: the number of times a bubble sort is exchanged for numbers
Analysis: at first listening to others said the challenge on the bubble sort Exchange times, has been confused. Think about it one day and understand it instantly.
In fact, the sequence is inserted into another array in the order you are inserted, where the number is placed in the ordered position. So the front is smaller than it, the back is bigger than it.
The answer can be calculated by very convenient calculation.
for (int0; j < N; j + +) [ + = J- sum (a[j ]); 1 );]
SUM (A[j]) is the number of <=a[j] that have been inserted, j-sum (A[j]) is the number of >a[j].
But the 999999999 is too big to be discretized.
Code:
1 Const intMAXN =500010;2 intBIT[MAXN];3 structNum {4 intVal;5 intPos;6 BOOL operator< (ConstNum &a)Const {7 returnVal <A.val;8 }9 }NUM[MAXN];Ten intN; One A intLowbit (intx) { - returnx&-x; - } the - intSuminti) { - intres =0; - while(I >0) { +Res + =Bit[i]; -I-=lowbit (i); + } A returnRes; at } - - voidAddintIintx) { - while(I <=N) { -Bit[i] + =x; -i + =lowbit (i); in } - } to + - the * voidsolve () { $ while(Cin >> n&&N) {Panax Notoginsengmemset (bit,0,sizeof(bit)); -ll ans =0; the for(inti =0; I < n; i++) { +CIN >>Num[i].val; ANum[i].pos =i; the } +Sort (num, num +n); - for(inti =0; I < n; i++) { $ intTMP = SUM (Num[i].pos +1); $cout << tmp << Endl <<Endl; -Ans + = i-tmp; -Add (Num[i].pos +1,1); the } -cout << ans <<Endl;Wuyi } the}
(Tree-like array) POJ-2299 Ultra-quicksort