// cartesian tree with insert and find
#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 -> left | t | temp.first | temp.second
		t -> right = temp.first;
		return {t, temp.second};
	}
	else
	{ // t -> x >= xs
		auto temp = tsplit (t -> left, xs);
		// temp.first | temp.second | t | t -> right
		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);
	// temp.first | v | temp.second
	auto half = tmerge (temp.first, v);
	return tmerge (half, temp.second);
}

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

void toutput (PNode t)
{
	toutputrecur (t);
	cout << endl;
}

int main ()
{
	int n = 1000000;
	PNode root = nullptr;
	for (int i = 0; i < n; i++)
	{
		root = tinsert (root, (i * 3 + 1) % n);
	}
	toutput (root);
	for (int i = 0; i < n; i++)
	{
		cout << tfind (root, i * 2);
	}
	cout << endl;
	return 0;
}
