Topic Link: Click to enter
The partition tree solves the problem of fast seeking the K-value of the interval, the main idea of the algorithm is based on the dividing method of segment tree and fast row, which can realize the K-value of any interval in logn time. The following code is a template based on the hud4251.
The code is as follows:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace STD;Const intmaxn=100000+ +;inttree[ -][MAXN];///value for each location on each layerintSORTED[MAXN];/// already ranked in the ordinal numberinttoleft[ -][MAXN];///toleft[p][i] Indicates the number of levels of the P-layer from the 1-i into the leftvoidBuildintLintRintDEP) {if(L==R)return;intMid= (l+r) >>1;intsame=mid-l+1;/// indicates the number of left-hand numbers equal to the median value for(inti=l;i<=r;i++)if(Tree[dep][i]<sorted[mid]) same--;intLpos=l;intRpos=mid+1; for(inti=l;i<=r;i++) {if(Tree[dep][i]<sorted[mid]) tree[dep+1][lpos++]=tree[dep][i];Else if(tree[dep][i]==sorted[mid]&&same>0) tree[dep+1][lpos++]=tree[dep][i],same--;Elsetree[dep+1][rpos++]=tree[dep][i]; toleft[dep][i]=toleft[dep][l-1]+lpos-l; } Build (l,mid,dep+1); Build (mid+1, r,dep+1);}////query interval k large value, [L,r] is a large interval, [l,r] is a query of the inter-communityintQueryintLintRintLintRintDepintK) {if(L==R)returnTREE[DEP][L];intMid= (L+R)/2;/// by the number of elements of the difference, determine whether the left or right interval to find intcnt=toleft[dep][r]-toleft[dep][l-1];/// interval [l,r], the number of elements assigned to the left interval if(cnt>=k) {/// recalculate the interval to be queried intnewl=l+toleft[dep][l-1]-toleft[dep][l-1];intnewr=newl+cnt-1;returnQuery (l,mid,newl,newr,dep+1, k); }Else{/// recalculate the interval to be queried intNEWR = R+toleft[dep][r]-toleft[dep][r];intNEWL =newr-(r-l-cnt);returnQuery (mid+1, r,newl,newr,dep+1, k-cnt); }}intMain () {Freopen ("In.txt","R", stdin);intN,m,t;scanf("%d", &t); while(t--) {scanf("%d%d", &n,&m);memset(Tree,0,sizeof(tree)); for(intI=1; i<=n;i++) {scanf("%d", &tree[0][i]); sorted[i]=tree[0][i]; } sort (sorted+1, sorted+n+1); Build1N0); for(intI=0;i<3; i++) { for(intj=1; j<=n;j++)printf("%d", Tree[i][j]);printf("\ n"); }intS,t,k; while(m--) {scanf("%d%d%d", &s,&t,&k);printf("%d\n", Query (1, N,s,t,0, k)); } }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Partition tree template + template problem--hdu4251