【模板】平衡树

· · 算法·理论

平衡树Treap模板:

两种写法:指针写法(刘汝佳)和数组写法(李煜东)

1.指针写法:

e.g (UVA1479 Graph and Queries)

//注:在本题中,连通并不等同于直接相连! 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#define MAXN 20010
#define MAXM 60010
#define MAXC 500010
using namespace std;

inline int read() {
    register int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

///平衡树模板
///用到指针前一定要用if判断是否为NULL
struct node {
    node *ch[2];
    int r, v, s; 
    node (int v):v(v) {ch[0] = ch[1] = NULL; r = rand(); s = 1; }
    int cmp1(int x) const {
        if (x == v) return -1;
        return x < v ? 0 : 1;
    }
    void maintain() {
        s = 1;
        if (ch[0] != NULL) s += ch[0]->s;
        if (ch[1] != NULL) s += ch[1]->s;
    }
};

struct edge {
    int from, to;
} E[MAXM];

inline void rorate(node* &o, int d) {
    node* k = o->ch[d ^ 1];
    o->ch[d ^ 1] = k->ch[d];
    k->ch[d] = o;
    o->maintain(); k->maintain();
    o = k;
}

inline void Insert(node* &o, int x) {
    if (o == NULL) o = new node(x);
    else {
        int d = (x < o->v ? 0 : 1);
        Insert(o->ch[d], x);
        if (o->ch[d]->r > o->r) rorate(o, d ^ 1);
    }
    o->maintain();
}

inline void Remove(node* &o, int x) {
    int d = o->cmp1(x);
    if (d == -1) {
        node* u = o;
        if (o->ch[0] != NULL && o->ch[1] != NULL) {
            int d2 = (o->ch[0]->r > o->ch[1]->r ? 1 : 0);
            rorate(o, d2); Remove(o->ch[d2], x);
        } else {
            if (o->ch[0] == NULL) o = o->ch[1];
            else o = o->ch[0];
            delete u;
        }
    } else {
        Remove(o->ch[d], x);
    }
    if (o != NULL) o->maintain();
}

inline void cut_tree(node* &o) {
    if (o->ch[0] != NULL) cut_tree(o->ch[0]);
    if (o->ch[1] != NULL) cut_tree(o->ch[1]);
    delete o;
    o = NULL;
}

inline int kth(node* o, int k) { //查找第K大的数,如果想要查找第K小的数,可以全部取反,最后答案再取反 
    if (o == NULL || k <= 0 || k > o->s) return 0;
    int s_right = (o->ch[1] == NULL ? 0 : o->ch[1]->s);
    if (k == s_right + 1) return o->v;
    else if (k <= s_right) return kth(o->ch[1], k);
    else return kth(o->ch[0], k - s_right - 1);
}

node* Tree[MAXN]; //建Treap

///并查集部分:
int fa[MAXN];
inline int Find_fa(int x) {
    if (x == fa[x]) return x;
    return fa[x] = Find_fa(fa[x]);
}

inline void Merge(node* &x, node *&y) {
    if (x->ch[0] != NULL) Merge(x->ch[0], y);
    if (x->ch[1] != NULL) Merge(x->ch[1], y);
    Insert(y, x->v);
    delete x;
    x = NULL;
}

inline void Add(int u, int v) {
    u = Find_fa(u), v = Find_fa(v); 
    if (u != v) {
        //正常的并查集合并操作 
            if (Tree[u]->s < Tree[v]->s) {
            fa[u] = v;
            Merge(Tree[u], Tree[v]);
        } else {
            fa[v] = u;
            Merge(Tree[v], Tree[u]);
        }   
    }
}
///主程序部分:倒序存储询问

struct order {
    char opt;
    int u, k;
} Orders[MAXC];

int T, n, m, eid;
long long query_num, query_cnt;
int w[MAXN];
bool deleted[MAXM];

int main() {
    while (scanf("%d %d", &n, &m) == 2 && n) {
        T++;
        for (int i = 1; i <= n; i++) w[i] = read();
        for (int i = 1; i <= m; i++) {
            E[i].from = read();
            E[i].to = read();
        }
        memset(deleted, false, sizeof(deleted));
        eid = 0;
        while (true) {
            char ch;
            int k = 0;
            scanf(" %c", &ch);
            if (ch == 'E') break;
            int x; scanf("%d", &x); //scanf输入整数时不需要加入空格, 因为会自动识别出整数,就像stringstream一样
            if (ch == 'D') deleted[x] = true;
            if (ch == 'Q') scanf("%d", &k);
            if (ch == 'C') {
                int v; scanf("%d", &v);
                k = w[x];
                w[x] = v;
            }
            eid++;
            Orders[eid] = (order){ch, x, k};
        }
        for (int i = 1; i <= n; i++) {
            fa[i] = i;
            if (Tree[i] != NULL) cut_tree(Tree[i]); //上个数据遗留下来的空间要清空,否则会MLE
            Tree[i] = new node(w[i]); 
        }
        for (int i = 1; i <= m; i++)
            if (!deleted[i])
                Add(E[i].from, E[i].to);
        query_num = 0; query_cnt = 0;
        ///注意:存储了Orders的反向操作之后,反向输出的时候所有的下标一定都是Orders[]里面的下标 
        for (int i = eid; i >= 0; i--) {
            if (Orders[i].opt == 'D') Add(E[Orders[i].u].from, E[Orders[i].u].to);
            if (Orders[i].opt == 'Q') {
                query_num++;
                query_cnt += kth(Tree[Find_fa(Orders[i].u)], Orders[i].k);
            } 
            if (Orders[i].opt == 'C') { //改一个点的权值可以不用再写一个BST修改操作,直接删去加上即可 
                int u = Find_fa(Orders[i].u);
                Remove(Tree[u], w[Orders[i].u]);
                Insert(Tree[u], Orders[i].k);
                w[Orders[i].u] = Orders[i].k;
            }
        }
        printf("Case %d: %.6lf\n", T, query_cnt / ((double)(query_num)));
    }
    return 0;
}

2.数组写法:

e.g P3369 【模板】普通平衡树

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#define MAXN 100010
#define INF 1000000010
#define ZZ register int
using namespace std;

struct treap {
    int ch[2], val, dat, cnt, siz;
} tr[MAXN];

int tot, root, n;

inline int read() {
    ZZ x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

inline int new_node(int v) {
    ///这样写避免了指针写法中的new node 的时间
    tr[++tot].val = v;
    tr[tot].dat = rand();
    tr[tot].cnt = tr[tot].siz = 1;
    return tot;
}

inline void update(int p) {
    tr[p].siz = tr[tr[p].ch[0]].siz + tr[tr[p].ch[1]].siz + tr[p].cnt;
}

inline void build() {
    new_node(-INF); new_node(INF);
    root = 1; tr[1].ch[1] = 2;
    update(root);
}

inline int get_rank(int p, int v) {
    if (p == 0) return 0;
    if (v == tr[p].val) return tr[tr[p].ch[0]].siz + 1;
    if (v < tr[p].val) return get_rank(tr[p].ch[0], v);
    return get_rank(tr[p].ch[1], v) + tr[tr[p].ch[0]].siz + tr[p].cnt;
}

inline int get_kth(int p, int r) {
    if (p == 0) return INF;
    if (tr[tr[p].ch[0]].siz >= r) return get_kth(tr[p].ch[0], r);
    if (tr[tr[p].ch[0]].siz + tr[p].cnt >= r) return tr[p].val;
    return get_kth(tr[p].ch[1], r - tr[tr[p].ch[0]].siz - tr[p].cnt);
}

inline void revote(int &p, int type) {
  ///当然也可以分开写成Zig和Zag
    ZZ q = tr[p].ch[type];
    tr[p].ch[type] = tr[q].ch[type ^ 1], tr[q].ch[type ^ 1] = p, p = q;
    update(tr[p].ch[type ^ 1]), update(p);
}

inline void insert(int &p, int v) {
    if (p == 0) {
        p = new_node(v);
        return;
    } 
    if (v == tr[p].val) {
        tr[p].cnt++; update(p);
        return;
    }
    if (v < tr[p].val) {
        insert(tr[p].ch[0], v);
        if (tr[p].dat < tr[tr[p].ch[0]].dat) revote(p, 0);
    } else {
        insert(tr[p].ch[1], v);
        if (tr[p].dat < tr[tr[p].ch[1]].dat) revote(p, 1);
    }
    update(p);
}

inline int get_minner(int v) {
    ZZ res = 1;
    ZZ p = root;
    while (p) {
        if (v == tr[p].val) {
            if (tr[p].ch[0] > 0) {
                p = tr[p].ch[0];
                while (tr[p].ch[1] > 0) p = tr[p].ch[1];
                res = p;
            }
            break;
        }
        if (tr[p].val < v && tr[p].val > tr[res].val) res = p;
        p = v < tr[p].val ? tr[p].ch[0] : tr[p].ch[1];
    }
    return tr[res].val;
}

inline int get_maxxer(int v) {
    ZZ res = 2, p = root;
    while (p) {
        if (v == tr[p].val) {
            if (tr[p].ch[1] > 0) {
                p = tr[p].ch[1];
                while (tr[p].ch[0] > 0) p = tr[p].ch[0];
                res = p;
            }
            break;
        }
        if (tr[p].val > v && tr[p].val < tr[res].val) res = p;
        p = v < tr[p].val ? tr[p].ch[0] : tr[p].ch[1];
    }
    return tr[res].val;
}

inline void delet (int &p, int v) {
    if (p == 0) return;
    if (v == tr[p].val) {
        if (tr[p].cnt > 1) {
            tr[p].cnt--;
            update(p);
            return;
        }
        if (tr[p].ch[0] || tr[p].ch[1]) {
            if (tr[p].ch[1] == 0 || tr[tr[p].ch[0]].dat > tr[tr[p].ch[1]].dat) {
                revote(p, 0);
                delet(tr[p].ch[1], v);
            } else {
                revote(p, 1);
                delet(tr[p].ch[0], v);
            }
            update(p);
        } else 
            p = 0;
        return;
    }
    v < tr[p].val ? delet(tr[p].ch[0], v) : delet(tr[p].ch[1], v);
    update(p);
}

int main() {
    build();
    n = read();
    while (n--) {
        ZZ opt, x;
        opt = read(); x = read();
        if (opt == 1) {
            insert(root, x);
        } else if (opt == 2) {
            delet(root, x);
        } else if (opt == 3) {
            printf("%d\n", get_rank(root, x) - 1);
        } else if (opt == 4) {
            printf("%d\n", get_kth(root, x + 1));
        } else if (opt == 5) {
            printf("%d\n", get_minner(x));
        } else {
            printf("%d\n", get_maxxer(x));
        }
    }
    return 0;
}