zoukankan      html  css  js  c++  java
  • 主席树静态

    以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)]);
    	}
    }
    
  • 相关阅读:
    设计模式
    雨夹雪背景特效
    lottie-前端实现AE动效
    响应式布局实现原理
    关于小程序(含uniapp)中使用npm模块
    使用脚手架快速搭建React项目
    vue项目接入友盟统计站点数据
    git常用命令
    uniapp请求方法的封装
    小程序获取用户登录及手机号登录
  • 原文地址:https://www.cnblogs.com/TRDD/p/9813501.html
Copyright © 2011-2022 走看看