#include <cassert>
#include <cstdlib>
#include <iostream>
#include <utility>
using namespace std;

int random ()
{
	return (rand () << 15) ^ rand ();
}

struct Node;
typedef Node * PNode;
struct Node
{
	int x;
	int y;
	PNode left;
	PNode right;

	Node (int x_)
	{
		x = x_;
		y = random ();
		left = nullptr;
		right = nullptr;
	}
};

bool tfind (PNode t, int xf)
{
	if (t == nullptr) return false;
	if (t -> x == xf) return true;
	if (t -> x < xf) return tfind (t -> right, xf);
	else return tfind (t -> left, xf);
}

pair <PNode, PNode> tsplit (PNode t, int xs)
{
	if (t == nullptr) return {nullptr, nullptr};
	if (t -> x < xs)
	{
		auto temp = tsplit (t -> right, xs);
		t -> right = temp.first;
		return {t, temp.second};
	}
	else
	{
		auto temp = tsplit (t -> left, xs);
		t -> left = temp.second;
		return {temp.first, t};
	}
}

PNode tmerge (PNode l, PNode r)
{
	if (l == nullptr) return r;
	if (r == nullptr) return l;
	if (l -> y < r -> y)
	{
		r -> left = tmerge (l, r -> left);
		return r;
	}
	else
	{
		l -> right = tmerge (l -> right, r);
		return l;
	}
}

PNode tinsert (PNode t, int x)
{
	auto temp = tsplit (t, x);
	auto v = new Node (x);
	// half={temp.first | v} | temp.second
	auto half = tmerge (temp.first, v);
	return tmerge (half, temp.second);
}

void tdelete (PNode t)
{
	if (t == nullptr) return;
	tdelete (t -> left);
	tdelete (t -> right);
	delete t;
}

PNode terase (PNode t, int x)
{
	auto temp = tsplit (t, x);
	auto r = tsplit (temp.second, x + 1);
	// temp.first | r.first | r.second
	//     <x         =x        >x
	tdelete (r.first);
	return tmerge (temp.first, r.second);
}

int main ()
{
	PNode root = new Node (123);
	assert (root -> x == 123);
	assert ((*root).x == 123);
	assert (tfind (root, 123));
	assert (!tfind (root, 1));
	return 0;
}
