跳到正文

个人记录

【模板】主席树

Chenhaorui88约 16 分钟
原文
文章信息与版本

文章信息

收录
2026年4月11日
更新
2026年4月11日
篇幅
约 16 分钟

版本

  1. v2当前
  2. v1

P3919 可持久化线段树 1

C++
// 包含所有标准库
#include<bits/stdc++.h>
using namespace std;

// 全局变量
int a[30000086],        // 原始数组,存储初始值
    root[30000086],     // 各个版本的根节点索引
    sz = 0;             // 主席树节点计数器

// 主席树节点结构
struct S {
    int ch[2];          // 左右子节点索引,ch[0]左子树,ch[1]右子树
    int v;              // 节点存储的值(这里是数组元素的值)
} tr[30000086];         // 主席树节点数组

// 创建新节点(复制已有节点)
int mak(int id) {
    tr[++sz].v = tr[id].v;              // 复制节点值
    tr[sz].ch[0] = tr[id].ch[0];        // 复制左子节点指针
    tr[sz].ch[1] = tr[id].ch[1];        // 复制右子节点指针
    return sz;                          // 返回新节点索引
}

// 构建初始版本的主席树
int build_tree(int l, int r) {
    int temp = ++sz;    // 创建新节点,分配索引

    // 如果是叶子节点
    if (l == r) {
        tr[sz].v = a[l];    // 存储数组元素值
        return sz;          // 返回节点索引
    }

    // 递归构建左右子树
    int mid = (l + r) / 2;
    tr[temp].ch[0] = build_tree(l, mid);    // 构建左子树
    tr[temp].ch[1] = build_tree(mid + 1, r); // 构建右子树

    return temp;    // 返回当前节点索引
}

// 更新操作:基于历史版本创建新版本
int update(int x, int l, int r, int id, int v) {
    // 创建当前节点的新副本(关键:实现可持久化)
    x = mak(x);

    // 如果是叶子节点,直接修改值
    if (l == r) {
        tr[x].v = v;        // 更新节点值
    }
    // 非叶子节点,递归更新
    else {
        int mid = (l + r) / 2;

        // 根据要更新的位置决定更新左子树还是右子树
        if (id <= mid)
            tr[x].ch[0] = update(tr[x].ch[0], l, mid, id, v);
        else
            tr[x].ch[1] = update(tr[x].ch[1], mid + 1, r, id, v);
    }

    return x;   // 返回新版本的当前节点索引
}

// 查询操作:在指定版本中查询值
int query(int x, int l, int r, int id) {
    // 找到叶子节点,返回存储的值
    if (l == r) {
        return tr[x].v;
    }
    // 非叶子节点,递归查找
    else {
        int mid = (l + r) / 2;

        // 根据要查询的位置决定查询左子树还是右子树
        if (id <= mid)
            return query(tr[x].ch[0], l, mid, id);
        else
            return query(tr[x].ch[1], mid + 1, r, id);
    }
}

int main() {
    // 优化输入输出
    cin.tie(0)->sync_with_stdio(0);

    int n, m;
    cin >> n >> m;  // n:数组长度,m:操作次数

    // 读入初始数组
    for (int i = 1; i <= n; i++)
        cin >> a[i];

    // 构建初始版本(版本0)
    root[0] = build_tree(1, n);

    // 处理m个操作
    for (int i = 1; i <= m; i++) {
        int temp,    // 基于哪个历史版本
            opt,     // 操作类型:1-更新,2-查询
            s;       // 位置索引
        cin >> temp >> opt >> s;

        // 更新操作
        if (opt == 1) {
            int c;   // 要更新的新值
            cin >> c;
            // 基于版本temp创建新版本i,在位置s更新为值c
            root[i] = update(root[temp], 1, n, s, c);
        }
        // 查询操作
        else {
            // 查询版本temp中位置s的值
            printf("%d\n", query(root[temp], 1, n, s));
            // 查询操作不修改,新版本与查询版本相同
            root[i] = root[temp];
        }
    }

    return 0;
}

干净版

