【Luogu3919】可持久化数组(主席树)

题面戳我

题解

放一个板子在这里
用主席树维护一下每个版本就可以啦。。。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
#define MAX 1000100
inline int read()
{
    register int x=0,t=1;
    register char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
    if(ch=='-'){t=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
    return x*t;
}
int root[MAX],a[MAX],N,M;
struct Node
{
    int l,r;
    int ls,rs;
    int val;
}t[MAX*20];
int sum=0,tot=1;
void Build(int now,int l,int r)
{
    t[now].l=l;t[now].r=r;
    if(l==r){t[now].val=a[l];return;}
    t[now].ls=++tot;
    int mid=(l+r)>>1;
    Build(tot,l,mid);
    t[now].rs=++tot;
    Build(tot,mid+1,r);
}
void AddNode(int now,int New,int k,int w)
{
    t[New]=t[now];
    if(t[now].l==t[now].r)
    {
            t[New].val=w;
        return;
    }
    int mid=(t[now].l+t[now].r)>>1;
    if(k<=mid)
    {
        t[New].ls=++tot;
        AddNode(t[now].ls,tot,k,w);
    }
    else
    {
        t[New].rs=++tot;
        AddNode(t[now].rs,tot,k,w);
    }
}
void Query(int now,int k)
{
    if(t[now].l==t[now].r)
    {
        printf("%d
",t[now].val);
        return;
    }
    int mid=(t[now].l+t[now].r)>>1;
    if(k<=mid)Query(t[now].ls,k);
    else Query(t[now].rs,k);
}
int main()
{
    N=read();M=read();
    for(int i=1;i<=N;++i)a[i]=read();
    Build(1,1,N);
    root[0]=1;
    while(M--)
    {
        int v=read(),opt=read();
        if(opt==1)
        {
            int vv=read(),ww=read();
            AddNode(root[v],root[++sum]=++tot,vv,ww);
        }
        else
        {
            int vv=read();
            Query(root[v],vv);
            root[++sum]=root[v];
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/cjyyb/p/7622132.html