【模板】可持久化数组(可持久化线段树/平衡树)

题目描述 题目

(指针版主席树)

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cstdlib>
 5 #include<algorithm>
 6 using namespace std;
 7 const int N=1000010;
 8 int n,m,a[N],cnt;
 9 struct node{node* ch[2];int v;};node* T[N];
10 
11 void build(node* &o,int l,int r)
12 {
13     if(l > r) return ;
14     o=new node();
15     if(l == r) {o->v=a[l];return ;}
16     int mid=(l+r)>>1;
17     build(o->ch[0],l,mid);
18     build(o->ch[1],mid+1,r);
19 }
20 
21 void updata(node* pre,node* &o,int l,int r,int x,int v)
22 {
23     if(l > r) return ;
24     o=new node();o->ch[0]=pre->ch[0];o->ch[1]=pre->ch[1];
25     if(l == r) {o->v=v;return ;}
26     int mid=(l+r)>>1;
27     if(x <= mid) updata(pre->ch[0],o->ch[0],l,mid,x,v);
28     else updata(pre->ch[1],o->ch[1],mid+1,r,x,v);
29 }
30 
31 int query(node* o,int l,int r,int x)
32 {
33     if(l > r) return 0;
34     if(l == r) return o->v;
35     int mid=(l+r)>>1;
36     if(x <= mid) return query(o->ch[0],l,mid,x);
37     return query(o->ch[1],mid+1,r,x);
38 }
39 
40 int read(){
41     int out=0,f=1;char c=getchar();while(c > '9' || c < '0') {if(c == '-') f=-1;c=getchar();}
42     while(c <= '9' && c >= '0') {out=(out<<1)+(out<<3)+c-'0';c=getchar();}return out*f;
43 }
44 
45 void solve()
46 {
47     n=read(),m=read();
48     for(int i=1;i<=n;i++) a[i]=read();
49     build(T[0],1,n);
50     for(int i=1;i<=m;i++)
51     {
52         int x=read(),opt=read(),loc=read();
53         if(opt == 1)
54         {
55             int y=read();
56             updata(T[x],T[++cnt],1,n,loc,y);
57         }
58         if(opt == 2) {T[++cnt]=T[x];printf("%d\n",query(T[x],1,n,loc));}
59     }
60 }
61 
62 int main()
63 {
64     solve();
65     return 0;
66 }

 

转载于:https://www.cnblogs.com/zerolt/p/9260899.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值