Cod sursa(job #1256271)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 5 noiembrie 2014 23:56:27
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.42 kb
#include <fstream>
#include <cstdlib>
#include <ctime>
#define INF 2000000001
#define infile "algsort.in"
#define outfile "algsort.out"

using namespace std;

ifstream f(infile);
ofstream g(outfile);

int n, nr;

struct treap {
	int key, priority;
	treap *left, *right;
	treap() {};
	treap(int key, int priority, treap *left, treap *right) {
		this->key = key;
		this->priority = priority;
		this->left = left;
		this->right = right;
	}
} *Root, *Empty;

bool Search(treap *nod, int key) {
	if (nod == Empty)
		return false;
	if (key == nod->key)
		return true;
	if (key > nod->key)
		return Search(nod->right, key);
	return Search(nod->left, key);
}

void Rotate_Left(treap *&nod) {
	treap *t = nod->left;
	nod->left = t->right;
	t->right = nod;
	nod = t;
}

void Rotate_Right(treap *&nod) {
	treap *t = nod->right;
	nod->right = t->left;
	t->left = nod;
	nod = t;
}

void Balance(treap *&nod) {
	if (nod->left->priority > nod->priority)
		Rotate_Left(nod);
	else
		if (nod->right->priority > nod->priority)
			Rotate_Right(nod);
}

void Insert(treap *&nod, int key, int priority) {
	if (nod == Empty) {
		nod = new treap(key, priority, Empty, Empty);
		return;
	}
	if (key < nod->key)
		Insert(nod->left, key, priority);
	else
		Insert(nod->right, key, priority);
	Balance(nod);
}

void Erase(treap *&nod, int key) {
	if (nod == Empty)
		return;
	if (key < nod->key)
		Erase(nod->left, key);
	else
		if (key > nod->key)
			Erase(nod->right, key);
		else {
			if (nod->left == Empty && nod->right == Empty) {
				delete nod;
				nod = Empty;
			}
			else {
				(nod->left->priority > nod->right->priority) ? (Rotate_Left(nod), Erase(nod->right, key)) : (Rotate_Right(nod), Erase(nod->left, key));
			}
		}
}

void Split(treap *&Root, treap *&Rootl, treap *&Rootr, int key) {
	Insert(Root, key, INF);
	Rootl = Root->left;
	Rootr = Root->right;
	delete Root;
	Root = Empty;
}

void Join(treap *&Root, treap *Rootl, treap *Rootr, int key) {
	Root = new treap(key, 0, Rootl, Rootr);
	Erase(Root, Root->key);
}

void LUR(treap *nod) {
	if (nod == Empty)
		return;
	LUR(nod->left);
	g << nod->key << " ";
	LUR(nod->right);
}

int main() {
	Root = Empty = new treap(0, 0, NULL, NULL);
	srand(unsigned(time(NULL)));
	f >> n;
	for (int i = 1; i <= n; ++i) {
		f >> nr;
		Insert(Root, nr, rand() % (INF - 1) + 1);
	}
	LUR(Root);
	return 0;
}

//Trust me, I'm the Doctor!