主席树求条
查看原帖
主席树求条
1013881
do_it_tomorrow楼主2024/5/7 20:21

有两个点 TLE 了,而且还死的很彻底。

#include<iostream>
using namespace std;
const int N=2e5+5;
int n,m,root[N],tot=1,cnt,dep[N],bef,p;
struct seg{
    int l,r,v,dep;
}s[N*50];
void build(int k,int l,int r){
    if(l==r){
        s[k].v=l;
        return;
    }
    int mid=(l+r)/2;
    s[k].l=++tot,s[k].r=++tot;
    build(s[k].l,l,mid),build(s[k].r,mid+1,r);
}
void change(int k,int l,int r,int pre,int x,int v){
    if(l==r){
        s[k].v=v;
        return;
    }
    int mid=(l+r)/2;s[k]=s[pre];
    if(x<=mid){
        s[k].l=++tot;
        change(s[k].l,l,mid,s[pre].l,x,v);
    }
    else{
        s[k].r=++tot;
        change(s[k].r,mid+1,r,s[pre].r,x,v);
    }
}
void change_dep(int k,int l,int r,int x){
    if(l==r){
        s[k].dep++;
        return ;
    }
    int mid=(l+r)/2;
    if(x<=mid){
        change_dep(s[k].l,l,mid,x);
    }
    else{
        change_dep(s[k].r,mid+1,r,x);
    }
}
pair<int,int> ask(int k,int l,int r,int x){
    if(l==r){
        return {s[k].v,s[k].dep};
    }
    int mid=(l+r)/2;
    if(x<=mid){
        return ask(s[k].l,l,mid,x);
    }
    else{
        return ask(s[k].r,mid+1,r,x);
    }
}
int fa(int x){
    return ask(root[cnt],1,n,x).first;
}
int find_root(int x){
    int dad=fa(x);
    if(dad==x){
        return x;
    }
    return find_root(dad);
}
void add(int x,int y){
    x=find_root(x),y=find_root(y);
    auto xx=ask(root[cnt],1,n,x),yy=ask(root[cnt],1,n,y);
    if(xx.second==yy.second){
        change_dep(root[cnt],1,n,x);
    }
    else if(xx.second<yy.second){
        swap(x,y);
    }
    root[++p]=++tot;
    change(tot,1,n,root[cnt],y,x);
    cnt=p;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr),cout.tie(nullptr),root[0]=1;
    cin>>n>>m;
    build(1,1,n);
    for(int i=1,op,x,y;i<=m;i++){
        cin>>op;
        if(op==1){
            cin>>x>>y;
            add(x,y);
        }
        if(op==2){
            cin>>cnt;
            root[++p]=root[cnt];
        }
        if(op==3){
            cin>>x>>y;
            int fx=find_root(x),fy=find_root(y);
            root[++p]=root[p];
            cout<<(fx==fy)<<'\n';
        }
    }
    return 0;
}
2024/5/7 20:21
加载中...