// basic treap: split, merge, insert, +remove
#include <bits/stdc++.h>
using namespace std;

// random_device dev;
// mt19937 gen (dev ());
mt19937 gen (12345);

int random (int range)
{
	return uniform_int_distribution <int> (0, range) (gen);
}

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

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

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

void recurOutput (PNode v)
{
	if (v == nullptr)
	{
		return;
	}
	cout << "(";
	recurOutput (v -> left);
	cout << v -> x;
	recurOutput (v -> right);
	cout << ")";
}

void output (PNode v)
{
	recurOutput (v);
	cout << endl;
}

pair <PNode, PNode> tSplit (PNode v, int x)
{ // first answer: < x ; second answer: >= x
	if (v == nullptr)
	{
		return {nullptr, nullptr};
	}
	if (v -> x < x)
	{
		auto temp = tSplit (v -> right, x);
		v -> right = temp.first;
		return {v, temp.second};
	}
	else
	{
		auto temp = tSplit (v -> left, x);
		v -> left = temp.second;
		return {temp.first, v};
	}
}

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

PNode tInsert (PNode v, int x)
{
	auto temp = tSplit (v, x);
	auto u = new Node (x);
	auto half = tMerge (temp.first, u);
	return tMerge (half, temp.second);
}

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

PNode tRemove (PNode v, int x)
{
	auto one = tSplit (v, x);
	auto two = tSplit (one.second, x + 1);
	// one.first | two.first | two.second
	// TODO: delete two.first
	tDelete (two.first);
	return tMerge (one.first, two.second);
}

int main ()
{
	int const size = 1000000; // test for speed
	PNode root = nullptr;
	for (int i = 1; i <= size; i++)
	{
		root = tInsert (root, i);
//		output (root); // set size to 10 and then uncomment
	}
	for (int i = 1; i <= size; i++)
	{
//		cout << tFind (root, i); // set size to 10 and then uncomment
		tFind (root, i);
	}
	for (int i = 1; i <= size; i++)
	{
		root = tRemove (root, i);
		if (size - i == 3)
		{
			output (root);
		}
	}
	return 0;
}
