• 主席树静态


    以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
    ", t[Query(root[l - 1], root[r], 1, m, k)]);
    	}
    }
    
  • 相关阅读:
    IIS7 503错误 Service Unavailable
    android错误系列之导出数据库出错Failed to pull selection
    android学习笔记(入门篇)
    使用cmd命令删除文件夹下所有文件
    vue 动态插入组件
    js获取当前时间
    获取带参值
    以毫秒为单位的时间长度转化为时分秒时间格式的时间长度
    js如何复制一个对象?
    想在已创建的Vue工程里引入vux组件
  • 原文地址:https://www.cnblogs.com/TRDD/p/9813501.html
Copyright © 2020-2023  润新知