Topic Link: Click to enter
This is the median of a given interval, so it is also possible to set up a template for tree partitioning directly.
The code is as follows:
#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>using namespace STD;Const intmaxn=100000+ -;inttree[ -][MAXN];intSORTED[MAXN];inttoleft[ -][MAXN];voidBuildintLintRintDEP) {if(L==R)return;intMid= (l+r) >>1;intsame=mid-l+1; 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);}intQueryintLintRintLintRintDepintK) {if(L==R)returnTREE[DEP][L];intMid= (l+r) >>1;intcnt=toleft[dep][r]-toleft[dep][l-1];if(cnt>=k) {intnewl=l+toleft[dep][l-1]-toleft[dep][l-1];intnewr=newl+cnt-1;returnQuery (l,mid,newl,newr,dep+1, k); }Else{intNEWR=R+TOLEFT[DEP][R]-TOLEFT[DEP][R];intnewl=newr-(R-L-CNT);returnQuery (mid+1, r,newl,newr,dep+1, k-cnt); }}intMain () {intN,case=1; Freopen ("In.txt","R", stdin); while(scanf("%d", &n)!=eof) {printf("Case%d:\n", case++);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);intMscanf("%d", &m); while(m--) {intb;scanf("%d%d", &a,&b);intk= (B-A)/2+1;printf("%d\n", Query (1, N,a,b,0, k)); } }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hud--4251the Famous ICPC Team again+ Getting started with tree partitioning