Splay

点击查看代码
struct Splay {
	int ch[M][2] , val[M] , size[M] , cnt[M] , fa[M] , T , root;
	inline void init(int p) {size[p] = cnt[p] = 1; ch[p][0] = ch[p][1] = 0;}
	inline bool getson(int p) {return ch[fa[p]][1] == p;}
	inline void pushup(int p) {size[p] =  size[ch[p][1]] + size[ch[p][0]] + cnt[p];}
	inline void rotate(int p) {
		int f = fa[p] , g = fa[fa[p]] , r = getson(p);
		if(f != root) ch[g][getson(f)] = p; fa[p] = g;
		fa[f] = p , ch[f][r] = ch[p][r ^ 1] , ch[p][r ^ 1] = f;
		if(ch[f][r]) fa[ch[f][r]] = f;
		pushup(f) , pushup(p);
	}	
	inline void splay(int p , const int to = 0) {
		for(; fa[p] != to; rotate(p)) if(fa[fa[p]] != to) rotate((getson(p) == getson(fa[p])) ? fa[p] : p);
		if(! to) root = p;	
	}
	inline int find(int x) {
		int p = root;
		while(val[p] != x) p = ch[p][x > val[p]];
		return p;	
	}
	inline int query_pre(int x) {
		int ans = 0 , p = root;
		while(p) {x > val[p] ? ans = p , p = ch[p][1] : p = ch[p][0];;}
		return ans;
	}
	inline int query_nxt(int x) {
		int ans = 0 , p = root;
		while(p) x < val[p] ? ans =  p , p = ch[p][0] : p = ch[p][1];
		return ans;
	}
	inline void insert(int x) {
		if(! root) {
			root = ++ T;
			init(T) , val[T] = x;
			return;
		}
		int p = root , u = 0;
		while(p && val[p] != x) u = p , p = ch[p][x > val[p]];
		if(p) ++ cnt[p];
		else {
			p = ++ T; if(u) ch[u][x > val[u]] = p;
			fa[p] = u , size[p] = cnt[p] = 1 , val[p] = x , ch[p][0] = ch[p][1] = 0;
		}
		splay(p);
	}
	inline void del(int x) {
		int pre	= query_pre(x) , nxt = query_nxt(x);
		splay(pre) , splay(nxt , pre);
		int p = ch[nxt][0];
		if(cnt[p] > 1) {
			cnt[p] --;
			return void(splay(p));
		}
		ch[p][0] = ch[p][1] = 0 , fa[p] = 0 , ch[nxt][0] = 0 , size[p] = cnt[p] = val[p] = 0 , pushup(nxt) , pushup(pre);
		
	}
	inline int query_rank(int x) {
		int p = find(x);
		splay(p);
		return size[ch[p][0]] + 1;
	}
	inline int query_kth(int k) {
		int p = root; 
		if(size[p] < k) return 0;
		while(p) {
			if(k > size[ch[p][0]] + cnt[p]) k -= size[ch[p][0]] + cnt[p] , p = ch[p][1];	
			else if(k <= size[ch[p][0]]) p = ch[p][0];
			else return p;
		}
	}
}s;
posted @ 2022-12-14 21:19  L3067545513  阅读(19)  评论(0编辑  收藏  举报