求助fhq-Treap
查看原帖
求助fhq-Treap
160839
Prean楼主2020/5/1 13:34

36分写挂了,后继出了一点儿问题,求助

Code:

#include<cstdlib>
#include<cstdio>
#include<ctime>
const int M=1e5+5;
class Treap
{
private:
	int s[M],val[M],rnd[M],chi[M][2];
	int cnt,root;
	int undate(int);
	int kth(int,int);
	int merge(int,int);
	void split(int,int,int&,int&);
public:
	int lower(int);
	int upper(int);
	void push(int);
	void pop(int);
	int find(int);
	int rank(int);
}BST;
int Treap::undate(int now)
{
	s[now]=s[chi[now][0]]+s[chi[now][1]]+1;
	return now;
}
int Treap::kth(int now,int rk)
{
	while(1)
	{
		if(rk==s[chi[now][0]]+1)return now;
		if(rk<=s[chi[now][0]])now=chi[now][0];
		else rk-=s[chi[now][0]]+1,now=chi[now][1];
	}
}
int Treap::merge(int x,int y)
{
	if(!x||!y)return x+y;
	if(rnd[x]<rnd[y])return chi[x][1]=merge(chi[x][1],y),undate(x);
	else return chi[y][0]=merge(x,chi[y][0]),undate(y);
}
void Treap::split(int now,int value,int&x,int&y)
{
	if(!now)return(void)(x=y=0);
	if(val[now]<=value)split(chi[x=now][1],value,chi[now][1],y);
	else split(chi[y=now][0],value,x,chi[now][0]);
	undate(now);
}
int Treap::lower(int value)
{
	int x,y;
	split(root,value-1,x,y);
	x=kth(x,s[x]);root=merge(x,y);
	return val[x];
}
int Treap::upper(int value)
{
	int x,y;
	split(root,value,x,y);
	y=kth(y,1);root=merge(x,y);
	return val[y];
}
void Treap::push(int value)
{
	int x,y;
	split(root,value,x,y);++cnt;
	s[cnt]=1;val[cnt]=value;rnd[cnt]=rand();
	root=merge(merge(x,cnt),y);
}
void Treap::pop(int value)
{
	int x,y,z;
	split(root,value,x,z);
	split(x,value-1,x,y);
	root=merge(merge(x,merge(chi[y][0],chi[y][1])),z);
}
int Treap::find(int value)
{
	int x,y,ans;
	split(root,value-1,x,y);
	ans=s[x]+1;root=merge(x,y);
	return ans;
}
int Treap::rank(int rk)
{
	return val[kth(root,rk)];
}
signed main(void)
{
	srand((unsigned)time(NULL));
	int n;scanf("%d",&n);
	while(n--)
	{
		int opt,k;scanf("%d%d",&opt,&k);
		if(opt==1)BST.push(k);
		if(opt==2)BST.pop(k);
		if(opt==3)printf("%d\n",BST.find(k));
		if(opt==4)printf("%d\n",BST.rank(k));
		if(opt==5)printf("%d\n",BST.lower(k));
		if(opt==6)printf("%d\n",BST.upper(k));
	}
}
2020/5/1 13:34
加载中...