AVL模板

感谢此博客

#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define de(x) cout << #x << " = " << x << endl
#define clr(a,b) memset(a,b,sizeof(a))
using namespace std;

typedef long long ll;
const int INF = 0x3f3f3f3f;

const int N = 2e5 + 15;

struct AvlTree
{
    int val;
    int ch[2];
    int hei, sz;
    /*node( int _v, int _h, int _sz )
    {
        val = _v;
        hei = _h;
        sz = _sz;
        ch[0] = ch[1] = 0;
    }*/
};
AvlTree t[N<<2];
int cnt, rt;

void node( AvlTree &x, int v, int _h, int _sz )
{
    x.val = v;
    x.hei = _h;
    x.sz = _sz;
    x.ch[0] = x.ch[1] = 0;
}
    

int height( int x )
{
    if ( !x ) return -1;
    else
        return t[x].hei;
}
    
int rotate( int x, int f )
{
    int y = t[x].ch[f^1];
    t[x].ch[f^1] = t[y].ch[f];
    t[y].ch[f] = x;
    
    t[x].hei = max( height(t[x].ch[0]), height(t[x].ch[1]) ) + 1;
    t[y].hei = max( height(t[y].ch[0]), height(t[y].ch[1]) ) + 1;
    return y;
}

int doubleL2R( int x )
{
    t[x].ch[0] = rotate( t[x].ch[0], 0 );
    return rotate( x, 1 );
}

int doubleR2L( int x )
{
    t[x].ch[1] = rotate( t[x].ch[1], 1 );
    return rotate( x, 0 );
}



void ins( int &x, int v )
{
    if ( !x ) node( t[x=cnt++], v, 0, 0);
    else if ( v < t[x].val )
    {
        ins( t[x].ch[0], v );
        if ( height(t[x].ch[0]) - height(t[x].ch[1]) == 2 )
        {
            int f = v < t[t[x].ch[0]].val;
            if ( f )
                x = rotate( x, f );
            else
                x = doubleL2R( x );
        }
    }
    else if ( v > t[x].val )
    {
        ins( t[x].ch[1], v );
        if ( height(t[x].ch[1]) - height(t[x].ch[0])  == 2 )
        {
            int f = v > t[t[x].ch[1]].val;
            if ( f )
                x = rotate( x, f^1 );
            else
                x = doubleR2L( x );
        }
    }
    t[x].hei = max( height(t[x].ch[0]), height(t[x].ch[1]) ) + 1;
}

void find( int x, int v )
{
    if ( !x ) return ;
    if ( t[x].val == v ) return ;
    printf("%d ", t[x].val );
    find( t[x].ch[ v > t[x].val ], v );
}

void init()
{
    cnt = 1;
    rt = 0;
    node( t[rt], 0, 0, 0 );
}

int main()
{
    int n;
    init();
    scanf("%d", &n);
    for ( int i = 0; i < n; i ++ )
    {
        int op, now;
        scanf("%d%d", &op, &now);
        if ( op == 1 ) ins( rt, now );
        else
        {
            find( rt, now );
            printf("%d\n", now);
        }
    }
    return 0;
}

转载于:https://www.cnblogs.com/FormerAutumn/p/9893094.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值