#include<stdio.h>
#include<stdlib.h>
typedef struct gNode{
  int key, priority;
  struct gNode *left;
  struct gNode *right;
}gNode;
gNode * del(gNode **,int);
gNode * _delete(gNode **,int);
int find(gNode *p,int x){
  while(p != NULL){
    if(p->key == x) return 1;
    else if(p->key > x) p = p->left;
    else p = p->right;
  }
  return 0;
}
void Inorder(gNode *p){
  if(p->left != NULL) Inorder(p->left);
  printf(" %d", p->key);
  if(p->right != NULL) Inorder(p->right);
  return;
}
void Preorder(gNode *p){
  printf(" %d", p->key);
  if(p->left != NULL) Preorder(p->left);
  if(p->right != NULL) Preorder(p->right);
  return;
}
void print(gNode *p){
  Inorder(p);
  printf("\n");
  Preorder(p);
  printf("\n");
  return;
}
gNode * Make_node(int x,int y){
  gNode *new = malloc(sizeof(gNode));
  new->key = x;
  new->priority = y;
  new->left = NULL;
  new->right = NULL;
  return new;
}
gNode *R_R(gNode *p){
  gNode *q = p->left;
  p->left = q->right;
  q->right = p;
  return q;
}
gNode *L_R(gNode *p){
  gNode *q = p->right;
  p->right = q->left;
  q->left = p;
  return q;
}
gNode* Ins(gNode **t, int key, int priority){
  gNode *new;
  if((*t) == NULL)
    return new = Make_node(key,priority);
  if ((*t)->key == key)
    return *t;
  if(key < (*t)->key){
    (*t)->left = Ins(&(*t)->left, key, priority);
    if((*t)->priority < (*t)->left->priority)
      (*t) = R_R((*t));
  }
  else {
    (*t)->right = Ins(&(*t)->right, key, priority);
    if((*t)->priority < (*t)->right->priority)
      (*t) = L_R((*t));
  }
  return *t;
}
gNode * del(gNode **t, int key){
  if((*t) == NULL)
    return NULL;
  if(key < (*t)->key)
    (*t)->left = del(&((*t)->left),key);
  else if(key > (*t)->key)
    (*t)->right = del(&((*t)->right),key);
  else return _delete(t,key);
  return *t;
}
gNode * _delete(gNode **t,int key){
  if((*t)->left == NULL && (*t)->right == NULL)
    return NULL;
  else if((*t)->left == NULL)
    (*t) = L_R(*t);
  else if((*t)->right == NULL)
    (*t) = R_R(*t);
  else {
    if((*t)->left->priority > (*t)->right->priority)
      (*t) = R_R(*t);
    else
      (*t) = L_R(*t);
  }
  return del(t,key);
}
int main(){
  int i;
	int n, x, y;
  char com[8];
  gNode *r = NULL;
  scanf("%d", &n);
  for(i = 0 ; i < n ; i++){
    scanf("%s", com);
    switch(com[0]){
    case 'i':scanf("%d %d", &x, &y);
      r = Ins(&r, x, y);
      break;
    case 'd':scanf("%d", &x);
      r = del(&r, x);
      break;
    case 'f':scanf("%d", &x);
      if(find(r,x)) printf("yes\n");
      else printf("no\n");
      break;
    case 'p':print(r);
      break;
    }
  }
  return 0;
}

