// array: cut and glue segments in O (log n)
#include <cstdlib>
#include <iostream>
#include <utility>
using namespace std;

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

struct Node;
typedef Node * PNode;
struct Node
{
	int value;
	int y;
	int size;
	PNode left;
	PNode right;

	Node (int value_)
	{
		value = value_;
		y = random ();
		size = 1;
		left = nullptr;
		right = nullptr;
	}

	void recalc ()
	{
//		size = 1 + left -> size + right -> size;
		size = 1;
		if (left != nullptr) size += left -> size;
		if (right != nullptr) size += right -> size;
	}
};

pair <PNode, PNode> tsplitK (PNode t, int k)
{
	if (t == nullptr) return {nullptr, nullptr};
	int leftSize = (t -> left == nullptr) ? 0 : t -> left -> size;
	if (k - leftSize - 1 >= 0) // where root will be?
//	if (k > leftSize)
	{
		auto temp = tsplitK (t -> right, k - leftSize - 1);
		// t -> left | t | temp.first | temp.second
		t -> right = temp.first;
		t -> recalc ();
		return {t, temp.second};
	}
	else
	{ // k <= leftSize
		auto temp = tsplitK (t -> left, k);
		// temp.first | temp.second | t | t -> right
		t -> left = temp.second;
		t -> recalc ();
		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);
		r -> recalc ();
		return r;
	}
	else
	{
		l -> right = tmerge (l -> right, r);
		l -> recalc ();
		return l;
	}
}

int kth (PNode & root, int k)
{
	auto temp = tsplitK (root, k);
	auto half = tsplitK (temp.second, 1);
	// temp.first:k  half.first:1  half.second:n-k-1
	int res = half.first -> value;
	temp.second = tmerge (half.first, half.second);
	root = tmerge (temp.first, temp.second);
	return res;
}

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

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

int main ()
{
	int n = 20;
	PNode root = nullptr;
	for (int i = 0; i < n; i++)
	{
		root = tmerge (new Node ((i * 3 + 1) % n), root);
		toutput (root);
	}
	for (int i = 1; i < n; i++)
	{
		auto temp = tsplitK (root, i);
		toutputrecur (temp.first);
		cout << " | ";
		toutput (temp.second);
		root = tmerge (temp.first, temp.second);
	}
	for (int i = 0; i < n; i++)
	{
		cout << kth (root, i) << " ";
	}
	cout << endl;

	{
		toutput (root);
		int lo = 5;
		int me = 11;
		int hi = 14;
		auto temp = tsplitK (root, me);
		auto one = tsplitK (temp.first, lo);
		auto two = tsplitK (temp.second, hi - me);
		//        temp.first          |          temp.second
		//  one.first  |  one.second  |  two.first  |  two.second
		//   lo - 0        me - lo        hi - me        n - hi
		auto glue1 = tmerge (one.first, two.first);
		auto glue2 = tmerge (one.second, two.second);
		root = tmerge (glue1, glue2);
		toutput (root);
	}

	return 0;
}
