POJ 2299 ultra-quicksort (merge sort or bit tree + discretization available)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.