题目大意:
给一个长为n的序列,m次询问,每次询问[l, r]内第k小的数是几。 n <= 100000, m <= 5000
emmmm这题其实和poj2104一模一样的。不过poj的那题我用的是划分树,这题用一下主席树。(划分树是不支持修改的)
主席树又名函数式线段树balabalabala....(关于主席树的简介包括名字来历我就不介绍了吧主要是我也不知道些什么)
进入正题。。
首先我们要将所有数字离散化。主席树相当于是在每个位置维护了一个线段树,线段树的节点是一个区间[x, y],这里的x和y都是离散后数的编号。
当然如果真的在每个位置建一棵线段树,空间肯定爆炸= = 不过我们先不管这个问题。
主席树节点中维护的值,是1-i之间这个区间内出现了数的次数。然后当我们查询的时候,就是利用到了前缀和的思想。
然后我们来模拟一下一组数据吧。
7 1
1 5 2 6 3 7 4
2 5 3
首先建树。
然后我们逐一插入数字。
将每个数字的大小(即离散化后的编号)插入到它的位子上,然后并把所有包括它的区间的sum都++。
。。。。。。。。
直到把所有数字插入以后,情况是这样的。
那么建树的具体过程大致如上。接下来我们考虑查询。
要查询[2, 5]中第3大的数我们首先把第1棵线段树和第5棵拿出来。
然后我们发现,将对应节点的数相减,刚刚好就是[2, 5]内某个范围内的数的个数。比如[1, 4]这个节点相减是2,就说明[2. 5]内有2个数是在1~4范围内(就是2, 3)。
所以对于一个区间[l, r],我们可以每次算出在[l, mid]范围内的数,如果数量>=k(k就是第k大),就往左子树走,否则就往右子树走。
这一段代码如下:
inline int query(int u, int v, int l, int r, int k)
{
if (l == r) return l;
int x = sum[L[v]] - sum[L[u]];
if (x >= k) return query(L[u], L[v], l, mid, k);
else return query(R[u], R[v], mid+1, r, k-x);
}
个人感觉还是挺好理解的qwq
那么之前说过的数组开不了的问题,你就先建一棵空树,然后更新的时候需要新开的点就开,不需要的就连到原来的点上去。这样复杂度是nlogn的。
然后放一下完整代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cctype>
#include<vector>
#include<map>
#include<queue>
#define rep(i, x, y) for (int i = (x); i <= (y); i ++)
#define down(i, x, y) for (int i = (x); i >= (y); i --)
#define mid (l+r)/2
#define lc o<<1
#define rc o<<1|1
#define pb push_back
#define mp make_pair
#define Pair pair<int, int>
#define F first
#define S second
#define B begin()
#define E end()
using namespace std;
typedef long long LL;
//head
const int N = 100010, LOG = 20;
int n, m, q, tot = 0;
int a[N], b[N];
int T[N], sum[N*LOG], L[N*LOG], R[N*LOG];
inline int build(int l, int r)
{
int rt = ++ tot;
if (l < r){
L[rt] = build(l, mid);
R[rt] = build(mid+1, r);
}
return rt;
}
inline 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){
if (x <= mid) L[rt] = update(L[pre], l, mid, x);
else R[rt] = update(R[pre], mid+1, r, x);
}
return rt;
}
inline int query(int u, int v, int l, int r, int k)
{
if (l == r) return l;
int x = sum[L[v]] - sum[L[u]];
if (x >= k) return query(L[u], L[v], l, mid, k);
else return query(R[u], R[v], mid+1, r, k-x);
}
int main()
{
int Test; scanf("%d", &Test);
while (Test --){
tot = 0;
memset(T, 0, sizeof T); memset(sum, 0, sizeof sum);
memset(L, 0, sizeof L); memset(R, 0, sizeof R);
scanf("%d%d", &n, &q);
rep(i, 1, n) scanf("%d", &a[i]), b[i] = a[i];
sort(b+1, b+1+n);
m = unique(b+1, b+1+n)-b-1;
T[0] = build(1, m);
rep(i, 1, n){
a[i] = lower_bound(b+1, b+1+m, a[i]) - b;
T[i] = update(T[i-1], 1, m, a[i]);
}
while (q --){
int x, y, z; scanf("%d%d%d", &x, &y, &z);
int p = query(T[x-1], T[y], 1, m, z);
printf("%d\n", b[p]);
}
}
return 0;
}
注意内存限制有点小。
我是不会告诉你我mle了无数发的。。