Cod sursa(job #470629)

Utilizator blasterzMircea Dima blasterz Data 14 iulie 2010 21:58:01
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 kb
/*
 *	Algsort
 *	AVL = Balanced BST
 *	@author: Mircea Dima
*/

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#define dim 8192
#define oo 0x3f3f3f3f

using namespace std;
char ax[dim];
int pz;

inline void cit (int &x)
{
	x = 0;
	while (ax[pz] < '0' || ax[pz] > '9')
		if (++pz == dim)
			fread (ax, 1, dim, stdin), pz = 0;
		
	while (ax[pz] >= '0' && ax[pz] <= '9')
	{
		x = x * 10 + ax[pz] - '0';
		if (++pz == dim)
			fread (ax, 1, dim, stdin), pz = 0;
	}
	
}


struct nod
{
	int key;
	char height;
	nod *left, *right;
};

typedef nod* tree;

tree R, nil;

void init ()
{
	srand (time (0));
	nil = new nod;
	nil->left = nil->right = 0;
	nil->key = 0;
	nil->height = 0;
	R = nil;
}

inline void getHeight (tree &n)
{
	if (n == nil) return;
	n->height = 1 + max (n->left->height, n->right->height);
}

inline void rotateLeft (tree &n)
{
	tree t = n->left;
	n->left = t->right;
	t->right = n;
	getHeight (n); getHeight (t);
	n = t;
}

inline void rotateRight (tree &n)
{
	tree t = n->right;
	n->right = t->left;
	t->left = n;
	getHeight (n); getHeight (t);
	n = t;
}

inline void balance (tree &n)
{
	getHeight (n);
	
	if (n->left->height > n->right->height + 1)
	{
		if (n->left->right->height > n->left->left->height)
			rotateRight (n->left);
		rotateLeft (n);
	}
	else
	if (n->right->height > n->left->height + 1)
	{
		if (n->right->left->height > n->right->right->height)
			rotateLeft (n->right);
		rotateRight (n);
	}
}

inline void insert (tree &n, int v)
{
	if (n == nil)
	{
		n = new nod;
		n->left = n->right = nil;
		n->key = v;
		n->height = 1;
		return;
	}
	
	if (v < n->key) 
		insert (n->left, v);

	else
		insert (n->right, v);
	
	balance (n);
}

inline void ino (tree n)
{
	if (n == nil) return;
	ino (n->left);
	printf ("%d ", n->key);
	ino (n->right);
}

int main ()
{
	freopen ("algsort.in", "r", stdin);
	freopen ("algsort.out", "w", stdout);
	
	init ();
	int n;
	cit (n);
	//scanf ("%d", &n);
	int v;
	for (int i = 1; i <= n; ++i)
	{
	//	scanf ("%d", &v);
		cit (v);
		insert (R, v);
	}
	
	ino (R);
	
	printf ("\n");
	return 0;
}