#include #include unsigned int rand_int(void) { static unsigned int x = 123456789, y = 362436069, z = 521288629, w = 88675123; unsigned int t; t = (x ^ (x << 11)); x = y; y = z; z = w; return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))); } typedef long long i64; typedef struct Node { i64 val; int size; struct Node *left; struct Node *right; } Node; Node *create_node(i64 val) { Node *ret = (Node *)malloc(sizeof(Node)); ret->val = val; ret->size = 1; ret->left = ret->right = NULL; return ret; } typedef struct Pair { Node *left, *right; } Pair; Pair make_pair(Node *left, Node *right) { Pair pair = {left, right}; return pair; } int size(Node *node) { return node == NULL ? 0 : node->size; } Node *update(Node *node) { node->size = 1 + size(node->left) + size(node->right); return node; } // left内の最大 <= right内の最小 Node *merge(Node *left, Node *right) { if (left == NULL) { return right; } else if (right == NULL) { return left; } // sizeの和は一定 if ((int)rand_int() % (size(left) + size(right)) < size(left)) { left->right = merge(left->right, right); return update(left); } else { right->left = merge(left, right->left); return update(right); } } // 小さいのk個を左側に、それ以外を右側に Pair split(Node *root, int k) { if (root == NULL) return make_pair(root, root); if (k <= size(root->left)) { // root+右部分木はぜんぶ右側 Pair nodes = split(root->left, k); root->left = nodes.right; return make_pair(nodes.left, update(root)); } else { // root+左部分木はぜんぶ左側 Pair nodes = split(root->right, k - size(root->left) - 1); root->right = nodes.left; return make_pair(update(root), nodes.right); } } // xより小さい数の個数 int lower_bound(Node *root, i64 x) { if (root == NULL) return 0; if (x <= root->val) { // 右部分木には1個もない return lower_bound(root->left, x); } else { // root+左部分木ぜんぶ は確定 return lower_bound(root->right, x) + size(root->left) + 1; } } int exist(Node *root, i64 x) { if (root == NULL) return 0; if (root->val == x) return 1; return exist(root->left, x) || exist(root->right, x); } Node *insert(Node *root, i64 x) { Pair nodes = split(root, lower_bound(root, x)); return merge(merge(nodes.left, create_node(x)), nodes.right); } Node *erase(Node *root, i64 x) { if (!exist(root, x)) return root; Pair nodes = split(root, lower_bound(root, x)); // xはnodes.rightに含まれる(しかもroot?) return merge(nodes.left, split(nodes.right, 1).right); } // k番目に小さいnode Node *get_kth(Node *root, int k) { if (root == NULL) return NULL; int left_size = size(root->left); if (left_size + 1 == k) { return root; // 右の部分木にroot->valと等しいのはあるかもしれない } else if (left_size + 1 > k) { return get_kth(root->left, k); } else { return get_kth(root->right, k - left_size - 1); } } int main(void) { Node *root = NULL; int q, k; scanf("%d %d", &q, &k); while (q--) { int type; scanf("%d", &type); if (type == 1) { i64 x; scanf("%lld", &x); root = insert(root, x); } else { if (size(root) < k) { printf("-1\n"); } else { Node *ret = get_kth(root, k); printf("%lld\n", ret->val); root = erase(root, ret->val); } } } return 0; }