HDU 2665 Kth number
Give you a sequence and ask you the kth big number of a inteval.
InputThe 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]
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
题意:给n个数的数组,m次询问,每次询问区间【L,R】的第k小
做法:裸的主席树,按点的位置,依次加入点权,每次询问,访问历史版本L和R二分判断答案即可。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
#define N 100005
int root[N], size[N*20], lchild[N*20], rchild[N*20];
int tot;
int a[N], b[N];
map<int, int>mp;
void insert(int last, int cur, int L, int R, int k)
{
size[cur]=size[last];
lchild[cur]=lchild[last];
rchild[cur]=rchild[last];
if(L==R)
{
size[cur]++;
return;
}
int mid=L+R>>1;
if(k<=mid) insert(lchild[last], lchild[cur]=++tot, L, mid, k);
else insert(rchild[last], rchild[cur]=++tot, mid+1, R, k);
size[cur]=size[lchild[cur]]+size[rchild[cur]];
}
int query(int last, int cur, int k, int L, int R)
{
if(L==R) return L;
int mid=L+R>>1;
int nows=size[lchild[cur]]-size[lchild[last]];
if(nows>=k) return query(lchild[last], lchild[cur], k, L, mid);
else return query(rchild[last], rchild[cur], k-nows, mid+1, R);
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
tot=0;
int ss=0, n, m, i, at;
scanf("%d%d", &n, &m);
for(i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
b[i]=a[i];
}
sort(b+1, b+n+1);
at = unique(b+1, b+n+1)-b;
at--;
for(i = 1; i <= at; i++) mp[b[i]]=++ss;
//cout<<"**"<<endl;
for(i = 1; i <= n; i++)
{
root[i]=++tot;
insert(root[i-1], root[i], 1, at, mp[a[i]]);
}
for(i = 0; i < m; i++)
{
int l, r, k;
scanf("%d%d%d", &l, &r, &k);
printf("%d\n", b[query(root[l-1], root[r], k, 1, at)]);
}
}
return 0;
}