【bzoj3223】文艺平衡树

本文深入探讨了Splay树的数据结构与实现细节,通过具体的代码示例展示了Splay树的旋转操作、分裂操作及翻转操作等核心功能,并提供了一个基于Splay树解决区间反转问题的完整案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

splay,没什么好说的
尼玛记得kth的时候也要push啊!!!
T_T

#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
#define lc ch[u][0]
#define rc ch[u][1]
#define maxn 100007
#define KEY ch[ch[rt][1]][0]

inline int rd() {
    char c = getchar();
    while (!isdigit(c)) c = getchar() ; int x = c - '0';
    while (isdigit(c = getchar())) x = x * 10 + c - '0';
    return x;
}

typedef int arr[maxn];

arr sz , val , rv , fa , st;

int ch[maxn][2] , m , n , tot , top , rt;

inline void upd(int u) { sz[u] = sz[lc] + sz[rc] + 1 ; }

void build(int&u , int l , int r) {
    if (l > r) return;
    u = ++ tot;
    sz[u] = 1;
    int m = (l + r) >> 1;
    val[u] = m;
    build(lc , l , m - 1) , build(rc , m + 1 , r);
    fa[lc] = fa[rc] = u;
    upd(u);
}

inline void rev(int u) {
    if (!u) return;
    swap(lc , rc);
    rv[u] ^= 1;
}

inline void rot(int u , int&aim) {
    int f = fa[u] , g = fa[f] , l , r;
    assert(u != f);
    l = (ch[f][1] == u) , r = l ^ 1;
    if (f == aim) aim = u ; else ch[g][ch[g][1] == f] = u;
    fa[f] = u , fa[u] = g;
    if (ch[u][r]) fa[ch[u][r]] = f;
    ch[f][l] = ch[u][r] , ch[u][r] = f;
    upd(f) , upd(u);
}

inline void push(int u) {
    if (u && rv[u]) {
        rev(lc) , rev(rc);
        rv[u] = 0;
    }
}

void clear(int u) {
    if (!u) return;
    clear(fa[u]);
    push(u);
}

void splay(int u , int&aim) {
    for (clear(u);u != aim;rot(u , aim)) {
        int f = fa[u] , g = fa[f];
        if (f != aim) rot ( ((ch[f][0] == u) ^ (ch[g][0] == f)) ? u : f , aim);
    }
}

int kth(int k) {
    int u = rt;
    while (sz[lc] + 1 != k) {
        push(u);
        int t = sz[lc] + 1;
        if (t > k)
            u = lc;
        else
            k -= t , u = rc;
    }
    return u;
}

void split(int u , int v) {
    splay(u , rt);
    splay(v , rc);
    //clear(v);
}

void input() {
    n = rd() , m = rd();
    build(rt , 0 , n + 1);
    fa[0] = 0;
}

void print(int u) {
    push(u);
    if (lc) print(lc);
    tot ++;
    printf("%d" , val[u]);
    if (tot != n) putchar(' ');
    if (rc) print(rc);
}

void solve() {
    rep (i , 1 , m) {
        int l = rd() , r = rd();
        split(kth(l) , kth(r + 2));
        rev(KEY);
    }
    tot = 0;
    split(kth(1) , kth(n + 2));
    print(KEY);
}

int main() {
    #ifndef ONLINE_JUDGE
        freopen("data.txt" , "r" , stdin);
        freopen("data.out" , "w" , stdout);
    #endif
    input();
    solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值