http://poj.org/problem?id=2104
主席树裸题没什么好说的,学主席树请看上一篇博客
1 #include<algorithm> 2 #include<iostream> 3 #include<cstdio> 4 using namespace std; 5 const int N=1e5+5; 6 int T; 7 int n,q; 8 int a[N],b[N],rt[N],ls[N*32],rs[N*32],sum[N*32]; 9 int cnt,ans; 10 void up(int &o,int pre,int l,int r,int p){ 11 o=++cnt; 12 ls[o]=ls[pre]; 13 rs[o]=rs[pre]; 14 sum[o]=sum[pre]+1; 15 if(l==r)return; 16 int m=(l+r)/2; 17 if(p<=m)up(ls[o],ls[pre],l,m,p); 18 else up(rs[o],rs[pre],m+1,r,p); 19 } 20 int qu(int o,int pre,int l,int r,int k){ 21 int g=sum[ls[o]]-sum[ls[pre]]; 22 if(l==r)return l; 23 int m=(l+r)/2; 24 if(k<=g)return qu(ls[o],ls[pre],l,m,k); 25 return qu(rs[o],rs[pre],m+1,r,k-g); 26 } 27 int h=1e5+5; 28 int main(){ 29 scanf("%d%d",&n,&q); 30 for(int i=1;i<=n;i++){ 31 scanf("%d",&a[i]); 32 b[i]=a[i]; 33 } 34 sort(b+1,b+1+n); 35 for(int i=1;i<=n;i++){ 36 a[i]=lower_bound(b+1,b+1+n,a[i])-b; 37 } 38 for(int i=1;i<=n;i++){ 39 up(rt[i],rt[i-1],1,h,a[i]); 40 } 41 while(q--){ 42 int ql,qr,k; 43 scanf("%d%d%d",&ql,&qr,&k); 44 int id=qu(rt[qr],rt[ql-1],1,h,k); 45 printf("%d ",b[id]); 46 } 47 } 48 /* 49 7 3 50 1 5 2 6 3 7 4 51 2 5 3 52 4 4 1 53 1 7 3 54 */