主席树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
#include<stack>
#include<map>
using namespace std;
#define R register
#define ll long long
#define fo(i,a,b) for(R int (i)=(a);(i)<=(b);++(i))
#define dbg(x) cout<<#x<<"="<<x<<'\n'
#define mmt(x,y) memset(x,y,sizeof(x))
struct node{int x,id;}tmp[100010];
int n,m,rt[100010],lc[50*100010],rc[50*100010],cnt,siz[50*100010];
int a[100010];
bool cmp(const node &a,const node &b){return a.x<b.x;}
void build(int &x,int &y,int l,int r,int data)
{
y=++cnt;siz[y]=siz[x]+1;
if(l==r)return;
R int mid=(l+r)>>1;
if(data<=mid)build(lc[x],lc[y],l,mid,data);
else build(rc[x],rc[y],mid+1,r,data);
if(!lc[y])lc[y]=lc[x];
if(!rc[y])rc[y]=rc[x];
}
int query(int x,int y,int l,int r,int k)
{
if(l==r)return r;
R int mid=(l+r)>>1;
if(siz[lc[y]]-siz[lc[x]]<k)
return query(rc[x],rc[y],mid+1,r,k-siz[lc[y]]+siz[lc[x]]);
else return query(lc[x],lc[y],l,mid,k);
}
int main()
{
scanf("%d%d",&n,&m);
fo(i,1,n)scanf("%d",&tmp[i].x),tmp[i].id=i;
sort(tmp+1,tmp+1+n,cmp);
fo(i,1,n)a[tmp[i].id]=i;
fo(i,1,n)build(rt[i-1],rt[i],1,n,a[i]);
while(m--)
{
R int x,y,z;
scanf("%d%d%d",&x,&y,&z);
printf("%d\n",tmp[query(rt[x-1],rt[y],1,n,z)].x);
}
return 0;
}
显示 Gitment 评论