Test instructions: To an array, calculate the number of bubble sorts required, the number of elements is large, cannot be calculated using n^2 bubble sort.
Analysis: The problem is actually to find the number of reverse order, you can use the method of merging, I here with another method of writing, bit tree + discretization. Because the value of the element can reach a very large, but the number of elements up to only 500,000, you can sort these numbers first, discretization, such as 5 number: 1 5 8 233333333 122222, after sorting their corresponding label can be 1 2 3 5 4; Insert one number at a time Add (val,1), Calculates the number and the sum (val) of all previous numbers, then the number of reverse pairs = The current position of the number-sum (Val); Sweep it all over again.
The code is as follows:
#include<cstdio>#include<cstring>#include<string>#include<algorithm>#include<set>#include<map>#include<queue>#include<vector>#include<iterator>#include<utility>#include<sstream>#include<iostream>#include<cmath>#include<stack>UsingNamespace Std;Constint INF=1000000007;ConstDouble EPS=0.00000001;typedef __Int64LL;int N;int A[500001],pos[500001],elem[500001];IntLowbit(int x){return x&-x;}IntSum(int ID){int ret=0;While(ID>0){RET+=elem[ID]; Id-=Lowbit(ID);}return ret;}voidAdd(int ID,int Val){While(ID<=n){Elem[ID]+=val; Id+=Lowbit(ID);}}Vector<int>Save;IntMain(){While(scanf("%d", &n)!=eof&&n){Save.Clear();Memset(Elem,0,sizeof(Elem));For(int I=1; I<=n; I++){scanf("%d", &a[I]); Save.Push_back(A[I]);}Sort(Save.Begin(), Save.End());For(int I=1; I<=n; I++){POS[I]=Lower_bound(Save.Begin(), Save.End(), A[I])-save.Begin()+1; Discretization of}LLAns=0;For(int I=1;i<=N< Span class= "Sh-symbol" >;i++) {add< Span class= "Sh-symbol" > (Pos[i],1+=i-sum [i Cout<<ans<<endl return 0;< Span class= "Sh-cbracket" >
POJ 2299 ultra-quicksort (merge sort or bit tree + discretization available)