Luogu P3919 [] array may persist

An array is a single point of modification, a single underlying data structure of the query.
If you want to improve the array so that it can be persistent, then obviously we need to use other data structures to improve it.
For single point and a single point of inquiry modify two operations, it is easy to find persistent segment tree can also support this operation.
So, we can use persistence tree line to maintain a persistent array

#include<cstdio>
#define mid ((l+r)>>1)
using namespace std;
const int maxn=1e6+5;
int tot,tree[maxn*20],ls[maxn*20],a[maxn],rs[maxn*20],rt[maxn],n,m,v,flag,loc,val;
int build(int l,int r)
{
    int now=++tot;
    if (l==r)
    {
        tree[now]=a[l];
        return now;
    }
    ls[now]=build(l,mid);
    rs[now]=build(mid+1,r);
    return now;
}
int update(int root,int l,int r,int pnt,int val)
{
    int now=++tot;
    ls[now]=ls[root];
    rs[now]=rs[root];
    if (l==r&&l==pnt)
    {
        tree[now]=val;
        return now;
    }
    else
    {
        if (l==r) return now;
        if (pnt<=mid) ls[now]=update(ls[now],l,mid,pnt,val);
        if (pnt>mid) rs[now]=update(rs[now],mid+1,r,pnt,val);
        return now;
    }
}
int query(int root,int l,int r,int pnt)
{
    if (l==r&&l==pnt)
        return tree[root];
    int ret;
    if (pnt<=mid) ret=query(ls[root],l,mid,pnt);
    if (pnt>mid) ret=query(rs[root],mid+1,r,pnt);
    return ret;
}
int main()
{
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++) scanf("%d",&a[i]);
    rt[0]=build(1,n);
    for (int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&v,&flag,&loc);
        if (flag==1)
        {
            scanf("%d",&val);
            rt[i]=update(rt[v],1,n,loc,val);
        }
        else 
        {
            rt[i]=rt[v];
            printf("%d\n",query(rt[v],1,n,loc));
        }
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/notscience/p/11962219.html