主席树学习笔记-hdu-2665
主席树就是对每个历史版本都建了一颗线段树,这样我们在统计一些问题的时候,对于一个区间[L,R]的询问,就可以利用前缀和的思想找到第L-1和第R颗历史版本的线段树来处理查找。由于这样空间需求就增大了,注意到如果每个版本之间只是多更新了一个点的话,那么这两颗树就只有一条链不相同,我们不妨在前一颗树的基础上建立第二颗树,用链表做链接,这样就达到了节省空间的目的。
Kth number
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15653 Accepted Submission(s): 4724
Problem Description
Give you a sequence and ask you the kth big number of a inteval.
Input
The first line is the number of the test cases.
For each test case, the first line contain two integer n and m (n, m <= 100000), indicates the number of integers in the sequence and the number of the quaere.
The second line contains n integers, describe the sequence.
Each of following m lines contains three integers s, t, k.
[s, t] indicates the interval and k indicates the kth big number in interval [s, t]
For each test case, the first line contain two integer n and m (n, m <= 100000), indicates the number of integers in the sequence and the number of the quaere.
The second line contains n integers, describe the sequence.
Each of following m lines contains three integers s, t, k.
[s, t] indicates the interval and k indicates the kth big number in interval [s, t]
Output
For each test case, output m lines. Each line contains the kth big number.
Sample Input
1
10 1
1 4 2 3 5 6 7 8 9 0
1 3 2
Sample Output
2
Source
主席树的模板题,求静态的区间第k小值。
#include<bits/stdc++.h> using namespace std; #define mid ((L+R)>>1) const int maxn=100010; int root[maxn],a[maxn],tot; struct node{int lc,rc,sum;}T[maxn*40]; vector<int>v; int getid(int x){return lower_bound(v.begin(),v.end(),x)-v.begin()+1;} void update(int &x,int y,int L,int R,int d){ T[++tot]=T[y],T[tot].sum++,x=tot; if(L==R) return; if(d<=mid){ update(T[x].lc,T[y].lc,L,mid,d); } else{ update(T[x].rc,T[y].rc,mid+1,R,d); } } int ask(int x,int y,int L,int R,int d){ if(L==R) return L; int s=T[T[x].lc].sum-T[T[y].lc].sum; if(s>=d) return ask(T[x].lc,T[y].lc,L,mid,d); else return ask(T[x].rc,T[y].rc,mid+1,R,d-s); } int main(){ int t,n,m,i,j,k,l,r; cin>>t; while(t--){ v.clear(); tot=0; cin>>n>>m; for(i=1;i<=n;++i) scanf("%d",a+i),v.push_back(a[i]); sort(v.begin(),v.end()),v.erase(unique(v.begin(),v.end()),v.end()); for(i=1;i<=n;++i) update(root[i],root[i-1],1,n,getid(a[i])); for(i=1;i<=m;++i){ scanf("%d%d%d",&l,&r,&k); printf("%d\n",v[ask(root[r],root[l-1],1,n,k)-1]); } } return 0; }