Cod sursa(job #1852495)

Utilizator oldatlantianSerban Cercelescu oldatlantian Data 20 ianuarie 2017 20:50:27
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <cstdio>
#include <ctime>
using namespace std;

const int NMAX = 5e5 + 5,
          BMAX = 1 << 14,
           nil = 0;

inline unsigned short int rand(void) {
    static unsigned short int res = time(NULL) & 0xffff;
    res = res ^ (1 << res) | 1;
    return res; }

struct PII {
    int x, y; };

struct T {
    unsigned short int pr;
    int key, st, dr;

    inline T() {
        key = -1;
        st = nil;
        dr = nil; }

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

char pbuff[BMAX];
T tb[NMAX];

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

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

    return pbuff[ 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'); }

inline int newT(const int &val) {
    static int bp = 0;
    tb[++bp] = T(val);
    return bp; }

int join(const int &a, const int &b) {
    if (!a) return b;
    if (!b) return a;

    if (tb[a].pr >= tb[b].pr) {
        tb[a].dr = join(tb[a].dr, b);
        return a; }
    else {
        tb[b].st = join(a, tb[b].st);
        return b; } }

int join3(const int &a, const int &b, const int &c) {
    return join(a, join(b, c)); }

PII split(const int &nod, const int &val) {
    if (nod == 0) return {0, 0};

    if (tb[nod].key <= val) {
        PII tmp = split(tb[nod].dr, val);
        tb[nod].dr = tmp.x;
        return {nod, tmp.y}; }
    else {
        PII tmp = split(tb[nod].st, val);
        tb[nod].st = tmp.y;
        return {tmp.x, nod}; } }

void dfs(const int &nod) {
    if (tb[nod].st) dfs(tb[nod].st);
    printf("%d ", tb[nod].key);
    if (tb[nod].dr) dfs(tb[nod].dr); }

inline int insert(const int &nod, const int &val) {
    PII tmp = split(nod, val);
    return join3(tmp.x, newT(val), tmp.y); }

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

    tb[0].st = 0;
    tb[0].dr = 0;
    tb[0].pr = -1;
    root = nil;

    get(n);
    for (int i = 0; i < n; ++i) {
        get(t);
        root = insert(root, t); }

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

    fprintf(stderr, "%d\n", sizeof(tb) + sizeof(pbuff) + sizeof(*stdin) + sizeof(*stdout));

    return 0; }