百年未打fhq_treap
查看原帖
百年未打fhq_treap
413301
Digital_Sunrise楼主2023/3/15 22:43

RT,MLE

#include <bits/stdc++.h>
using namespace std;
const int _ = 1e5 + 5;

inline int read()
{
	int f = 0,w = 1;
	char ch = getchar();
	while(ch < '0' or ch > '9'){if(ch == '-') w = -1;ch = getchar();}
	while(ch >= '0' and ch <= '9'){f = f * 10 + ch - '0';ch = getchar();}
	return f * w;
}

mt19937 rnd;


namespace fhq_treap
{
	struct node
	{
		int v;
		int lc,rc;
		int siz;
		int Priority; 
	}tree[_];
	int cnt;
	int Root;
	void init(){cnt = 0;Root = 0;}
	int creat(int v)
	{
		int k;
		k = ++cnt;
		tree[k].v = v;
		tree[k].lc = tree[k].rc = 0;
		tree[k].siz = 1;
		tree[k].Priority = rnd() % 19260817;
		return k;
	}
	void push_up(int k)
	{
		tree[k].siz = tree[tree[k].lc].siz + tree[tree[k].rc].siz + 1;
	}
	void split(int root,int pos,int &x,int &y)
	{
		if(!root)
		{
			x = y = 0;
			return;
		}
		if(tree[root].v <= pos)
		{
			x = root;
			split(tree[root].rc,pos,tree[root].rc,y);
		}
		else
		{
			y = root;
			split(tree[root].lc,pos,x,tree[root].lc); 
		}
		push_up(root);
	}
	int merge(int x,int y)
	{
		if(x * y == 0)
			return x + y;
		if(tree[x].Priority > tree[y].Priority)
		{
			tree[x].rc = merge(tree[x].rc,y);
			push_up(x);
			return x;
		}
		else
		{
			tree[y].lc = merge(x,tree[y].lc);
			push_up(y);
			return y;
		}
	}
	void insert(int v)
	{
		if(!Root)
		{
			Root = creat(v);
			return;
		}
		int x,y;
		split(Root,v - 1,x,y);
		Root = merge(merge(x,creat(v)),y);
	}
	void remove(int v)
	{
		int x,y,z;
		split(Root,v,x,z);
		split(Root,v - 1,x,y);
		if(y)
			y = merge(tree[y].lc,tree[y].rc);
		Root = merge(merge(x,y),z);
	}
	int rank(int v)
	{
		int x,y,rnk;
		split(Root,v - 1,x,y);
		rnk = tree[x].siz + 1;
		Root = merge(x,y);
		return rnk;
	}
	int xrank(int k)
	{
		int root = Root;
		while(1)
		{
			if(tree[tree[root].lc].siz + 1 == k)
				break;
			else if(tree[tree[root].lc].siz + 1 > k)
				root = tree[root].lc;
			else
			{
				k -= tree[tree[root].lc].siz + 1;
				root = tree[root].rc;
			}
		}
		return tree[root].v;
	}
	int prev(int k)
	{
		int x,y,root,ans;
//		root = Root;
		split(Root,k - 1,x,y);
		root = x;
		while(tree[root].rc) root = tree[root].rc;
		ans = tree[root].v;
		Root = merge(x,y);
		return ans;
	}
	int next(int k)
	{
		int x,y,root,ans;
		//this 
		split(Root,k,x,y);
		//is fucking wrong
		root = y;
		
		while(tree[root].lc) root = tree[root].lc;
		
		ans = tree[root].v;
		Root = merge(x,y);
		return ans;
	}
}

int m;

signed main()
{
	fhq_treap::init();
	m = read();
	while(m--)
	{
		int opt = read(),x = read();
		if(opt == 1) fhq_treap::insert(x);
		if(opt == 2) fhq_treap::remove(x);
		if(opt == 3) printf("%lld\n",fhq_treap::rank(x));
		if(opt == 4) printf("%lld\n",fhq_treap::xrank(x));
		if(opt == 5) printf("%lld\n",fhq_treap::prev(x));
		if(opt == 6) printf("%lld\n",fhq_treap::next(x));
	}
	return 0;
}
2023/3/15 22:43
加载中...