Test Instructions: give a number n (n<500,000), and then give the sequence of n number a1, a2.....an each AI range is 0~999,999,999 require the number of times to be exchanged in ascending order by the method of the adjacent two exchanges
Analysis: In fact, after a simulation, will find wonderful things, this sort is ranked by position, the maximum requirements to the largest, the smallest to go to the smallest, the transformation of thought this is a problem of the inverse logarithm, the answer is the logarithm of the reverse order.
Here the data is too large 999999999, the array cannot be opened so large, we can discretization, only record the relative size.
Here the discretization is different, here in order to press, the space to change the time of the method. The previous article has said that sum (i) indicates how much earlier than this small number, can sum (n)-sum (i), here is the new knowledge is sum (i) is how many small number, that the current total is I, the large number is (I-sum (i) This is the reverse order of the method, visual very fast.
#include <stdio.h>#include<algorithm>#include<string.h>using namespacestd;inta[ -];intb[ -],c[ -],n;intLowbit (intx) { returnx& (-x);}voidAddintKintnum) { while(k<=N) {c[k]+=num; K+=Lowbit (k); }}intSumintk) {intans=0; while(k) {ans+=C[k]; K-=Lowbit (k); } returnans;}intMain () { while(SCANF ("%d", &n)! =EOF) {memset (c,0,sizeof(c)); if(n==0) Break; for(intI=0; I<n; i++) {scanf ("%d",&A[i]); B[i]=A[i]; } sort (B,b+N); intsumm=0; for(intI=0; I<n; i++) {A[i]= (Lower_bound (b,b+n,a[i])-B) +1; Summ+ = (sum (n)-sum (a[i])); //summ+= (I-sum (a[i]+1)Add (A[i],1); } printf ("%d\n", Summ); }}
View Code
POJ 2299 Ultra-quicksort (tree-like array && discretization && reverse order)