Problem:
Treap A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct.  binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$  heap property. If $v$ is a child of $u$, then $v.priority < u.priority$  This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure.  Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. The rotate operations can be implemented as follows.    rightRotate(Node t)
    Node s = t.left
    t.left = s.right
    s.right = t
    return s // the new root of subtree    leftRotate(Node t)
    Node s = t.right
    t.right = s.left
    s.left = t
    return s // the new root of subtree    The following figure shows processes of the rotate operations after the insert operation to maintain the properties. The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority)            // search the corresponding place recursively
    if t == NIL
        return Node(key, priority)               // create a new node when you reach a leaf
    if key == t.key
        return t                                 // ignore duplicated keys

    if key < t.key                               // move to the left child
        t.left = insert(t.left, key, priority)   // update the pointer to the left child
        if t.priority < t.left.priority          // rotate right if the left child has higher priority
            t = rightRotate(t)
    else                                         // move to the right child
        t.right = insert(t.right, key, priority) // update the pointer to the right child
        if t.priority < t.right.priority         // rotate left if the right child has higher priority
            t = leftRotate(t)

  return t  Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key)                        // seach the target recursively
    if t == NIL
        return NIL
    if key < t.key                             // search the target recursively
        t.left = delete(t.left, key)
    else if key > t.key
        t.right = delete(t.right, key)
    else
        return _delete(t, key)
    return t

_delete(Node t, int key)                       // if t is the target node
    if t.left == NIL && t.right == NIL         // if t is a leaf
        return NIL
    else if t.left == NIL                      // if t has only the right child, then perform left rotate
        t = leftRotate(t)
    else if t.right == NIL                     // if t has only the left child, then perform right rotate
        t = rightRotate(t)
    else                                       // if t has both the left and right child
        if t.left.priority > t.right.priority  // pull up the child with higher priority
            t = rightRotate(t)
        else
            t = leftRotate(t)
    return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm.  insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$.  find ($k$): Report whether $T$ has a node containing $k$.  delete ($k$): Delete a node containing $k$.  print (): Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.  Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $k$ or print are given. Output For each find($k$) operation, print " yes " if $T$ has a node containing $k$, " no " if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key . Constraints  The number of operations $ \leq 200,000$  $0 \leq k, p  \leq 2,000,000,000$  The height of the binary tree does not exceed 50 if you employ the above algorithm  The keys in the binary search tree are all different.  The priorities in the binary search tree are all different.  The size of output $\leq 10$ MB  Sample Input 1 16
insert 35 99
insert 3 80
insert 1 53
insert 14 25
insert 80 76
insert 42 3
insert 86 47
insert 21 12
insert 7 10
insert 6 90
print
find 21
find 22
delete 35
delete 99
print Sample Output 1 1 3 6 7 14 21 35 42 80 86
 35 6 3 1 14 7 21 80 42 86
yes
no
 1 3 6 7 14 21 42 80 86
 6 3 1 80 14 7 21 42 86 Reference  Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.  Randomized Search Trees, R. Seidel, C.R. Aragon.

Solution (Python):
import sys, os
from io import StringIO

