Cod sursa(job #1520552)

Utilizator narcis_vsGemene Narcis - Gabriel narcis_vs Data 9 noiembrie 2015 00:27:22
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include <cstdio>

using namespace std;
struct AVL
{
	AVL *Left, *Right;
	int value, bal, count;
	AVL(const int _value)
	{
		value = _value;
		bal = 0; count = 1;
		Left = Right = NULL;
	}
};
AVL *T, *NIL;
inline void RotateSS(AVL *&node)
{
	AVL *aux = node->Left;
	node->Left = aux->Right;
	aux->Right = node;
	node = aux;
	node->Right->bal = 0;
	node->bal = 0;
}
inline void RotateDD(AVL *&node)
{
	AVL *aux = node->Right;
	node->Right = aux->Left;
	aux->Left = node;
	node = aux;
	node->Left->bal = 0;
	node->bal = 0;
}
inline void RotateSD(AVL *&A)
{
	AVL *B = A->Left, *C = B->Right;
	A->Left = C->Right;
	B->Right = C->Left;
	if (C->bal == -1)
	{
		B->bal = 1;
		A->bal = 0;
	}
	else
	{
		B->bal = 0;
		A->bal = 1;
	}
	C->Left = B;
	C->Right = A;
	A = C;
	A->bal = 0;
}
inline void RotateDS(AVL *&A)
{
	AVL *B = A->Right, *C = B->Left;
	A->Right = C->Left;
	B->Left = C->Right;

	if (C->bal == -1)
	{
		B->bal = 1;
		A->bal = 0;
	}
	else
	{
		
		B->bal = 0;
		A->bal = 1;
	}


	C->Right = B;
	C->Left = A;
	A = C;
	A->bal = 0;
}
inline void Add(AVL *&node, const int value)
{
	if (node == NIL)
	{
		node = new AVL(value);
		node->Left = node->Right = NIL;
		return;
	}
	if (value < node->value)
	{
		Add(node->Left, value);
		/*if (node->bal == -1)
		{
			if (node->Left->bal == -1)
				RotateSS(node);
			else
				RotateSD(node);
		}
		else
			node->bal--;*/
		return;
	}
	if (value > node->value)
	{
		Add(node->Right, value);
		/*if (node->bal == 1)
		{
			if (node->Right->bal == 1)
				RotateDD(node);
			else
				RotateDS(node);
		}
		else
			node->bal++;*/
		return;
	}
	node->count++;
}
inline void DFS(AVL *node)
{
	if (node == NIL)
		return;								
	DFS(node->Left);
	for (int i = 1; i <= node->count; ++i)
		printf("%d ", node->value);
	DFS(node->Right);
}
int main()
{
	NIL = new AVL(-1);
	NIL->Left = NIL->Right = NIL;
	T = NIL;
	int n, x;
	freopen("algsort.in", "r", stdin);
	freopen("algsort.out", "w", stdout);
	scanf("%d\n", &n);
	for (int i = 1; i <= n; ++i)
	{
		scanf("%d\n", &x);
		Add(T, x);
	}
	DFS(T);
	return 0;
}