Cod sursa(job #1852454)

Utilizator oldatlantianSerban Cercelescu oldatlantian Data 20 ianuarie 2017 20:15:18
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 5e5 + 5,
          BMAX = 1 << 17;

struct T {
    static T *nil;

    int key, pr;
    T *st, *dr;

    inline T() {
        key = 1-(1<<31);
        st = nil;
        dr = nil;
        pr = rand(); }

    inline T(int _key) {
        key = _key;
        pr = rand();
        st = nil;
        dr = nil; } };

T *T::nil = new T();
T *nil = T::nil;

int v[NMAX];
char buff[BMAX];

inline char nextch(void) {
    static int bp = BMAX;

    if (bp == BMAX) {
        bp = 0;
        fread(buff, 1, BMAX, stdin); }

    return buff[ bp++ ]; }

void get(int &arg) {
    char ch;

    do {
        ch = nextch(); }
    while (ch < '0' || ch > '9');
    arg = 0;
    do {
        arg = arg * 10 + ch - '0';
        ch = nextch(); }
    while ('0' <= ch && ch <= '9'); }

T *join(T *a, T *b) {
    if (a == nil) return b;
    if (b == nil) return a;

    if (a->pr >= b->pr) {
        a->dr = join(a->dr, b);
        return a; }
    else {
        b->st = join(a, b->st);
        return b; } }

T *join3(T *a, T *b, T *c) {
    return join(a, join(b, c)); }

pair<T*,T*> split(T *nod, int val) {
    if (nod == nil) return {nil, nil};

    if (nod->key <= val) {
        auto tmp = split(nod->dr, val);
        nod->dr = tmp.first;
        return {nod, tmp.second}; }
    else {
        auto tmp = split(nod->st, val);
        nod->st = tmp.second;
        return {tmp.first, nod}; } }

void dfs(T *nod) {
    if (nod->st != nil) dfs(nod->st);
    printf("%d ", nod->key);
    if (nod->dr != nil) dfs(nod->dr); }

T *insert(T *nod, int val) {
    auto tmp = split(nod, val);
    return join3(tmp.first, new T(val), tmp.second); }

int main(void) {
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);
    T *root;
    int n;

    nil->st = nil;
    nil->dr = nil;

    get(n);
    for (int i = 0; i < n; ++i)
        get(v[i]);

    root = nil;
    for (int i = 0; i < n; ++i)
        root = insert(root, v[i]);

    dfs(root);
    printf("\n");

    return 0; }