class BinaryTree:

    class Node:
        def __init__(self, key, priority = 0):
            self.key = key
            self.left = None
            self.right = None
            self.parent = None
            self.priority = priority

    def __init__(self):
        self.root = None
        self.output = StringIO()


    def insert(self, key, priority):
        self.root = self._insert_main(key, self.root, priority)

    def _insert_main(self, key, node, priority):
        if node is None:
            return self.Node(key, priority)
        else:
            if key > node.key:
                node.right = self._insert_main(key, node.right, priority)
                if node.priority < node.right.priority:
                    node = self.rotate_left(node)
            else:
                node.left = self._insert_main(key, node.left, priority)
                if node.priority < node.left.priority:
                    node = self.rotate_right(node)
            return node


    def rotate_right(self, base):
        left_node = base.left
        
        
        base.left = left_node.right
        left_node.right = base
        return left_node

    def rotate_left(self, base):
        right_node = base.right
        
        
        
        base.right = right_node.left
        right_node.left = base
        return right_node

    def ini_print_inorder(self):
        self.output = StringIO()
        self._print_inorder(self.root)
        return self.output.getvalue()

    def ini_print_preorder(self):
        self.output = StringIO()
        self._print_preorder(self.root)
        return self.output.getvalue()

    def ini_print_postorder(self):
        self.output = StringIO()
        self._print_postorder(self.root)
        return self.output.getvalue()

    def _print_inorder(self, node):
        if node is not None:
            self._print_inorder(node.left)
            print(node.key, end = " ", file = self.output)
            self._print_inorder(node.right)

    def _print_preorder(self, node):
        if node is not None:
            print(node.key, end = " ", file = self.output)
            self._print_preorder(node.left)
            self._print_preorder(node.right)

    def _print_postorder(self, node):
        if node is not None:
            self._print_preorder(node.left)
            self._print_preorder(node.right)
            print(node.key, end = " ", file = self.output)

    def test_insert(self, keys):
        for k in keys:
            self.insert(k)

    def ini_find(self, key):
        print(self.find(key))

    def find(self, key):
        root = self.root
        while root is not None:
            if key == root.key:
                return "yes"
            elif key < root.key:
                root = root.left
            else:
                root = root.right
        return "no"

    def get_successor(self, node):
        parent = node
        while True:
            node = node.left
            if node is None:
                return parent, parent.parent
            parent = node
        return None

    def delete(self, key):
        self.root = self._delete_main(key, self.root)

    def _delete_main(self, key, node):
        if node:
            if key > node.key:
                node.right = self._delete_main(key, node.right)
            elif key < node.key:
                node.left = self._delete_main(key, node.left)
            else:
                if node.right is None and node.left is None:
                    return None
                elif node.right is None:
                    node = self.rotate_right(node)
                elif node.left is None:
                    node = self.rotate_left(node)
                else:
                    if node.left.priority > node.right.priority:
                        node = self.rotate_right(node)
                    else:
                        node = self.rotate_left(node)
                node = self._delete_main(key, node)
        return node

    def _search_min(self, node):
        if node.left is None:
            return node.key
        return self._search_min(node.left)

    def _delete_min(self, node):
        if node.left is None:
            return node.right
        node.left = self._delete_min(node.left)
        return node



b = BinaryTree()
length = int(input())
for _ in range(length):
    comm = input()
    if comm[0] == "i":
        com, num, pri = comm.split(" ")
        b.insert(int(num), int(pri))
    elif comm[0] == "p":
        print(" ", end = "")
        print(b.ini_print_inorder()[:-1])
        print(" ", end = "")
        print(b.ini_print_preorder()[:-1])

    elif comm[0] == "f":
        com, num = comm.split(" ")
        b.ini_find(int(num))
    else:
        com, num = comm.split(" ")
        b.delete(int(num))

Solution (Python):
class Node:
    def __init__(self,key,priority):
        self.key=key
        self.parent=None
        self.left=None
        self.right=None
        self.priority=priority
        self.rightflag=-1


def insert(root,node):
    if(root.key <= node.key):
        if(root.right is None):
            root.right=node
            node.parent=root
            node.rightflag=1
        else:
            insert(root.right,node)
    
    else:
        if(root.left is None):
            root.left=node
            node.parent=root
            node.rightflag=0
        else:
            insert(root.left,node)


def find(root,key):
    if(root.key==key):
        return root

    elif(root.key < key):
        if(root.right is not None):
            return find(root.right,key)
        else:
            return None

    else:
        if(root.left is not None):
            return find(root.left,key)
        else:
            return None







                   
            
        



    

def Preorder(root,order):
    order.append(root.key)
    if(root.left is not None):
        Preorder(root.left,order)
    
    if(root.right is not None):
        Preorder(root.right,order)




