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;
}
posted @ 2018-11-01 22:39  FormerAutumn  阅读(335)  评论(0编辑  收藏  举报