题面
Xiao Ming and Xiao Bao are playing a simple Numbers game. In a round Xiao Ming can choose to write down a number, or ask Xiao Bao what the kth great number is. Because the number written by Xiao Ming is too much, Xiao Bao is feeling giddy. Now, try to help Xiao Bao.
题解
题意:
给
N
N
N个操作,
I
I
I 和
Q
Q
Q
I
I
I 插入值
Q
Q
Q 询问前面所有插入数的第
K
K
K大
分析
维护
1
1
1~
r
r
r 的区间第
k
k
k大 等价于维护一个大小为k的小顶堆。
考虑当前堆的大小 s z sz sz < k k k 的情况,没有第 k k k 大,直接往堆中插入值即可
如果当前堆的大小 s z sz sz >= k k k
-
考虑加入的值 x < t o p ( ) x < top() x<top() 此时, x x x不会影响当前的第k大的数,也不会对后续添加的数造成影响
-
考虑 x > = t o p ( ) x >= top() x>=top() 此时, x x x一定会出现在 第一大 ~ 第k大之间,而当前堆顶不可能会出现在其中,
所以将堆顶弹出,插入当前的x
查询第k大的时候,将堆顶输出即可
/*
@Author: YooQ
@Problem: 322971A
*/
#include <bits/stdc++.h>
using namespace std;
#define sc scanf
#define pr printf
#define ll long long
#define int long long
#define FILE_OUT freopen("out", "w", stdout);
#define FILE_IN freopen("in", "r", stdin);
#define debug(x) cout << #x << ": " << x << "\n";
#define AC 0
#define WA 1
#define INF 0x3f3f3f3f
const ll MAX_N = 2e6+5;
const ll MOD = 1e9+7;
int N, M, K;
int arr[MAX_N];
struct Tr {
int k, l, r;
}tr[MAX_N];
int dis[MAX_N];
int root = 0;
int indx = 0;
int sz = 0;
int merge(int x, int y) {
if (!x || !y) return x | y;
if (tr[x].k > tr[y].k) swap(x, y);
tr[x].r = merge(tr[x].r, y);
if (dis[tr[x].r] > dis[tr[x].l]) swap(tr[x].l, tr[x].r);
dis[x] = dis[tr[x].r] + 1;
return x;
}
void pop() {
root = merge(tr[root].l, tr[root].r);
dis[root] = dis[tr[root].r] + 1;
}
void solve(){
sz = 0;
indx = 0;
root = 0;
char opt[10];
int x;
for (int i = 1; i <= N; ++i) {
sc("%s", opt);
if (*opt == 'I') {
sc("%lld", &x);
if (sz < K || tr[root].k < x) {
if (sz == K) pop(), --sz;
tr[++indx] = {x, 0, 0};
dis[indx] = 0;
root = merge(root, indx);
++sz;
}
} else {
pr("%lld\n", tr[root].k);
}
}
}
signed main()
{
#ifndef ONLINE_JUDGE
//FILE_IN
FILE_OUT
#endif
int T = 1;//cin >> T;
while (~sc("%lld%lld", &N, &K)) solve();
return AC;
}