Persistence array can study notes

Recommended read: be persistent segment tree study notes


First, the definition:

It can be modified, and supports an array of the following two functions:

1. Modify the value at a certain location at a certain version of history

2. Access the value of a location on one version of history

Second, the principle:

If you have learned to be persistent segment tree (I'll be up when you do not see header), you will find an array of persistence may in fact have been included in the Chairman of the tree, the tree or by the chairman of realization

Contribution to modify operation is identical with the Chairman of the tree: by minimizing the space shared node

Query queries directly to the target version

Complete code:

#include<cstdio>
#include<algorithm>
#define maxn 200010
#define mid (l+r)/2
using namespace std;
struct node
{
    int val,l,r;
}tree[20000010];
int root[maxn<<5];
int a[maxn<<5],n,m,cc;
int cnt;
void build(int l,int r,int &rt)
{
    rt=++cnt;
    if(l==r)
    {
        tree[rt].val=a[l];
        return;
    }
    build(l,mid,tree[rt].l);
    build(mid+1,r,tree[rt].r);
}
void update(int num,int &rt,int l,int r)
{
    tree[++cnt]=tree[rt];
    rt=cnt;
    if(l==r)
    {
        tree[rt].val=cc;
        return;
    }
    if(num<=mid)
        update(num,tree[rt].l,l,mid);
    else
        update(num,tree[rt].r,mid+1,r);
}
int query(int rt,int l,int r,int num)
{
    if(l==r) return tree[rt].val;
    if(num<=mid) return query(tree[rt].l,l,mid,num);
    else return query(tree[rt].r,mid+1,r,num);
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    build(1,n,root[0]);
    for(int i=1;i<=m;i++)
    {
        int ty,id,bb;
        scanf("%d%d%d",&id,&ty,&bb);
        if(ty==1)
        {
            scanf("%d",&cc);
            root[i]=root[id];
            update(bb,root[i],1,n);
        }
        if(ty==2)
        {
            printf("%d\n",query(root[id],1,n,bb));
            root[i]=root[id];
        }
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/charlesss/p/11243617.html