luogu 3834 主席树模板

pass

 1 #include <algorithm>
 2 #include <cstdio>
 3 using namespace std;
 4 const int MAXN = 210000;
 5 int n,m,tot,cnt;
 6 int vec[MAXN],num[MAXN],hsh[MAXN];
 7 int ls[40 * MAXN],rs[40 * MAXN],sum[40 * MAXN],root[MAXN];
 8 int find(int x)
 9 {
10     int l = 1,r = tot;
11     while (l <= r)
12     {
13         int mid = l + r >> 1;
14         if (hsh[mid] < x)
15             l = mid + 1;
16         else
17             r = mid - 1; 
18     }
19     return l;
20 } 
21 void insert(int l,int r,int pre,int &k,int v)
22 {
23     k = ++cnt;
24     sum[k] = sum[pre] + 1;
25     if (l == r)
26         return;
27     int mid = l + r >> 1;
28     if (v <= mid)
29     {
30         rs[k] = rs[pre];
31         insert(l,mid,ls[pre],ls[k],v);
32     }
33     else
34     {
35         ls[k] = ls[pre];
36         insert(mid + 1,r,rs[pre],rs[k],v);
37     }
38 }
39 int ask(int l,int r,int k,int x,int y)
40 {
41     if (l == r)
42         return l;
43     int mid = l + r >> 1;
44     if (sum[ls[y]] - sum[ls[x]] >= k)
45         return ask(l,mid,k,ls[x],ls[y]);
46     else
47         return ask(mid + 1,r,k - (sum[ls[y]] - sum[ls[x]]),rs[x],rs[y]);
48 }
49 int main()
50 {
51     scanf("%d%d",&n,&m);
52     for (int i = 1;i <= n;i++)
53     {
54         scanf("%d",&vec[i]);
55         num[i] = vec[i];
56     }
57     sort(num + 1,num + 1 + n);
58     hsh[++tot] = num[1];
59     for (int i = 2;i <= n;i++)
60         if (num[i] != num[i - 1])
61             hsh[++tot] = num[i];
62     for (int i = 1;i <= n;i++)
63         insert(1,tot,root[i - 1],root[i],find(vec[i]));
64     int ta,tb,tk;
65     for (int i = 1;i <= m;i++)
66     {
67         scanf("%d%d%d",&ta,&tb,&tk);
68         printf("%d\n",hsh[ask(1,tot,tk,root[ta - 1],root[tb])]); 
69     }
70 }

 

posted @ 2020-02-16 15:07  IAT14  阅读(154)  评论(0编辑  收藏  举报