Sustainable technology segment tree

template

A single point of modifying a single point of inquiry

#include <cstdio>
using namespace std;
const int maxn=2e7+5e6;
const int maxm=1e6+5;
int v[maxn],lson[maxn],rson[maxn];
int root[maxm]={1},a[maxm];//root[i]存i版本对应根节点(0号版本对应根为1)
int tot;
int build(int l,int r){
    int pos=++tot;
    if(l==r){
        v[pos]=a[l];
        return pos;
    }
    int mid=(l+r)>>1;
    lson[pos]=build(l,mid);
    rson[pos]=build(mid+1,r);
    return pos;
}
int update(int rt,int l,int r,int p,int w){
    int pos=++tot;
    if(l==r){
        v[pos]=w;
        return pos;
    }
    lson[pos]=lson[rt];
    rson[pos]=rson[rt];
    int mid=(l+r)>>1;
    if(p<=mid) lson[pos]=update(lson[rt],l,mid,p,w);
    else rson[pos]=update(rson[rt],mid+1,r,p,w);
    return pos;
}
int query(int rt,int l,int r,int p){
    if(l==r) return v[rt];
    int mid=(l+r)>>1;
    if(p<=mid) return query(lson[rt],l,mid,p);
    else return query(rson[rt],mid+1,r,p);
}
int main(){
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    build(1,n);
    int ed_,type,p_,w_;
    for(int i=1;i<=m;i++){
        scanf("%d%d",&ed_,&type);
        if(type==1){
            scanf("%d%d",&p_,&w_);
            root[i]=update(root[ed_],1,n,p_,w_);
        }
        if(type==2){
            scanf("%d",&p_);
            root[i]=root[ed_];
            printf("%d\n",query(root[ed_],1,n,p_) );
        }
    }
}

Interval k-small

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=2e5+5;
const int Log=40;
int num[maxn*Log],L[maxn*Log],R[maxn*Log];
int root[maxn],a[maxn],b[maxn];
int tot;
int build(int l,int r){
    int pos=++tot;
    if(l<r){
        int mid=(l+r)>>1;
        L[pos]=build(l,mid);
        R[pos]=build(mid+1,r);
    }
    return pos;
}
int update(int rt,int l,int r,int p){
    int pos=++tot;
    num[pos]=num[rt]+1;
    L[pos]=L[rt];
    R[pos]=R[rt];
    if(l<r){
        int mid=(l+r)>>1;
        if(p<=mid) L[pos]=update(L[rt],l,mid,p);
        else R[pos]=update(R[rt],mid+1,r,p);
    }
    return pos;
}
int query(int Old,int New,int l,int r,int k){
    if(l==r)return l;
    int mid=(l+r)>>1;
    int x=num[L[New]]-num[L[Old]];
    if(x>=k) return query(L[Old],L[New],l,mid,k);
    else return query(R[Old],R[New],mid+1,r,k-x);
}
int main(){
    int n,q;
    cin>>n>>q;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),b[i]=a[i];
    sort(b+1, b+1+n);
    int size = unique(b+1, b+1+n)-b-1;
    root[0] = build(1, size);
    for(int i=1;i<=n;i++)
        a[i] = lower_bound(b+1,b+1+size, a[i])-b;
    for(int i=1;i<=n;i++)
        root[i]=update(root[i-1],1,size,a[i]);
    while(q--){
        int x,y,z;scanf("%d%d%d",&x,&y,&z);
        int p=query(root[x-1],root[y],1,size,z);
        printf("%d\n",b[p]);
    }
}

Guess you like

Origin www.cnblogs.com/ucprer/p/11368517.html