Cod sursa(job #1852475)

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

const int NMAX = 5e5 + 5,
          BMAX = 4096,
           nil = 0;

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

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

    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(int val) {
    static int bp = 0;
    tb[++bp] = T(val);
    return bp; }

int join(int a, 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(int a, int b, int c) {
    return join(a, join(b, c)); }

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

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

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

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

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));

    return 0; }