当前位置:网站首页>可持久化线段树
可持久化线段树
2022-08-01 04:51:00 【glorious_dream】
为什么叫可持久化线段树(主席树) :发明人是黄嘉泰 (hjt) 想到了谁?
何为可持久化线段树?
考虑这样一道题目
也就是说,在线段树的基础上,需要支持回退到某一个版本。
首先,最暴力的方式,肯定是每一个版本都建一棵线段树,但空间肯定爆炸。
所以考虑优化,让每一个版本修改的数量尽量变少。
在修改版本中,只需要修改logn个节点,其余节点和原来的线段树共用,这样就可以省掉很大一部分空间。注意实现的时候要记录下来每一个版本的根节点的编号。
其余的各种操作和线段树类似。
#include<bits/stdc++.h>
#define re register
#define rep(a,b,c) for(re int a(b) ; a<=c ; ++a)
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch == '-') f=-1 ; ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48) ; ch=getchar();}
return x*f;
}
const int M = 2e7+5e6;
const int N = 1e6+10;
int a[N],root[N];
int top;
struct tree{
int l,r,val;
}t[M];
int n,m;
struct qwq{
inline int clone(int node){ //新建一个版本,要把原版本的信息复制给新的版本
t[++top] = t[node];
return top;
}
inline int build(int node,int l,int r){
node = ++top;
if(l == r){
t[node].val = a[l]; //建树
return node;
}
int mid = (l+r)>>1;
t[node].l = build(t[node].l,l,mid);
t[node].r = build(t[node].r,mid+1,r);
return node; //返回根节点的编号
}
inline int modify(int node,int l,int r,int x,int y){
node = clone(node); //新的节点编号
if(l == r) t[node].val = y;
else{
int mid = (l+r)>>1;
if(x<=mid) t[node].l = modify(t[node].l,l,mid,x,y);
else t[node].r = modify(t[node].r,mid+1,r,x,y); //与线段树的操作类似
}
return node;
}
inline int query(int node,int l,int r,int x){
if(l == r) return t[node].val;
else{
int mid = (l+r)>>1;
if(x<=mid) return query(t[node].l,l,mid,x);
else return query(t[node].r,mid+1,r,x);
}
}
}pst;
signed main(){
scanf("%d%d",&n,&m);
rep(i,1,n) a[i] = read();
root[0] = pst.build(0,1,n); //第0个版本的根节点的编号
rep(i,1,m){
int rt,op,x;
scanf("%d%d%d",&rt,&op,&x);
if(op == 1){
int y=read();
root[i] = pst.modify(root[rt],1,n,x,y); //记录下来每一个版本根节点的编号
}
else{
printf("%d\n",pst.query(root[rt],1,n,x));
root[i] = root[rt]; //询问也算一次操作
}
}
return 0;
}
边栏推荐
猜你喜欢
(Codeforce 757) E. Bash Plays with Functions
leetcode:126. Word Solitaire II
scheduleWithFixedDelay和scheduleAtFixedRate的区别
博客系统(完整版)
Article summary: the basic model of VPN and business types
Typescript20 - interface
Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
万字逐行解析与实现Transformer,并进行德译英实战(一)
API设计笔记:pimpl技巧
typescript28 - value of enumeration type and data enumeration
随机推荐
风险策略调优中重要的三步分析法
leetcode:126. Word Solitaire II
雪糕和轮胎
Pyspark Machine Learning: Vectors and Common Operations
typescript22-接口继承
在沈自所的半年总结
lambda
律师解读 | 枪炮还是玫瑰?从大厂之争谈元宇宙互操作性
开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
Dry goods!How to Construct SRv6-TE Performance Test Environment Using Instrumentation
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
万字逐行解析与实现Transformer,并进行德译英实战(二)
认真对待每一个时刻
干货!如何使用仪表构造SRv6-TE性能测试环境
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
LeetCode 27. 移除元素
PMP子过程定义总结
Pyspark机器学习:向量及其常用操作
y83. Chapter 4 Prometheus Factory Monitoring System and Actual Combat -- Advanced Prometheus Alarm Mechanism (14)
UE4 模型OnClick事件不生效的两种原因