def Inorder(root,order):
    if(root.left is not None):
        Inorder(root.left,order)
    
    order.append(root.key)


    if(root.right is not None):
        Inorder(root.right,order)



def right_rotate(node,Root):
    if(node.parent==None):
        return 0
    
    node.parent.left=node.right
    if(node.right is not None):
        node.right.parent=node.parent
        node.right.rightflag=0
    

    if(node.parent.parent is not None):
        tmp_parent=node.parent.parent
        node.parent.parent=node
        node.rightflag=node.parent.rightflag
        node.parent.rightflag=1
        node.right=node.parent
        node.parent=tmp_parent
        if(node.rightflag):
            tmp_parent.right=node
        else:
            tmp_parent.left=node
    else:
        node.parent.parent=node
        node.rightflag=-1
        node.parent.rightflag=1
        node.right=node.parent
        node.parent=None
        Root[0]=node
    
    return 1


def left_rotate(node,Root):
    if(node.parent==None):
        return 0
    
    node.parent.right=node.left
    if(node.left is not None):
        node.left.parent=node.parent
        node.left.rightflag=1
    

    if(node.parent.parent is not None):
        tmp_parent=node.parent.parent
        node.parent.parent=node
        node.rightflag=node.parent.rightflag
        node.parent.rightflag=0
        node.left=node.parent
        node.parent=tmp_parent
        if(node.rightflag):
            tmp_parent.right=node
        else:
            tmp_parent.left=node
    else:
        node.parent.parent=node
        node.rightflag=-1
        node.parent.rightflag=0
        node.left=node.parent
        node.parent=None
        Root[0]=node
    
    return 1


def delete(Root,key):
    if(Root[0] is None):
        pass
    else:
        target=find(Root[0],key)
        if(target is None):
            pass
        else:
            while( target.left is not None or target.right is not None):
                if(target.left is not None and target.right is not None):
                    if(target.left.priority <= target.right.priority):
                        left_rotate(target.right,Root)
                    else:
                        right_rotate(target.left,Root)
                
                
                elif(target.left is not None):
                    right_rotate(target.left,Root)
                elif(target.right is not None):
                    left_rotate(target.right,Root)        
            
            if(target.rightflag==1):
                target.parent.right=None
            elif(target.rightflag==0):
                target.parent.left=None
            else:
                Root[0]=None


n=int(input())
root=None

for loop in range(n):
    ope=input().split()

    if(ope[0]=="insert"):
        tmp_node=Node(int(ope[1]),int(ope[2]))
        try:
            insert(root,tmp_node)
            Root=[root]
            while(tmp_node.parent.priority <tmp_node.priority):
                if(tmp_node.rightflag):
                    left_rotate(tmp_node,Root)
                else:
                    right_rotate(tmp_node,Root)
            root=Root[0]
        except:
            root=tmp_node

    elif(ope[0]=="rotate"):
        if(root is not None):
            target=find(root,int(ope[1]))
            if(target is not None):
                Root=[root]
                left_rotate(target,Root)
                root=Root[0]
    
    elif(ope[0]=="find"):
        try:
            if(find(root,int(ope[1])) is not None):
                print("yes")

            else:
                print("no")
        except:
            print("no")
    
    elif(ope[0]=="delete"):
        Root=[root]
        delete(Root,int(ope[1]))
        root=Root[0]

    else:
        in_order=[]
        p_order=[]

        
        Inorder(root,in_order)
        Preorder(root,p_order)

        for x in in_order:
            print(f" {x}",end="")
            
        print()
        for x in p_order:
            print(f" {x}",end="")
        print()

Solution (Python):
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write

def rotate(nd, d):
    c = nd[d]
    if d:
        nd[1] = c[0]
        c[0] = nd
    else:
        nd[0] = c[1]
        c[1] = nd
    return c