C++
#include<bits/stdc++.h>
using namespace std;
int a[30000086],root[30000086],sz = 0;
struct S{
	int ch[2];
	int v;
}tr[30000086];
int mak(int id){
	tr[++sz].v = tr[id].v;
	tr[sz].ch[0] = tr[id].ch[0];
	tr[sz].ch[1] = tr[id].ch[1];
	return sz;
}
int build_tree(int l,int r){
	int temp = ++sz;
	if(l==r){
		tr[sz].v = a[l];
		return sz;
	}
	int mid = (l+r)/2;
	tr[temp].ch[0] = build_tree(l,mid);
	tr[temp].ch[1] = build_tree(mid+1,r);
	return temp;
}
int update(int x,int l,int r,int id,int v){
	x = mak(x);
	if(l==r) tr[x].v = v;
	else{
		int mid = (l+r)/2;
		if(id<=mid)
			tr[x].ch[0] = update(tr[x].ch[0],l,mid,id,v);
		else
			tr[x].ch[1] = update(tr[x].ch[1],mid+1,r,id,v);
	}
	return x;
}
int query(int x,int l,int r,int id){
	if(l==r) return tr[x].v;
	else{
		int mid = (l+r)/2;
		if(id<=mid)
			return query(tr[x].ch[0],l,mid,id);
		else
			return query(tr[x].ch[1],mid+1,r,id);
	}
}
int main(){
	cin.tie(0)->sync_with_stdio(0);
	int n,m;
	cin>>n>>m;
	for(int i = 1;i<=n;i++)
		cin>>a[i];
	root[0] = build_tree(1,n);
	for(int i = 1;i<=m;i++){
		int temp,opt,s;
		cin>>temp>>opt>>s;
		if(opt==1){
			int c;
			cin>>c;
			root[i] = update(root[temp],1,n,s,c);
		}
		else{
			printf("%d\n",query(root[temp],1,n,s));
			root[i]=root[temp];
		}
	}
}

P3834 【模板】可持久化线段树 2

C++
#include<bits/stdc++.h>
using namespace std;

// 数组定义
int a[5000086], d[5000086], root[5000086], sz = 0;  // sz:节点计数器
int n, m;

// 线段树节点结构体
struct S{
    int ch[2];  // 左右子节点编号,ch[0]:左孩子,ch[1]:右孩子
    int cnt;    // 当前值域区间内元素个数
}tr[5000086];   // 可持久化线段树节点数组

// 建空树(初始版本)
int build(int l, int r){
    int temp = ++sz;           // 创建新节点
    if(l == r){                // 叶子节点
        tr[temp].cnt = 0;      // 初始计数为0
        return temp;
    }
    int mid = (l + r) / 2;     // 二分值域
    // 递归构建左右子树
    tr[temp].ch[0] = build(l, mid);
    tr[temp].ch[1] = build(mid + 1, r);
    tr[temp].cnt = 0;          // 内部节点初始计数为0
    return temp;
}

// 更新操作:在版本x基础上插入值id,返回新版本根节点
int update(int x, int l, int r, int id){
    int temp = ++sz;           // 创建新节点(可持久化:不修改原节点)
    tr[temp] = tr[x];          // 复制原节点信息
    if(l == r){                // 叶子节点
        tr[temp].cnt++;        // 值id出现次数+1
        return temp;
    }
    int mid = (l + r) / 2;
    // 根据id的位置决定更新左子树还是右子树
    if(id <= mid)
        tr[temp].ch[0] = update(tr[x].ch[0], l, mid, id);
    else
        tr[temp].ch[1] = update(tr[x].ch[1], mid + 1, r, id);
    // 更新当前节点的计数 = 左子树计数 + 右子树计数
    tr[temp].cnt = tr[tr[temp].ch[1]].cnt + tr[tr[temp].ch[0]].cnt;
    return temp;
}

// 查询操作:在区间[u, v](对应版本root[l-1]和root[r])中查找第k小值
int query(int u, int v, int l, int r, int k){
    if(l == r) return l;       // 叶子节点:找到第k小值
    int mid = (l + r) / 2;
    // 计算左子树中元素个数差 = 版本v左子树计数 - 版本u左子树计数
    // 这个差值就是区间[l, r]中值在[l, mid]范围内的元素个数
    int lsum = tr[tr[v].ch[0]].cnt - tr[tr[u].ch[0]].cnt;
    if(k <= lsum)              // 第k小在左子树
        return query(tr[u].ch[0], tr[v].ch[0], l, mid, k);
    else                       // 第k小在右子树
        // 关键:在右子树中查找第 (k - lsum) 小
        return query(tr[u].ch[1], tr[v].ch[1], mid + 1, r, k - lsum);
}

