跳到正文

个人记录

FHQ Treap

ysy11约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年5月29日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 4 分钟

版本

  1. v1当前
C++
namespace FHQTreap
{
	struct node
	{
		ll s[2],ky,cnt,siz,pri;
	}t[MAXN];
	ll cnt,root;
	ll newnode(ll x)
	{
		t[++cnt]={{0,0},x,1,1,rand()};
		return cnt;
	}
	void pushup(ll u)
	{
		ll ls=t[u].s[0],rs=t[u].s[1];
		t[u].siz=t[ls].siz+t[rs].siz;
		t[u].siz+=t[u].cnt;
	}
	void split(ll u,ll x,ll &l,ll &r)
	{
		if(!u)
		{
			l=r=0;
			return ;
		}
		if(t[u].ky<=x)
		{
			l=u;
			split(t[u].s[1],x,t[u].s[1],r);
		}
		else
		{
			r=u;
			split(t[u].s[0],x,l,t[u].s[0]);
		}
		pushup(u);
	}
	ll merge(ll l,ll r)
	{
		if(!l||!r)return l+r;
		if(t[l].pri>t[r].pri)
		{
			t[l].s[1]=merge(t[l].s[1],r);
			pushup(l);
			return l;
		}
		t[r].s[0]=merge(l,t[r].s[0]);
		pushup(r);
		return r;
	}
	void add(ll x)
	{
		ll l,r,u;
		split(root,x,l,r);
		split(l,x-1,l,u);
		if(t[u].ky==x)
		{
			t[u].cnt++;
			t[u].siz++;
			root=merge(merge(l,u),r);
			return ;
		}
		root=merge(merge(l,newnode(x)),r);
	}
	void del(ll x)
	{
		ll l,r,u;
		split(root,x,l,r);
		split(l,x-1,l,u);
		if(t[u].cnt>1)
		{
			t[u].cnt--;
			t[u].siz--;
			root=merge(merge(l,u),r);
			return ;
		}
		root=merge(l,r);
	}
	ll get(ll x,bool y)
	{
		ll l,r,u;
		if(!y)
		{
			split(root,x-1,l,r);
			u=l;
		}
		else
		{
			split(root,x,l,r);
			u=r;
		}
		while(t[u].s[y^1])
		{
			u=t[u].s[y^1];
		}
		root=merge(l,r);
		return u;
	}
	ll rk(ll x)
	{
		ll l,r;
		split(root,x-1,l,r);
		ll u=t[l].siz;
		root=merge(l,r);
		return u;
	}
	ll kth(ll x)
	{
		x++;
		ll y=root;
		if(t[y].siz<x)return 0;
		while(1)
		{
			ll ls=t[y].s[0];
			if(t[ls].siz>=x)
			{
				y=ls;
				continue;
			}
			x-=t[ls].siz;
			if(t[y].cnt>=x)
			{
				return y;
				continue;
			}
			x-=t[y].cnt;
			y=t[y].s[1];
		}
	}
	void ask(ll x)
	{
		if(t[x].s[0])ask(t[x].s[0]);
		cout<<t[x].ky<<" ";
		if(t[x].s[1])ask(t[x].s[1]);
	}
}using namespace FHQTreap;
原文