模板 可持久化线段树
只支持单点修改区间查值的可持久化线段树
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 struct tree{ 6 int ls; 7 int rs; 8 int l,r; 9 int vls; 10 }tr[10000000]; 11 int size; 12 int line[1000000]; 13 int n,q; 14 int rt[1000000]; 15 int ts; 16 void pushup(int spc) 17 { 18 tr[spc].vls=max(tr[tr[spc].ls].vls,tr[tr[spc].rs].vls); 19 } 20 void build(int &spc,int l,int r) 21 { 22 if(!spc) 23 { 24 spc=++size; 25 } 26 tr[spc].l=l; 27 tr[spc].r=r; 28 if(l==r) 29 { 30 tr[spc].vls=line[l]; 31 return ; 32 } 33 int mid=(l+r)>>1; 34 build(tr[spc].ls,l,mid); 35 build(tr[spc].rs,mid+1,r); 36 pushup(spc); 37 } 38 void updt(int &spc,int lst,int plc,int vl) 39 { 40 spc=++size; 41 tr[spc].ls=tr[lst].ls; 42 tr[spc].rs=tr[lst].rs; 43 tr[spc].l=tr[lst].l; 44 tr[spc].r=tr[lst].r; 45 tr[spc].vls=tr[lst].vls; 46 if(tr[spc].l==tr[spc].r) 47 { 48 tr[spc].vls=vl; 49 return ; 50 } 51 if(((tr[spc].l+tr[spc].r)/2)>=plc) 52 { 53 updt(tr[spc].ls,tr[lst].ls,plc,vl); 54 }else{ 55 updt(tr[spc].rs,tr[lst].rs,plc,vl); 56 } 57 pushup(spc); 58 } 59 int ask(int l,int r,int spc) 60 { 61 if(tr[spc].l>r||tr[spc].r<l)return -1; 62 if(tr[spc].l>=l&&tr[spc].r<=r)return tr[spc].vls; 63 return max(ask(l,r,tr[spc].ls),ask(l,r,tr[spc].rs)); 64 } 65 int main() 66 { 67 scanf("%d%d",&n,&q); 68 for(int i=1;i<=n;i++) 69 { 70 scanf("%d",line+i); 71 } 72 build(rt[++ts],1,n); 73 while(q--) 74 { 75 int cmd,k,lp,rv; 76 scanf("%d%d%d%d",&cmd,&k,&lp,&rv); 77 if(cmd) 78 { 79 updt(rt[++ts],rt[k],lp,rv); 80 }else{ 81 printf("%d\n",ask(lp,rv,rt[k])); 82 } 83 } 84 return 0; 85 }