通过字典树去求,类似线段树的查询方法
思路: 每个节点存入放前缀相同的字符串个数
然后查询时对每个子树的数量进行判断,从前缀大的往小的遍历,找到对应的,进行深度遍历。
代码:
#include <bits/stdc++.h>
using namespace std;
const int mx = 1e5;
struct tree{
int count_s;
vector<int>nex;
tree() {
nex = vector<int>(10, -1);
}
}T[mx];
int tot;
void Insert(string s) {
int r = 0;
for (auto &i : s) {
int is = i-'0';
if (T[r].nex[is] == -1) T[r].nex[is] = ++tot;
r = T[r].nex[is];
T[r].count_s++;
}
return;
}
string query(int a, int r) {
for (int i = 9; i >= 0; --i) {
if (T[r].nex[i] == -1) continue;
if (a <= T[T[r].nex[i]].count_s)
return (char)(i+'0')+query(a, T[r].nex[i]);
else a -= T[T[r].nex[i]].count_s;
}
return "";
}
int main() {
int n, m;
string s;
cin >> n >> m;
T[0].count_s = 0;
for (int i = 0; i < n; ++i) {
cin >> s;
if (s == "I") {
cin >> s;
Insert(s);
}
else
cout << query(m, 0) << endl;
}
return 0;
}