求按字典序第k大的數字

通過字典樹去求,類似線段樹的查詢方法

思路: 每個節點存入放前綴相同的字符串個數
然後查詢時對每個子樹的數量進行判斷,從前綴大的往小的遍歷,找到對應的,進行深度遍歷。

代碼:

#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;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章