题解:P3721 [AHOI2017/HNOI2017] 单旋

· · 题解

小数据结构题。

注意到一个 BST 的性质,就是最小值没有左儿子,最大值没有右儿子。观察一下最小值单旋的过程中其他点的深度变化。

注意到 1 的深度变成了 1,1 的右子树深度不变,其他点深度加 1。所以我们可以用一个值域树状数组实现区间加,单点查询。最大值同理。

然后是插入操作。我们发现一个点插入 BST 后,一定是其前驱或后继的儿子。我们可以用一个 set 来存所有已插入的点。注意特判树为空。

最后是 4,5 操作,其实就是在 2,3 操作后把根节点删除即可。

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define il inline
#define N 100005
il int rd(){
    int s = 0, w = 1;
    char ch = getchar();
    for (;ch < '0' || ch > '9'; ch = getchar()) if (ch == '-') w = -1;
    for (;ch >= '0' && ch <= '9'; ch = getchar()) s = ((s << 1) + (s << 3) + ch - '0');
    return s * w;
}
const int INF = 1e9 + 7;
set <int> s;
int rt, n, op[N], qx[N], nls[N], tot;
int ls[N], rs[N], fa[N];
struct BIT{
    int tr[N];
    il void add(int x, int k){ for (int i = x; i <= tot; i += (i & -i)) tr[i] += k; }
    il int ask(int x){ int ans = 0; for (int i = x; i; i -= (i & -i)) ans += tr[i]; return ans; }
    il void upd(int l, int r, int k){ add(max(l, 1), k), add(r + 1, -k); }
    il void chg(int x, int k){ upd(x, x, k - ask(x)); }
}B;
il void insert(int x){
    if (s.empty()) return printf ("%d\n", 1), s.insert(x), rt = x, fa[x] = tot + 1, B.chg(x, 1);
    auto it = s.lower_bound(x);
    if (it != s.end()) fa[x] = *it;
    if (it != s.begin()){
        it--;
        if (!fa[x] || B.ask(*it) > B.ask(fa[x])) fa[x] = *it;
    }
    if (x < fa[x]) ls[fa[x]] = x; else rs[fa[x]] = x;
    B.chg(x, B.ask(fa[x]) + 1), s.insert(x);
    printf ("%d\n", B.ask(x));
}
il void rotmin(){
    int x = *s.begin();
    printf ("%d\n", B.ask(x));
    if (rt == x) return ;
    B.upd(fa[x], tot, 1), B.chg(x, 1);
    if (rs[x]) fa[rs[x]] = fa[x], ls[fa[x]] = rs[x];
    fa[rt] = x, rs[x] = rt, rt = x, fa[x] = tot + 1;
}
il void rotmax(){
    int x = *(--s.end());
    printf ("%d\n", B.ask(x));
    if (rt == x) return ;
    B.upd(1, fa[x], 1), B.chg(x, 1);
    if (ls[x]) fa[ls[x]] = fa[x], rs[fa[x]] = ls[x];
    fa[rt] = x, ls[x] = rt, rt = x, fa[x] = tot + 1; 
}
il void delmin(){
    int x = *s.begin();
    rotmin(), s.erase(x), B.upd(1, tot, -1), rt = rs[x], fa[rt] = tot + 1;
}
il void delmax(){
    int x = *(--s.end());
    rotmax(), s.erase(x), B.upd(1, tot, -1), rt = ls[x], fa[rt] = tot + 1;
}
signed main(){
    n = rd();
    for (int i = 1; i <= n; i++){
        op[i] = rd();
        if (op[i] == 1) nls[++tot] = qx[i] = rd();
    }
    sort (nls + 1, nls + tot + 1), tot = unique(nls + 1, nls + tot + 1) - nls - 1;
    for (int i = 1; i <= n; i++) if (qx[i]) qx[i] = lower_bound(nls + 1, nls + tot + 1, qx[i]) - nls;
    for (int i = 1; i <= n; i++){
        if (op[i] == 1) insert(qx[i]);
        if (op[i] == 2) rotmin();
        if (op[i] == 3) rotmax();
        if (op[i] == 4) delmin();
        if (op[i] == 5) delmax();
    }
    return 0;
}