SBT平衡树

来源:互联网 发布:数据科学导论 pdf下载 编辑:程序博客网 时间:2024/04/28 09:54
#include <bits/stdc++.h>using namespace std;#define REP(i, a, b) for (int i = (a), _end_ = (b); i <= _end_; ++i)#define debug(...) fprintf(stderr, __VA_ARGS__)#define mp make_pair#define x first#define y second#define pb push_back#define SZ(x) (int((x).size()))#define ALL(x) (x).begin(), (x).end()template<typename T> inline bool chkmin(T &a, const T &b){ return a > b ? a = b, 1 : 0; }template<typename T> inline bool chkmax(T &a, const T &b){ return a < b ? a = b, 1 : 0; }typedef long long LL;const int dmax = 300100, oo = 0x3f3f3f3f;int n, m;#define L ch[0]#define R ch[1]struct node{    int x, size;    node *f, *ch[2];    node()    {x = size = 0;        f = L = R = NULL;    }};node *Null;inline void init(){Null = new node;Null->f = Null->L = Null->R = Null;Null->size = 0;}inline node *new_node(int k){node *tmp = new node;tmp->x = k;tmp->size = 1;tmp->f = tmp->L = tmp->R = Null;    return tmp;}struct SBT{    node *root = NULL;    inline bool is_root(node *t) { return t == Null || t->f->L != t && t->f->R != t; }    inline void push_up(node *t) { t->size = t->L->size + t->R->size + 1; }    inline void rotate(node *x)    {if (is_root(x)) return;        node *y = x->f;        if (is_root(y))            root = x;        else{            if (y == y->f->L)                y->f->L = x;            else y->f->R = x;        }        x->f = y->f;        int k = x == y->R;        y->ch[k] = x->ch[!k];        if (x->ch[!k] != Null) x->ch[!k]->f = y;        x->ch[!k] = y;        y->f = x;        push_up(y);        push_up(x);}void maintain(node *t, int T){if (!T){if (t->L->L->size > t->R->size)rotate(t->L);else if(t->L->R->size > t->R->size){rotate(t->L->R);rotate(t->L);} else return;} else {if (t->R->R->size > t->L->size)rotate(t->R);else if (t->R->L->size > t->L->size){rotate(t->R->L);rotate(t->R);} else return;}maintain(t->L, 0);maintain(t->R, 1);maintain(t, 0);maintain(t, 1);}void insert(int k, node *t){if (root == NULL){root = new_node(k);return;}int T = k >= t->x;if (t->ch[T] != Null)insert(k, t->ch[T]);else {t->ch[T] = new_node(k);t->ch[T]->f = t;}push_up(t);maintain(t, T);}void dfs(node *x){if (x == Null) return;dfs(x->L);printf("%d ", x->x);dfs(x->R);}inline void out(){dfs(root);puts("");}}t;int main(){#ifndef ONLINE_JUDGEfreopen("input.txt", "r", stdin);freopen("output.txt", "w", stdout);#endifinit();scanf("%d", &n);REP(i, 1, n){int k;scanf("%d", &k);t.insert(k, t.root);}t.out();return 0;}

1 0
原创粉丝点击