Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- typedef long long ll;
- using namespace std;
- struct node {
- ll x; int h = 1;
- node* l = 0, * r = 0;
- node() {}
- node(ll _x) {
- this->x = _x;
- }
- };
- int get_h(node* v) {
- return (v ? v->h : 0);
- }
- int dif(node* v) {
- return (v ? get_h(v->r) - get_h(v->l) : 0);
- }
- void update(node* v) {
- int h1 = get_h(v->l),
- h2 = get_h(v->r);
- v->h = max(h1, h2) + 1;
- }
- node* right_rotate(node* v) {
- if (!v) return v;
- node* c = v->l;
- v->l = c->r;
- c->r = v;
- update(v);
- update(c);
- return c;
- }
- node* left_rotate(node* v) {
- if (!v) return v;
- node* c = v->r;
- v->r = c->l;
- c->l = v;
- update(v);
- update(c);
- return c;
- }
- node* balance(node* v) {
- if (!v) return v;
- update(v);
- if (dif(v) == 2) {
- if (dif(v->r) < 0) {
- v->r = right_rotate(v->r);
- }
- return left_rotate(v);
- }
- if (dif(v) == -2) {
- if (dif(v->l) > 0) {
- v->l = left_rotate(v->l);
- }
- return right_rotate(v);
- }
- return v;
- }
- node* insert(node* v, ll k) {
- if (!v) {
- return new node(k);
- }
- else if (k < v->x) {
- v->l = insert(v->l, k);
- }
- else {
- v->r = insert(v->r, k);
- }
- return balance(v);
- }
- bool find(node* v, ll k) {
- if (!v) {
- return false;
- }
- else if (v->x == k) {
- return true;
- }
- else if (k < v->x) {
- return find(v->l, k);
- }
- else {
- return find(v->r, k);
- }
- }
- void print(node* v) {
- if (!v) {
- return;
- }
- print(v->l);
- cout << v->x << "\n";
- print(v->r);
- }
- int main() {
- ios_base::sync_with_stdio(0);
- cin.tie(0); cout.tie(0);
- node* root = nullptr;
- ll cur;
- while (true) {
- cin >> cur;
- if (!cur) {
- break;
- }
- else if (find(root, cur)) {
- continue;
- }
- else {
- root = insert(root, cur);
- }
- }
- print(root);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement