Cod sursa(job #1816765)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 26 noiembrie 2016 21:21:21
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <iostream>
#include <fstream>
#include <stdlib.h>
#define max(a, b) ((a) > (b) ? (a) : (b))
#define geth(n) (n->h = 1 + max(n->l->h, n->r->h))

using namespace std;

ifstream in("algsort.in");
ofstream out("algsort.out");

struct node
{
      int key, h;
      node *l, *r;
} *NIL;

void init(void)
{
      NIL = (node *) malloc(sizeof(node));
      NIL->key = NIL->h = 0,
      NIL->l = NIL->r = NULL;
}

node* rotleft(node *n)
{
      node *t = n->l;

      n->l = t->r, t->r = n,
              geth(n), geth(t);
      return t;
}

node* rotright(node *n)
{
      node *t = n->r;

      n->r = t->l, t->l = n,
              geth(n), geth(t);
      return t;
}

node* balance(node *n)
{
      geth(n);
      if (n->l->h > n->r->h + 1)
      {
              if (n->l->r->h > n->l->l->h)
                      n->l = rotright(n->l);
              n = rotleft(n);
      }
      else
              if (n->r->h > n->l->h + 1)
              {
                      if (n->r->l->h > n->r->r->h)
                              n->r = rotleft(n->r);
                      n = rotright(n);
              }
      return n;
}

node* insert(node *n, int key)
{
      if (n == NIL)
      {
              n = (node *) malloc(sizeof(node));
              n->key = key, n->h = 1, n->l = n->r = NIL;
              return n;
      }
      if (key < n->key)
              n->l = insert(n->l, key);
      else
              n->r = insert(n->r, key);
      return balance(n);
}

void sort(node* Root)
{
    if (Root)
    {
        if (Root -> l != NULL)
            sort(Root -> l);
        if (Root -> key)
            out << Root -> key << " ";
        if (Root -> r != NULL)
            sort(Root -> r);
    }
}

int n;
node* AVL;

int main()
{
    init();
    AVL = NIL;
    in >> n;
    int x;
    for (int i = 1; i <= n; i++)
    {
       in >> x;
       AVL = insert(AVL, x);
    }
    sort(AVL);
    out.close();
    return 0;
}