int main(){
    // 输入
    cin >> n >> m;
    for(int i = 1; i <= n; i++){
        cin >> a[i];
        d[i] = a[i];           // d数组用于离散化
    }

    // ========== 离散化处理 ==========
    // 1. 排序
    sort(d + 1, d + n + 1);
    // 2. 去重,cur为去重后元素个数
    int cur = unique(d + 1, d + n + 1) - d - 1;
    // 3. 将原数组a映射为离散化后的值(1-based)
    for(int i = 1; i <= n; i++)
        a[i] = lower_bound(d + 1, d + cur + 1, a[i]) - d;

    // ========== 建立可持久化线段树 ==========
    // 版本0:空树
    root[0] = build(1, cur);
    // 依次插入每个元素,生成新版本
    for(int i = 1; i <= n; i++)
        root[i] = update(root[i - 1], 1, cur, a[i]);

    // ========== 处理查询 ==========
    while(m--){
        int x, y, k;
        cin >> x >> y >> k;
        // 查询区间[x, y]的第k小
        // root[x-1]: 前缀[1, x-1]的版本
        // root[y]: 前缀[1, y]的版本
        // 两者做差得到区间[x, y]的信息
        int idx = query(root[x - 1], root[y], 1, cur, k);
        // idx是离散化后的排名,d[idx]是原始值
        printf("%d\n", d[idx]);
    }

    return 0;
}

干净版

C++
#include<bits/stdc++.h>
using namespace std;
int a[5000086],d[5000086],root[5000086],sz = 0;
int n,m;
struct S{
	int ch[2];
	int cnt;
}tr[5000086];
int build(int l,int r){
	int temp = ++sz;
	if(l==r){
		tr[temp].cnt = 0;
		return temp;
	}
	int mid = (l+r)/2;
	tr[temp].ch[0] = build(l,mid);
	tr[temp].ch[1] = build(mid+1,r);
	tr[temp].cnt = 0;
	return temp;
}
int update(int x,int l,int r,int id){
	int temp = ++sz;
	tr[temp] = tr[x];
	if(l==r){
		tr[temp].cnt++;
		return temp;
	}
	int mid = (l+r)/2;
	if(id<=mid)
		tr[temp].ch[0] = update(tr[x].ch[0],l,mid,id);
	else
		tr[temp].ch[1] = update(tr[x].ch[1],mid+1,r,id);
	tr[temp].cnt = tr[tr[temp].ch[1]].cnt+tr[tr[temp].ch[0]].cnt;
	return temp;
}
int query(int u,int v,int l,int r,int k){
	if(l==r) return l;
	int mid = (l+r)/2;
	int lsum = tr[tr[v].ch[0]].cnt-tr[tr[u].ch[0]].cnt;
	if(k<=lsum)
		return query(tr[u].ch[0],tr[v].ch[0],l,mid,k);
	else
		return query(tr[u].ch[1],tr[v].ch[1],mid+1,r,k-lsum);
}
int main(){
	cin>>n>>m;
	for(int i = 1;i<=n;i++)
		cin>>a[i],d[i] = a[i];
	sort(d+1,d+n+1);
	int cur = unique(d+1,d+n+1)-d-1;
	for(int i = 1;i<=n;i++)
		a[i] = lower_bound(d+1,d+cur+1,a[i])-d;
	root[0] = build(1,cur);
	for(int i = 1;i<=n;i++)
		root[i] = update(root[i-1],1,cur,a[i]);
	//for(int i = 1;i<=n;i++)
	//	printf("%d ",tr[i].cnt);
	while(m--){
		int x,y,k;
		cin>>x>>y>>k;
		int idx = query(root[x-1],root[y],1,cur,k);
		printf("%d\n",d[idx]);
	}
}
原文