主席树静态

以POJ2104为模板题。附链接

主席树的学习可参考此博客

送上一个模板

#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 100000;
struct Tree {
	int lson, rson, cnt;
}T[maxn * 20 + 5];
int a[maxn + 5], t[maxn + 5], root[maxn + 5];
int n, m, q, tot;
void Init() {
	scanf("%d%d", &n, &q);
	for(int i = 1; i <= n; t[i] = a[i], i++)scanf("%d", &a[i]);
	sort(t + 1, t + n + 1);
	m = unique(t + 1, t + n + 1) - t - 1;
}
void Build(int &rt, int L, int R) {
	rt = ++tot;
	T[rt].cnt = 0;
	if(L != R) {
		int mid = (L + R) / 2;
		Build(T[rt].lson, L, mid);
		Build(T[rt].rson, mid + 1, R);
	}
}
void Insert(int &rt, int pre, int L, int R, int x, int val) {
	rt = ++tot;
	T[rt] = T[pre]; T[rt].cnt = T[pre].cnt + val;
	if(L != R) {
		int mid = (L + R) / 2;
		if(x <= mid)Insert(T[rt].lson, T[pre].lson, L, mid, x, val);
		else Insert(T[rt].rson, T[pre].rson, mid + 1, R, x, val);
	}
}
int Query(int nodel, int noder, int L, int R, int k) {
	if(L == R)return L;
	int mid = (L + R) / 2;
	int num = T[T[noder].lson].cnt - T[T[nodel].lson].cnt;
	if(num >= k)return Query(T[nodel].lson, T[noder].lson, L, mid, k);
	else return Query(T[nodel].rson, T[noder].rson, mid + 1, R, k - num);
}
int main() {
	Init();
	Build(root[0], 1, m);
	for(int i = 1; i <= n; i++) {
		int pos = lower_bound(t + 1, t + m + 1, a[i]) - t;
		Insert(root[i], root[i - 1], 1, m, pos, 1);
	}
	for(int i = 1; i <= q; i++) {
		int l, r, k;
		scanf("%d%d%d", &l, &r, &k);
		printf("%d\n", t[Query(root[l - 1], root[r], 1, m, k)]);
	}
}
posted @ 2018-10-14 21:26  呵呵!!!  阅读(85)  评论(0编辑  收藏  举报