root = None
def insert(val, pri):
    global root
    st = []
    dr = []
    x = root
    while x:
        st.append(x)
        if x[2] == val:
            return
        d = (x[2] < val)
        dr.append(d)
        x = x[d]
    nd = [None, None, val, pri]
    while st:
        x = st.pop(); d = dr.pop()
        c = x[d] = nd
        if x[3] >= c[3]:
            break
        rotate(x, d)
    else:
        root = nd

def __delete(nd):
    st = []; dr = []
    while nd[0] or nd[1]:
        l = nd[0]; r = nd[1]
        d = (l[3] <= r[3]) if l and r else (l is None)
        st.append(rotate(nd, d))
        dr.append(d ^ 1)
    nd = x = None
    while st:
        nd = x; x = st.pop(); d = dr.pop()
        x[d] = nd
    return x

def delete(val):
    global root
    x = root

    y = None
    while x:
        if val == x[2]:
            break
        y = x; d = (x[2] < val)
        x = x[d]
    else:
        return

    if y:
        y[d] = __delete(x)
    else:
        root = __delete(x)

def find(val):
    x = root
    while x:
        if val == x[2]:
            return 1
        x = x[x[2] < val]
    return 0

def debug():
    s0 = [""]
    s1 = [""]

    def dfs(nd):
        v = str(nd[2])
        s0.append(v)
        if nd[0]:
            dfs(nd[0])
        s1.append(v)
        if nd[1]:
            dfs(nd[1])
    dfs(root)
    return " ".join(s1), " ".join(s0)


M = int(readline())
ans = []
for m in range(M):
    cmd, *V, = readline().split()
    if cmd == "print":
        ans.extend(debug())
    elif cmd == "find":
        ans.append("yes" if find(int(V[0])) else "no")
    elif cmd == "delete":
        delete(int(V[0]))
    else:
        val, pri = map(int, V)
        insert(val, pri)
write("\n".join(ans))
write("\n")

Solution (Python):
class Node:
    def __init__(self, key, priority):
        self.key = key
        self.pri = priority
        self.parent = None
        self.left = None
        self.right = None
        
    def insert(self, z):
        if z.key < self.key:
            if self.left:
                self.left.insert(z)
            else:
                self.left = z
                z.parent = self
            if self.pri < self.left.pri:
                self.rightR()
        elif self.key < z.key:
            if self.right:
                self.right.insert(z)
            else:
                self.right = z
                z.parent = self
            if self.pri < self.right.pri:
                self.leftR()
    
    def find(self, key):
        if self.key == key:
            return True
        elif not self.left and not self.right:
            return False
        else:
            if key < self.key:
                return self.left.find(key)
            else:
                return self.right.find(key)
            
    def delete(self, key):
        if key < self.key:
            self.left.delete(key)
        elif key > self.key:
            self.right.delete(key)
        else:
            self._delete()
    
    def _delete(self):
        if not self.left and not self.right:
            if self.parent.left == self:
                self.parent.left = None
            else:
                self.parent.right = None
            del self
            return None
        elif self.left and self.right:
            if self.left.pri > self.right.pri:
                self.rightR()
            else:
                self.leftR()
        elif self.right:
            self.leftR()
        else:
            self.rightR()
        self._delete()
        
    def rightR(self):
        tmp = self.left
        if self.parent:
            if self.key < self.parent.key:
                self.parent.left = tmp
            else:
                self.parent.right = tmp
        self.left = tmp.right
        if self.left:
            self.left.parent = self
        tmp.right = self
        tmp.parent = self.parent
        self.parent = tmp
        
    def leftR(self):
        tmp = self.right
        if self.parent:
            if self.key < self.parent.key:
                self.parent.left = tmp
            else:
                self.parent.right = tmp
        self.right = tmp.left
        if self.right:
            self.right.parent = self
        tmp.left = self
        tmp.parent = self.parent
        self.parent = tmp
    
    def preo(self):
        tmp = ""
        tmp += " " + str(self.key)
        if self.left:
            tmp += self.left.preo()
        if self.right:
            tmp += self.right.preo()
        return tmp
    
    def ino(self):
        tmp = ""
        if self.left:
            tmp += self.left.ino()
        tmp += " " + str(self.key)
        if self.right:
            tmp += self.right.ino()
        return tmp

