关于重新封装stl实现set用的红黑树
  • 板块灌水区
  • 楼主Inv_day_in_R
  • 当前回复3
  • 已保存回复3
  • 发布时间2025/1/21 22:54
  • 上次更新2025/1/22 10:03:26
查看原帖
关于重新封装stl实现set用的红黑树
774202
Inv_day_in_R楼主2025/1/21 22:54

代码:

template<typename T>using _rbt=std::_Rb_tree<T,T,std::_Identity<T>,std::less<T>>;
template<typename V>struct _nd{V vf;int ss,cc;_nd():vf(){}_nd(const V&v):vf(v){}bool operator<(const _nd&__x)const{return vf<__x.vf;}};
template<typename T>struct Rb_tree:_rbt<_nd<T>>{
typedef _rbt<_nd<T>> _B;typedef typename _B::iterator _I;typedef typename _B::_Base_ptr _P;
#define f(x)	((x)->_M_parent)
#define L(x)	((x)==0?0:(x)->_M_left)
#define R(x)	((x)==0?0:(x)->_M_right)
#define V(x)	((x)==0?_n.vf:_I(x)->vf)
#define s(x)	((x)==0?_n.ss:_I(x)->ss)
#define c(x)	((x)==0?_n.cc:_I(x)->cc)
#define r()     (_B::_M_root())
private:
	_nd<T>_n;
	void _p(_P x){if(x!=0)s(x)=s(L(x))+s(R(x))+c(x);}
public:
	void insert(const T&v){auto[_f,_s]=_B::_M_insert_unique(v);_s?_f->cc=1:++_f->cc;auto x=_f._M_node;while(x!=r())_p(L(x)),_p(R(x)),x=f(x);_p(L(x)),_p(R(x)),_p(x),++_B::_M_impl._M_node_count;}
	void erase(const T&v){auto it=_B::find(v);--it->cc;auto x=it._M_node;while(x!=r())_p(x),x=f(x);_p(x),--_B::_M_impl._M_node_count;}
	const T&kth(int k){auto x=r();while(x)if(k<=s(L(x)))x=L(x);else{k-=s(L(x))+c(x);if(k<=0)return V(x);x=R(x);}return V(0);}
	int rank(const T&v){int res=1;auto x=r();while(x&&v!=V(x))v>=V(x)?res+=s(L(x))+c(x),x=R(x):x=L(x);return res+s(L(x));}
	const T&prev(const T&v){return kth(rank(v)-1);}
	const T&next(const T&v){return kth(rank(v+1));}
#undef f
#undef L
#undef R
#undef s
#undef c
#undef r
};

用法:

int main(){
    ios::sync_with_stdio(0),cin.tie(0);
    int n,m,a,last=0,ans=0,op,x;
    Rb_tree<int>tr;
    for(cin>>n>>m;n--;tr.insert(a))cin>>a;
    while(m--){
        cin>>op>>x;
        x^=last;
        if(op==1)tr.insert(x);
        if(op==2)tr.erase(x);
        if(op==3)ans^=last=tr.rank(x);
        if(op==4)ans^=last=tr.kth(x);
        if(op==5)ans^=last=tr.prev(x);
        if(op==6)ans^=last=tr.next(x);
    }
    cout<<ans;
}
2025/1/21 22:54
加载中...