結果
| 問題 |
No.649 ここでちょっとQK!
|
| コンテスト | |
| ユーザー |
kazuma
|
| 提出日時 | 2018-04-03 22:20:01 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 439 ms / 3,000 ms |
| コード長 | 2,696 bytes |
| コンパイル時間 | 2,195 ms |
| コンパイル使用メモリ | 195,444 KB |
| 最終ジャッジ日時 | 2025-01-05 09:53:48 |
|
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 4 |
| other | AC * 32 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using T = ll;
struct node {
T val;
node *ch[2];
int size;
node(T v, node *l = nullptr, node *r = nullptr) : val(v), size(1) {
ch[0] = l; ch[1] = r;
}
};
int count(node *t) { return !t ? 0 : t->size; }
node *update(node *t) {
t->size = count(t->ch[0]) + count(t->ch[1]) + 1;
return t;
}
node *rotate(node *t, int b) {
node *s = t->ch[1 - b];
t->ch[1 - b] = s->ch[b];
s->ch[b] = t;
update(t); update(s);
return s;
}
node *splay(node *t, int k) {
assert(t && k < count(t));
int c = count(t->ch[0]);
if (k < c) {
int cc = count(t->ch[0]->ch[0]);
if (k < cc) {
t->ch[0]->ch[0] = splay(t->ch[0]->ch[0], k);
t = rotate(t, 1);
t = rotate(t, 1);
}
else if (k > cc) {
t->ch[0]->ch[1] = splay(t->ch[0]->ch[1], k - (cc + 1));
t->ch[0] = rotate(t->ch[0], 0);
t = rotate(t, 1);
}
else {
t = rotate(t, 1);
}
}
else if (k > c) {
k -= c + 1;
int cc = count(t->ch[1]->ch[0]);
if (k < cc) {
t->ch[1]->ch[0] = splay(t->ch[1]->ch[0], k);
t->ch[1] = rotate(t->ch[1], 1);
t = rotate(t, 0);
}
else if (k > cc) {
t->ch[1]->ch[1] = splay(t->ch[1]->ch[1], k - (cc + 1));
t = rotate(t, 0);
t = rotate(t, 0);
}
else {
t = rotate(t, 0);
}
}
return t;
}
node *merge(node *l, node *r) {
if (!l || !r) return !l ? r : l;
l = splay(l, count(l) - 1);
l->ch[1] = r;
update(l);
return l;
}
pair<node*, node*> split(node *t, int k) {
if (!t) return make_pair(nullptr, nullptr);
if (k >= count(t)) return make_pair(t, nullptr);
t = splay(t, k);
auto s = t->ch[0];
t->ch[0] = nullptr;
return make_pair(s, update(t));
}
node *insert(node *t, int k, T v) {
pair<node*, node*> s = split(t, k);
node *r = merge(s.first, new node(v));
r = merge(r, s.second);
return r;
}
node *erase(node *t, int k) {
pair<node*, node*> s1 = split(t, k), s2 = split(s1.second, 1);
if (s2.first) delete s2.first;
return merge(s1.first, s2.second);
}
node *find(node *t, int k) {
if (!t) return t;
int c = count(t->ch[0]);
return k < c ? find(t->ch[0], k) : k == c ? t : find(t->ch[1], k - (c + 1));
}
int cnt(node *t, T v) {
if (!t) return 0;
if (t->val < v) return count(t->ch[0]) + 1 + cnt(t->ch[1], v);
if (t->val == v) return count(t->ch[0]);
return cnt(t->ch[0], v);
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int Q, K;
cin >> Q >> K;
node *root = nullptr;
while (Q--) {
int t;
cin >> t;
if (t == 1) {
ll v;
cin >> v;
root = insert(root, cnt(root, v), v);
}
else if (count(root) >= K) {
printf("%lld\n", find(root, K - 1)->val);
root = erase(root, K - 1);
}
else {
printf("%d\n", -1);
}
}
return 0;
}
kazuma