#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct _node {
  struct _node* left;
  struct _node* right;
  long key;
  long npl;
} node;

void visit_node_in_order(node* q, void (*callback)(node *)) {
  if (!q) {
    return;
  }

  visit_node_in_order(q->left, callback);
  callback(q);
  visit_node_in_order(q->right, callback);
}

void visit_node_post_order(node *q, void (*callback)(node *)) {
  if (!q) {
    return;
  }

  visit_node_post_order(q->left, callback);
  visit_node_post_order(q->right, callback);
  callback(q);
}

void node_destroy(node *q) {
  void (*func)(node *) = (void (*)(node *))free;
  visit_node_post_order(q, func);
}

node* node_union(node* l, node* r) {
  if (!l) {
    return r;
  }

  if (!r) {
    return l;
  }

  node* res;

  if (l->key >= r->key) {
    res = l;
    res->right = node_union(l->right, r);
  } else {
    res = r;
    res->right = node_union(r->right, l);
  }

  if (!res->left || res->left->npl < res->right->npl) {
    node *q = res->left;
    res->left = res->right;
    res->right = q;
  }

  if (!res->right) {
    res->npl = 0;
  } else {
    res->npl = res->right->npl + 1;
  }

  return res;
}

const int MAX_BUFFER = 0x1000;

int main() {
  char cmd[MAX_BUFFER];
  node *q = NULL;
  while (1) {
    fgets(cmd, MAX_BUFFER, stdin);
    printf("Got command %s\n", cmd);

    if (strlen(cmd) == 0 || cmd[0] == '\n') {
      printf("Finished reading\n");
      break;
    } else if (memcmp(cmd, "ADD", 3) == 0) {
      // handle command add
      int x = atoi(cmd + 4);
      node *el = (node *)malloc(sizeof(node));
      el->left = NULL;
      el->right = NULL;
      el->key = x;
      el->npl = 0;
  
      if (q) {
        q = node_union(q, el);
      } else {
        q = el;
      }

      printf("Added number: %d\n", x);
  
    } else if (memcmp(cmd, "DEL", 3) == 0) {
      // handle command del
      if (!q) {
        fprintf(stderr, "There is nothing to delete - heap is empty\n");
        continue;
      }
      long key = q->key;
      q = node_union(q->left, q->right);
      printf("Removed element: %d\n", key);
    } else {
      // handle unknown command
      fprintf(stderr, "Got unknown command %s\n", cmd);
    }

  }

  if (!q) {
    node_destroy(q);
  }

  return 0;
}
