object Main extends App {
  val n: Int = io.StdIn.readInt()
  val tr: Treap = Empty

  (0 until n).foldLeft[Treap](tr){(t, _) =>
    val op: Array[String] = io.StdIn.readLine().split(" ")
    op(0) match {
      case "print" => t.show; t
      case "insert" => t.insert(op(1).toInt, op(2).toInt)
      case "find" => {
        val key: Int = op(1).toInt
        println(if (t.find(key)) "yes" else "no")
        t
      }
      case "delete" => {
        val key: Int = op(1).toInt
        t.delete(key)
      }
      case _ => throw new Error("Unknown operation")
    }
  }

  trait Treap {
    def priority: Int
    def leftRotate: Treap
    def rightRotate: Treap
    def insert(k: Int, p: Int): Treap
    def delete(k: Int): Treap
    def find(k: Int): Boolean
    def preorder: List[Int]
    def inorder: List[Int]
    def show: Unit = {
      println(" " + this.inorder.mkString(" "))
      println(" " + this.preorder.mkString(" "))
    }
  }
  case object Empty extends Treap {
    def priority: Int = throw new Error
    def leftRotate: Treap = throw new Error
    def rightRotate: Treap = throw new Error
    def insert(k: Int, p: Int): Node = Node(k, p, Empty, Empty)
    def delete(k: Int): Treap = this
    def find(k: Int): Boolean = false
    def preorder: List[Int] = Nil
    def inorder: List[Int] = Nil
  }

  case class Node(key: Int, priority: Int, left: Treap, right: Treap) extends Treap {
    def leftRotate: Treap = right match {
      case Empty => throw new Error
      case Node(k, p, l, r) =>
        Node(k, p, Node(key, priority, left, l), r)
    }
    def rightRotate: Node = left match {
      case Empty => throw new Error
      case Node(k, p, l, r) =>
        Node(k, p, l, Node(key, priority, r, right))
    }
    def insert(k: Int, p: Int): Treap = {
      if (key == k) this
      else if (k < key) {
        val l: Treap = left.insert(k, p)
        val updated: Node = Node(key, priority, l, right)
        if (priority < l.priority) updated.rightRotate
        else updated
      } else {
        val r: Treap = right.insert(k, p)
        val updated: Node = Node(key, priority, left, r)
        if (priority < r.priority) updated.leftRotate
        else updated
      }
    }
    def delete(k: Int): Treap = {
      if (k < key) Node(key, priority, left.delete(k), right)
      else if (k > key) Node(key, priority, left, right.delete(k))
      else (this match {
        case Node(_, _, Empty, Empty) => Empty
        case Node(_, _, Empty, _) => this.leftRotate
        case Node(_, _, _, Empty) => this.rightRotate
        case _ =>
          if (left.priority > right.priority) this.rightRotate
          else this.leftRotate
      }).delete(k)
    }
    def find(k: Int): Boolean = {
      if (k == key) true
      else if (k < key) left.find(k)
      else right.find(k)
    }
    def preorder: List[Int] = key :: (left.preorder ::: right.preorder)
    def inorder: List[Int]  = left.inorder ::: (key :: right.inorder)
  }
}
