#include<iostream>
#include<cstdlib>
using namespace std;
template<typename T>
class Node
{
public:
T data;
int fix;
int amount;
Node *left,*right;
Node()
{
left=right=NULL;
amount=0;
}
Node(T d)
{
data=d;
fix=rand();
amount=1;
left=right=NULL;
}
};
template<typename T>
class Treap
{
private:
Node<T> *root;
void l_rotate(Node<T> *&r)
{
Node<T> *p=r->right;
r->right=p->left;
p->left=r;
r=p;
}
void r_rotate(Node<T> *&r)
{
Node<T> *p=r->left;
r->left=p->right;
p->right=r;
r=p;
}
void _insert(Node<T> *&r,T d)
{
if(r==NULL)r=new Node<T>(d);
else if(r->data==d)r->amount++;
else if(r->data > d)
{
_insert(r->left,d);
if(r->fix > r->left->fix)r_rotate(r);
}
else if(r->data < d)
{
_insert(r->right,d);
if(r->fix > r->right->fix)l_rotate(r);
}
}
int _find(Node<T> *&r,T d)
{
if(r==NULL)return 0;
if(r->data == d)return r->amount;
else if(r->data > d)return _find(r->left,d);
else if(r->data < d)return _find(r->right,d);
}
void del(Node<T> *&r)
{
if(r->left==NULL&&r->right==NULL)
{
delete r;
r=NULL;
}
else if(r->left==NULL)
{
Node<T> *p=r;
r=r->right;
delete p;
}
else if(r->right==NULL)
{
Node<T> *p=r;
r=r->left;
delete p;
}
else
{
if(r->left->fix < r->right->fix)
{
r_rotate(r);
del(r->right);
}
else
{
l_rotate(r);
del(r->left);
}
}
}
bool _remove(Node<T> *&r,T d)
{
if(r==NULL)return false;
else if(r->data > d)return _remove(r->left,d);
else if(r->data < d)return _remove(r->right,d);
r->amount--;
if(r->amount == 0)del(r);
return true;
}
void _clear(Node<T> *r)
{
if(r==NULL)return;
_clear(r->left);
_clear(r->right);
delete r;
}
public:
Treap()
{
root=NULL;
}
~Treap()
{
_clear(root);
}
void insert(T data)
{
_insert(root,data);
}
int find(T data)
{
return _find(root,data);
}
bool remove(T data)
{
return _remove(root,data);
}
void clear()
{
_clear(root);
}
};