Cod sursa(job #1305955)

Utilizator mathboyDragos-Alin Rotaru mathboy Data 30 decembrie 2014 13:06:36
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <cstdio>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <cstring>
#include <string>
#include <set>
#include <stack>
#include <deque>
#define pb push_back

#define mp make_pair
#define f first
#define s second
#define ll long long

using namespace std;
const int luck = 1e6;

template <class T>
class Treap {
  struct Node {
    int priority;
    T val;
    Node *left, *right;
    Node(): priority(0), val(0) {}
    Node(T _val, int _priority, Node* _left, Node* _right): val(_val) {
      this->left = _left;
      this->right = _right;
      priority = _priority;
    }
  };
  private:
    Node* Root, *nil;

  public:

    Treap() {
      srand(time(NULL));
      Root = nil = new Node(0, 0, NULL, NULL);
    }
    Treap(const vector <T>& input) {
      srand(time(NULL));

      Root = nil = new Node(0, 0, NULL, NULL);

      for (const auto&it: input) {
        this->insert(it);
      }
    }
    void insert(const T& key) {
      _insert(Root, key, rand() % luck + 1);
    }

    friend ostream& operator << (ostream &os, Treap& Tr) {
      Tr._print(Tr.Root, os);
      return os;
    }

  private:
    void rotright(Node* &R) {
      Node* aux = R->left;
      R->left = aux->right; aux->right = R;
      R = aux;
    }
    void rotleft(Node* &R) {
      Node* aux = R->right;
      R->right = aux->left; aux->left = R;
      R = aux;
    }
    void balance(Node* &R) {
      if (R->left->priority > R->priority) {
        rotright(R);
      } else if (R->right->priority > R->priority) {
        rotleft(R);
      }
    }
    void _insert(Node* &R, T key, int priority) {
      if (R == nil) {
        R = new Node(key, priority, nil, nil);
        return ;
      }
      if (key < R->val) {
        _insert(R->left,key, priority);
      }
      else if(key >= R->val) {
        _insert(R->right,key, priority);
      }
      balance(R);
    }

    void _print(Node* &R, ostream& os) {
      if (R->left != nil) {
        _print(R->left, os);
      }
      if (R->right != nil) {
        _print(R->right, os);
      }
      os << R->val << " ";
    }
};
int main() {
#ifndef ONLINE_JUDGE
  ifstream cin("test.in");
  ofstream cout("test.out");
#endif

  int N; cin >> N;
  vector <int> v(N);
  for (int i = 0; i < N; ++i) {
    cin >> v[i];
  }
  Treap<int> T;
  T.insert(1); T.insert(2); T.insert(3);
  cout << T;
  return 0;
}