Cod sursa(job #1837795)

Utilizator depevladVlad Dumitru-Popescu depevlad Data 30 decembrie 2016 14:32:53
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 500005;
const int SQRT = 1 << 16;
const int BUFFSIZE = (1 << 13);

inline char getChar() {
    static char buff[BUFFSIZE];
    static int pos = 0;
    if (pos == BUFFSIZE) {
        fread(buff, 1, BUFFSIZE, stdin);
        pos = 0;
    }
    return buff[pos++];
}

inline int readInt() {
    int q = 0;
    char c;
    do {
        c = getChar();
    } while (!isdigit(c));
    do {
        q = (q << 1) + (q << 3) + (c - '0');
        c = getChar();
    } while (isdigit(c));
    return q;
}

char buf[BUFFSIZE];
int ptr = 0;

inline void putChar(const char &ch) {
    buf[ptr++] = ch;
    if (ptr == BUFFSIZE) {
        fwrite(buf, 1, BUFFSIZE, stdout);
        ptr = 0;
    }
}

inline void writeInt(int x) {
    char digs[10];
    int n = 0, q;
    do {
        q = x / 10;
        digs[n++] = x - (q << 1) - (q << 3) + '0';
        x = q;
    } while (x);
    while (n--) {
        putChar(digs[n]);
    }
    putChar(' ');
}

int n, c;
int fi[2 * SQRT + 1];
int v[NMAX];
int nxt[NMAX];

void bucketSort() {
    memset(fi, -1, sizeof fi);
    n = readInt();
    for (int i = 1; i <= n; i++) {
        v[i] = readInt();
        int j = v[i] % SQRT;
        nxt[i] = fi[j];
        fi[j] = i;
    }
    for (int i = SQRT - 1; i >= 0; i--) {
        int j = fi[i];
        while (j != -1) {
            int _nxt = nxt[j];
            int k = v[j] / SQRT + SQRT;
            nxt[j] = fi[k];
            fi[k] = j;
            j = _nxt;
        }
    }
    for (int i = SQRT; i <= 2 * SQRT; i++) {
        for (int j = fi[i]; j != -1; j = nxt[j]) {
            writeInt(v[j]);
        }
    }
    fwrite(buf, 1, ptr, stdout);
}

int main() {
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);
    bucketSort();
    return 0;
}