b392困難

字首多重集合排名

運用離線字典序座標與樹狀陣列排名,正確求解本題並處理邊界情況。

解題思路

先讀完操作,將所有更新會使用的字串排序去重,字典序位置固定。

樹狀陣列維護每個字串目前份數,刪除時先確認份數大於零。字首 p 對應排序區間 [lower_bound(p),lower_bound(p+{))。

若區間份數足夠,令目標排名為區間前的份數+k,再用樹狀陣列的二進位下降找第 k 份;重複份數自然佔用多個排名。

設總字元數 S;排序字串比較成本最壞 O(S log Q),操作 O(S log Q+Q log Q),輸出另計字元數;空間 O(S+Q)。

Step-by-step animation

教學例子:插入 a、ab、a。

回報動畫錯誤
步驟 1 / 3

插入

插入 a、ab、a。

a
a
ab
a 份數
2

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
struct BIT {
    int n;
    vector<long long> f;
    BIT(int n) : n(n), f(n + 1) {
    }
    void add(int i, long long v) {
        for (; i <= n; i += i & -i)
            f[i] += v;
    }
    long long sum(int i) {
        long long s = 0;
        for (; i; i -= i & -i)
            s += f[i];
        return s;
    }
};
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int q;
    cin >> q;
    struct Op {
        int t, k;
        string s;
    };
    vector<Op> ops;
    vector<string> a;
    while (q--) {
        int t, k = 0;
        string s;
        cin >> t >> s;
        if (t == 3)
            cin >> k;
        else
            a.push_back(s);
        ops.push_back({t, k, s});
    }
    sort(a.begin(), a.end());
    a.erase(unique(a.begin(), a.end()), a.end());
    BIT b(a.size());
    vector<int> cnt(a.size());
    for (auto o : ops) {
        int l = lower_bound(a.begin(), a.end(), o.s) - a.begin();
        if (o.t != 3) {
            int d = o.t == 1 ? 1 : (cnt[l] > 0 ? -1 : 0);
            cnt[l] += d;
            b.add(l + 1, d);
        } else {
            int r = lower_bound(a.begin(), a.end(), o.s + "{") - a.begin();
            if (b.sum(r) - b.sum(l) < o.k) {
                cout << "NONE\n";
                continue;
            }
            long long k = b.sum(l) + o.k;
            int pos = 0;
            for (int z = 1 << 18; z; z >>= 1)
                if (pos + z <= b.n && b.f[pos + z] < k) {
                    k -= b.f[pos + z];
                    pos += z;
                }
            cout << a[pos] << '\n';
        }
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多