Pagini recente » Cod sursa (job #3340438) | Cod sursa (job #197565) | Cod sursa (job #1872291) | Cod sursa (job #1601670) | Cod sursa (job #1256267)
#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) : Rotate_Right(nod);
Erase(nod, 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!