m = int(input())
root = None
for i in range(m):
    com = input().split()
    if com[0] == "insert":
        node = Node(int(com[1]), int(com[2]))
        try:
            root.insert(node)
        except AttributeError :
            root = node
    elif com[0] == "find":
        try:
            if root.find(int(com[1])):
                print("yes")
            else:
                print("no")
        except AttributeError:
            print("no")
    elif com[0] == "delete":
        try:
            root.delete(int(com[1]))
        except AttributeError:
            pass
    else:
        try:
            print(root.ino())
            print(root.preo())
        except AttributeError:
            print("None")
    c = 0
    while(True):
        if root.parent:
            root = root.parent
        else:
            break

Solution (Python):

class Node:
	def __init__(self, key, pri):
		self.key = key
		self.pri = pri
		self.left = self.right = None
	def __str__(self):
		ret = ''
		ret += 'key=' + str(self.key)
		ret += ',pri=' + str(self.pri)
		ret += ',left='
		if self.left != None: ret += str(self.left.key)
		ret += ',right='
		if self.right != None: ret += str(self.right.key)
		return ret

class Treap:
	def __init__(self):
		self.root = None

	def print(self):
		self.print_in_order()
		self.print_pre_order()

	def print_in_order(self):
		st = []
		cur = self.root
		while cur != None or len(st) != 0:
			if cur != None:
				st.append(cur)
				cur = cur.left
			else:
				cur = st.pop()
				print(' ' + str(cur.key), end='')
				cur = cur.right
		print()

	def print_pre_order(self):
		st = []
		st.append(self.root)
		while len(st) != 0:
			cur = st.pop()
			print(' ' + str(cur.key), end='')
			if cur.right != None:
				st.append(cur.right)
			if cur.left != None:
				st.append(cur.left)
		print()

	def find(self, key):
		cur = self.root
		while cur != None:
			if key == cur.key:
				return cur
			if key < cur.key:
				cur = cur.left
			else:
				cur = cur.right
		return None

	def insert(self, key, pri):
		self.root = self.insert_(self.root, key, pri)

	def insert_(self, node, key, pri):
		if node == None:
			return Node(key, pri)
		if key == node.key:
			return node

		if key < node.key:
			node.left = self.insert_(node.left, key, pri)
			if node.pri < node.left.pri:
				node = self.right_rotate(node)
		else:
			node.right = self.insert_(node.right, key, pri)
			if node.pri < node.right.pri:
				node = self.left_rotate(node)
		return node

	def right_rotate(self, node):
		tmp = node.left
		node.left = tmp.right
		tmp.right = node
		return tmp

	def left_rotate(self, node):
		tmp = node.right
		node.right = tmp.left
		tmp.left = node
		return tmp

	def delete(self, key):
		self.root = self.delete_(self.root, key)

	def delete_(self, node, key):
		if node == None:
			return node
		if key < node.key:
			node.left = self.delete_(node.left, key)
		elif key > node.key:
			node.right = self.delete_(node.right, key)
		else:
			return self.delete__(node, key)
		return node

	def delete__(self, node, key):
		if (node.left == None and node.right == None):
			return None
		elif node.left == None:
			node = self.left_rotate(node)
		elif node.right == None:
			node = self.right_rotate(node)
		else:
			if node.left.pri > node.right.pri:
				node = self.right_rotate(node)
			else:
				node = self.left_rotate(node)
		return self.delete_(node, key)

n = int(input())
treap = Treap()
for i in range(n):
	cmd = list(map(str, input().split()))
	if cmd[0] == 'print':
		treap.print()
	else:
		key = int(cmd[1])
		if cmd[0] == 'insert':
			treap.insert(key, int(cmd[2]))
		elif cmd[0] == 'find':
			if treap.find(key) != None:
				print('yes')
			else:
				print('no')
		else:
			treap.delete(key)