【模板】可持久化数组

指路例题

 1 /*
 2 5 10
 3 59 46 14 87 41
 4 0 2 1
 5 0 1 1 14
 6 0 1 1 57
 7 0 1 1 88
 8 4 2 4
 9 0 2 5
10 0 2 4
11 4 2 1
12 2 2 2
13 1 1 5 91
14 */
15 #include<iostream>
16 #include<cstdio>
17 #include<cstring>
18 using namespace std;
19 int cnt=0,a[50000001],root[50000001];
20 struct node{
21     int val,l,r;
22 }tree[50000001];
23 int build(int x,int l,int r){
24     cnt++;
25     x=cnt;
26     if(l==r){
27         tree[x].val=a[l];
28         return x;
29     }
30     int mid=(l+r)/2;
31     tree[x].l=build(0,l,mid);
32     tree[x].r=build(0,mid+1,r);
33     return x;
34 }
35 int New(int x){
36     tree[++cnt]=tree[x];
37     return cnt;
38 }
39 int turn(int x,int pos,int turn_val,int l,int r){
40     x=New(x);
41     if(l==r){
42         tree[x].val=turn_val;
43         return x;
44     }
45     int mid=(l+r)/2;
46     if(pos<=mid) tree[x].l=turn(tree[x].l,pos,turn_val,l,mid);
47     else tree[x].r=turn(tree[x].r,pos,turn_val,mid+1,r);
48     return x;
49 }
50 int search(int x,int pos,int l,int r){
51     if(l==r) return tree[x].val;
52     int mid=(l+r)/2;
53     if(pos<=mid) return search(tree[x].l,pos,l,mid);
54     else return search(tree[x].r,pos,mid+1,r);
55 }
56 int main(){
57     int n,m;
58     scanf("%d%d",&n,&m);
59     for(int i=1;i<=n;i++) scanf("%d",&a[i]); 
60     root[0]=build(0,1,n);
61     for(int i=1;i<=m;i++){
62         int edition,type,Pos;
63         scanf("%d%d%d",&edition,&type,&Pos);
64         if(type==1){
65             int value;
66             scanf("%d",&value);
67             root[i]=turn(root[edition],Pos,value,1,n);
68             continue;    
69         }
70         int ans=search(root[edition],Pos,1,n);
71         printf("%d\n",ans);
72         root[i]=root[edition];
73     }
74     return 0;
75 }

 

posted @ 2021-01-29 09:19  latent_Lin  阅读(89)  评论(1)    收藏  举报