[BZOJ2028][SHOI2009]会场预约(Splay)

考虑以日期为关键字,把预约用Splay进行维护。
先考虑加入新的预约。设新的预约是从 l 日到r日。
很显然,一个从 l0 日到 r0 日的预约与这个新的预约不冲突的充分必要条件为: r0<l l0>r
首先找出满足 r0<l 的情况下 r0 最大的节点 x ,以及满足l0>r的情况下 l0 最小的节点 y 。这显然就是平衡树中求前驱后继的操作。
下面使用类似于Splay维护序列时提取区间的操作,把节点xSplay到根,再把 y Splay到根的右子节点。那么y的左子树就包含了所有冲突的预约。此时冲突的预约个数就是 y 的左子树的size。此时,就可以新建一个节点(新的预约),并用这个节点替换掉 y 的左子树,并维护下size
2 个操作就是询问根节点的size(我的程序稍微写麻烦了点)。
代码:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
    int res = 0; bool bo = 0; char c;
    while (((c = getchar()) < '0' || c > '9') && c != '-');
    if (c == '-') bo = 1; else res = c - 48;
    while ((c = getchar()) >= '0' && c <= '9')
        res = (res << 3) + (res << 1) + (c - 48);
    return bo ? ~res + 1 : res;
}
inline char get() {
    char c; while ((c = getchar()) != 'A' && c != 'B'); return c;
}
const int N = 2e5 + 5;
int n, T, Rt, cnt, fa[N], lc[N], rc[N], sze[N], L[N], R[N];
int which(int x) {return rc[fa[x]] == x;}
void upt(int x) {
    sze[x] = 1;
    if (lc[x]) sze[x] += sze[lc[x]];
    if (rc[x]) sze[x] += sze[rc[x]];
}
void rotate(int x) {
    int y = fa[x], z = fa[y], b = lc[y] == x ? rc[x] : lc[x];
    if (z) (lc[z] == y ? lc[z] : rc[z]) = x;
    fa[x] = z; fa[y] = x; if (b) fa[b] = y;
    if (lc[y] == x) rc[x] = y, lc[y] = b;
    else lc[x] = y, rc[y] = b; upt(y); upt(x);
}
void splay(int x, int tar) {
    while (fa[x] != tar) {
        if (fa[fa[x]] != tar) {
            if (which(x) == which(fa[x])) rotate(fa[x]);
            else rotate(x);
        }
        rotate(x);
    }
    if (!tar) Rt = x;
    upt(x);
}
int PreR(int v) {
    int x = Rt, res = 1;
    while (x)
        if (R[x] < v) res = x, x = rc[x];
        else x = lc[x];
    return res;
}
int SufL(int v) {
    int x = Rt, res = 2;
    while (x)
        if (L[x] > v) res = x, x = lc[x];
        else x = rc[x];
    return res;
}
void ins(int l, int r) {
    int x = PreR(l), y = SufL(r);
    splay(x, 0); splay(y, Rt);
    printf("%d\n", (lc[rc[Rt]] ? sze[lc[rc[Rt]]] : 0));
    if (lc[rc[Rt]]) {
        cnt -= sze[lc[rc[Rt]]];
        fa[lc[rc[Rt]]] = 0; lc[rc[Rt]] = 0;
        upt(rc[Rt]); upt(Rt);
    }
    L[lc[rc[Rt]] = ++T] = l; R[T] = r; fa[T] = rc[Rt];
    sze[T] = 1; upt(rc[Rt]); upt(Rt); cnt++;
}
void init() {
    fa[T = rc[Rt = 1] = 2] = sze[2] = 1;
    L[sze[1] = 2] = R[2] = 1e5 + 3;
}
int main() {
    int i, x, y; n = read(); char c; init();
    while (n--) {
        c = get(); if (c == 'A') {
            x = read(); y = read();
            ins(x, y);
        }
        else printf("%d\n", cnt);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值