Test instructions: To find the number of times a sequence of bubbles is exchanged;
Reference: http://blog.csdn.net/suwei19870312/article/details/5293694
Ideas:
The number of bubbles in a sequence is the sum of the inverse logarithm corresponding to each number, and the naïve thought is the complexity of two for,o (n^2);
The number range is 0-999999999, the array size is 500000, so the first discretization, the structure of the original sequence of the subscript and the value of the record;
For the number of I, using the structure of the tree array, the number of numbers in the sequence is inserted into the tree array and the number of the current tree array before that number num,i-num that number is the inverse logarithm;
Saves the state of the number in the tree array with a new array;
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;intn,a[500010];intnum[500010];Long Longans;structnode{intId,w;} q[500010];intCMP (node A,node b) {returna.w<B.W;}intLowbit (inti) { returni& (-i);}intSuminti) { intCnt=0; while(i>=1) {CNT+=num[i];i-=lowbit (i); } returnCNT;}voidUpdateintIintval) { while(i<=N) {Num[i]+=val;i+=lowbit (i); }}intMain () {inti,j,k; while(SCANF ("%d", &n)! =EOF) { if(n==0) Break; memset (num,0,sizeof(num)); Ans=0; for(i=1; i<=n;i++) {q[i].id=i; scanf ("%d",&Q[I].W); } sort (Q+1, q+n+1, CMP); for(i=1; i<=n;i++) a[q[i].id]=i; for(j=1; j<=n;j++) {update (a[j],1); Ans+=j-sum (a[j]); } printf ("%lld\n", ans); } return 0;}
POJ 2299 Ultra-quicksort (tree-like array)