Pagini recente » Cod sursa (job #1509079) | Cod sursa (job #51049) | Cod sursa (job #863758) | Cod sursa (job #841685) | Cod sursa (job #1539869)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
class Nod {
public:
Nod* st; Nod* dr;
int h; //adancimea maxima a celor doi subarbori
int key;
Nod() {
this->st = NULL;
this->dr = NULL;
this->h = 0;
this->key = 0;
}
Nod(Nod* st, Nod* dr, int h, int key) {
this->st = st;
this->dr = dr;
this->h = h;
this->key = key;
}
};
Nod* nil;
int getH(Nod* nod) {
return 1 + max(nod->st->h, nod->dr->h);
}
Nod* rotateRight(Nod* curent) {
Nod* leftSon = curent->st;
curent->st = leftSon->dr;
leftSon->dr = curent;
curent->h = getH(curent);
leftSon->h = getH(leftSon);
return leftSon;
}
Nod* rotateLeft(Nod* curent) {
Nod* rightSon = curent->dr;
curent->dr = rightSon->st;
rightSon->st = curent;
curent->h = getH(curent);
rightSon->h = getH(rightSon);
return rightSon;
}
Nod* balance(Nod* curent) {
curent->h = getH(curent);
if(curent->st->h > curent->dr->h + 1) {
//LR
if(curent->st->dr->h > curent->st->st->h)
curent = rotateLeft(curent->st);
//LL
curent = rotateRight(curent);
}
if(curent->dr->h > curent->st->h + 1) {
//RL
if(curent->dr->st->h > curent->dr->dr->h)
curent = rotateRight(curent->dr);
//RR
curent = rotateLeft(curent);
}
return curent;
}
Nod* insert(Nod* curent,const int key) {
if(curent == nil) {
curent = new Nod(nil, nil, 1, key);
return curent;
}
if(curent->key > key)
curent->st = insert(curent->st, key);
else
curent->dr = insert(curent->dr, key);
return balance(curent);
}
void inOrdine(Nod* curent) {
if(curent->st != nil)
inOrdine(curent->st);
fout << curent->key << " ";
if(curent->dr != nil)
inOrdine(curent->dr);
}
int main() {
Nod* root = NULL;
nil = new Nod(NULL, NULL, 0, 0);
root = nil;
int n;
fin >> n ;
for(int i = 0 ; i < n; ++i) {
int x;
fin >> x;
root = insert(root, x);
}
inOrdine(root);
return 0;
}