转自:http://www.cnblogs.com/Empress/p/4652449.html
题意:给n、m
下面有n个数 (编号1到n)
有m个询问,询问的是上面的数的编号在[l,r]之间第k小的数
n、m的范围都是
HDOJ2665的题意居然是一样的~~~说好的第K大呢···
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
#define lson l, m
#define rson m+1, r
const int N = 1e5 + 5;
int L[N << 5], R[N << 5], sum[N << 5]; //这个区间内数字的个数
int tot; //tot是现在数组开到多大了
int a[N], T[N], Hash[N];//Ti表示一棵[1, i]区间的线段树
//我们并不需要建一整棵树,我们只需要 单独建立logn个结点,跟Ti−1连起来就好了
int build(int l, int r)
{
int rt = (++tot);
sum[rt] = 0;
if (l<r)
{
int m = (l + r) >> 1;
L[rt] = build(lson);
R[rt] = build(rson);
}
return rt;
}
int update(int pre, int l, int r, int x)
{
int rt = (++tot);
L[rt] = L[pre], R[rt] = R[pre], sum[rt] = sum[pre] + 1;
if (l<r)
{
int m = (l + r) >> 1;
if (x <= m)
L[rt] = update(L[pre], lson, x);
else
R[rt] = update(R[pre], rson, x);
}
return rt;
}
int query(int u, int v, int l, int r, int k)
{
if (l >= r)
return l;
int m = (l + r) >> 1;
int num = sum[L[v]] - sum[L[u]];//[u,v]=[1,v]-[1,u]
if (num >= k)
return query(L[u], L[v], lson, k);
else
return query(R[u], R[v], rson, k - num);
}//一边做减法 一边查询
int main()
{
tot = 0;
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
Hash[i] = a[i];
}
sort(Hash + 1, Hash + n + 1);
int d = unique(Hash + 1, Hash + n + 1) - Hash - 1;
T[0] = build(1, d);
for (int i = 1; i <= n; i++)
{
int x = lower_bound(Hash + 1, Hash + d + 1, a[i]) - Hash;
T[i] = update(T[i - 1], 1, d, x);
}
while (m--)
{
int l, r, k;
scanf("%d%d%d", &l, &r, &k);
int x = query(T[l - 1], T[r], 1, d, k);
printf("%d\n", Hash[x]);
}
return 0;
}
转自:
http://www.cnblogs.com/Empress/p/4652449.html